@mcp-ts/sdk 1.0.1 → 1.2.0

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.
Files changed (83) hide show
  1. package/README.md +42 -19
  2. package/dist/adapters/agui-adapter.d.mts +6 -6
  3. package/dist/adapters/agui-adapter.d.ts +6 -6
  4. package/dist/adapters/agui-adapter.js +50 -25
  5. package/dist/adapters/agui-adapter.js.map +1 -1
  6. package/dist/adapters/agui-adapter.mjs +50 -25
  7. package/dist/adapters/agui-adapter.mjs.map +1 -1
  8. package/dist/adapters/agui-middleware.d.mts +23 -8
  9. package/dist/adapters/agui-middleware.d.ts +23 -8
  10. package/dist/adapters/agui-middleware.js +71 -43
  11. package/dist/adapters/agui-middleware.js.map +1 -1
  12. package/dist/adapters/agui-middleware.mjs +71 -44
  13. package/dist/adapters/agui-middleware.mjs.map +1 -1
  14. package/dist/adapters/ai-adapter.d.mts +2 -2
  15. package/dist/adapters/ai-adapter.d.ts +2 -2
  16. package/dist/adapters/langchain-adapter.d.mts +2 -2
  17. package/dist/adapters/langchain-adapter.d.ts +2 -2
  18. package/dist/adapters/mastra-adapter.d.mts +2 -2
  19. package/dist/adapters/mastra-adapter.d.ts +2 -2
  20. package/dist/client/index.d.mts +182 -55
  21. package/dist/client/index.d.ts +182 -55
  22. package/dist/client/index.js +535 -130
  23. package/dist/client/index.js.map +1 -1
  24. package/dist/client/index.mjs +535 -131
  25. package/dist/client/index.mjs.map +1 -1
  26. package/dist/client/react.d.mts +386 -4
  27. package/dist/client/react.d.ts +386 -4
  28. package/dist/client/react.js +890 -143
  29. package/dist/client/react.js.map +1 -1
  30. package/dist/client/react.mjs +883 -145
  31. package/dist/client/react.mjs.map +1 -1
  32. package/dist/client/vue.d.mts +3 -3
  33. package/dist/client/vue.d.ts +3 -3
  34. package/dist/client/vue.js +546 -141
  35. package/dist/client/vue.js.map +1 -1
  36. package/dist/client/vue.mjs +546 -142
  37. package/dist/client/vue.mjs.map +1 -1
  38. package/dist/{events-BP6WyRNh.d.mts → events-BgeztGYZ.d.mts} +12 -1
  39. package/dist/{events-BP6WyRNh.d.ts → events-BgeztGYZ.d.ts} +12 -1
  40. package/dist/index.d.mts +4 -4
  41. package/dist/index.d.ts +4 -4
  42. package/dist/index.js +797 -248
  43. package/dist/index.js.map +1 -1
  44. package/dist/index.mjs +791 -245
  45. package/dist/index.mjs.map +1 -1
  46. package/dist/{multi-session-client-DMF3ED2O.d.mts → multi-session-client-CxogNckF.d.mts} +1 -1
  47. package/dist/{multi-session-client-BOFgPypS.d.ts → multi-session-client-cox_WXUj.d.ts} +1 -1
  48. package/dist/server/index.d.mts +41 -37
  49. package/dist/server/index.d.ts +41 -37
  50. package/dist/server/index.js +241 -116
  51. package/dist/server/index.js.map +1 -1
  52. package/dist/server/index.mjs +237 -112
  53. package/dist/server/index.mjs.map +1 -1
  54. package/dist/shared/index.d.mts +39 -3
  55. package/dist/shared/index.d.ts +39 -3
  56. package/dist/shared/index.js +19 -0
  57. package/dist/shared/index.js.map +1 -1
  58. package/dist/shared/index.mjs +18 -1
  59. package/dist/shared/index.mjs.map +1 -1
  60. package/package.json +9 -2
  61. package/src/adapters/agui-adapter.ts +58 -35
  62. package/src/adapters/agui-middleware.ts +83 -45
  63. package/src/client/core/app-host.ts +417 -0
  64. package/src/client/core/sse-client.ts +365 -212
  65. package/src/client/core/types.ts +31 -0
  66. package/src/client/index.ts +1 -0
  67. package/src/client/react/agui-subscriber.ts +275 -0
  68. package/src/client/react/index.ts +23 -3
  69. package/src/client/react/use-agui-subscriber.ts +270 -0
  70. package/src/client/react/use-app-host.ts +73 -0
  71. package/src/client/react/use-mcp-app-iframe.ts +164 -0
  72. package/src/client/react/{useMcp.ts → use-mcp.ts} +18 -0
  73. package/src/client/vue/index.ts +1 -1
  74. package/src/server/handlers/nextjs-handler.ts +8 -7
  75. package/src/server/handlers/sse-handler.ts +129 -165
  76. package/src/server/mcp/oauth-client.ts +32 -2
  77. package/src/server/storage/index.ts +17 -1
  78. package/src/server/storage/sqlite-backend.ts +185 -0
  79. package/src/shared/events.ts +12 -0
  80. package/src/shared/index.ts +6 -1
  81. package/src/shared/tool-utils.ts +61 -0
  82. package/src/shared/types.ts +3 -1
  83. /package/src/client/vue/{useMcp.ts → use-mcp.ts} +0 -0
@@ -1,119 +1,246 @@
1
- import { M as McpConnectionEvent, d as McpObservabilityEvent } from '../events-BP6WyRNh.mjs';
2
- export { D as Disposable, a as DisposableStore, E as Emitter, b as Event, c as McpConnectionState } from '../events-BP6WyRNh.mjs';
1
+ import { M as McpConnectionEvent, d as McpObservabilityEvent, e as McpAppsUIEvent } from '../events-BgeztGYZ.mjs';
2
+ export { D as Disposable, a as DisposableStore, E as Emitter, b as Event, c as McpConnectionState } from '../events-BgeztGYZ.mjs';
3
3
  import { s as SessionListResult, e as ConnectParams, h as ConnectResult, j as DisconnectResult, n as ListToolsRpcResult, r as RestoreSessionResult, k as FinishAuthResult, L as ListPromptsResult, l as ListResourcesResult } from '../types-CLccx9wW.mjs';
4
4
  export { p as McpRpcRequest, q as McpRpcResponse, T as ToolInfo } from '../types-CLccx9wW.mjs';
5
5
  import '@modelcontextprotocol/sdk/types.js';
6
6
 
7
7
  /**
8
8
  * SSE Client for MCP Connections
9
- * Browser-side client that connects to SSE endpoint
9
+ *
10
+ * Browser-side client that manages real-time communication with the MCP server
11
+ * using Server-Sent Events (SSE) for server→client streaming and HTTP POST for
12
+ * client→server RPC requests.
13
+ *
14
+ * Key features:
15
+ * - Direct HTTP response for RPC calls (bypasses SSE latency)
16
+ * - Resource preloading for instant MCP App UI loading
17
+ * - Automatic reconnection with exponential backoff
18
+ * - Type-safe RPC methods
10
19
  */
11
20
 
12
21
  interface SSEClientOptions {
13
- /**
14
- * SSE endpoint URL
15
- */
22
+ /** SSE endpoint URL */
16
23
  url: string;
17
- /**
18
- * User/Client identifier
19
- */
24
+ /** User/Client identifier */
20
25
  identity: string;
21
- /**
22
- * Optional auth token
23
- */
26
+ /** Optional auth token for authenticated requests */
24
27
  authToken?: string;
25
- /**
26
- * Connection event callback
27
- */
28
+ /** Callback for MCP connection state changes */
28
29
  onConnectionEvent?: (event: McpConnectionEvent) => void;
29
- /**
30
- * Observability event callback
31
- */
30
+ /** Callback for observability/logging events */
32
31
  onObservabilityEvent?: (event: McpObservabilityEvent) => void;
33
- /**
34
- * Connection status callback
35
- */
36
- onStatusChange?: (status: 'connecting' | 'connected' | 'disconnected' | 'error') => void;
32
+ /** Callback for connection status changes */
33
+ onStatusChange?: (status: ConnectionStatus) => void;
34
+ /** Callback for MCP App UI events */
35
+ onEvent?: (event: McpAppsUIEvent) => void;
36
+ /** Request timeout in milliseconds @default 60000 */
37
+ requestTimeout?: number;
38
+ /** Enable debug logging @default false */
39
+ debug?: boolean;
37
40
  }
41
+ type ConnectionStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
38
42
  /**
39
43
  * SSE Client for real-time MCP connection management
40
44
  */
41
45
  declare class SSEClient {
42
- private options;
46
+ private readonly options;
43
47
  private eventSource;
44
48
  private pendingRequests;
49
+ private resourceCache;
45
50
  private reconnectAttempts;
46
- private maxReconnectAttempts;
47
- private reconnectDelay;
48
51
  private isManuallyDisconnected;
49
52
  private connectionPromise;
50
53
  private connectionResolver;
51
54
  constructor(options: SSEClientOptions);
52
55
  /**
53
- * Connect to SSE endpoint
56
+ * Connect to the SSE endpoint
54
57
  */
55
58
  connect(): void;
56
59
  /**
57
- * Disconnect from SSE endpoint
60
+ * Disconnect from the SSE endpoint
58
61
  */
59
62
  disconnect(): void;
60
63
  /**
61
- * Send RPC request via SSE
62
- * Note: SSE is unidirectional (server->client), so we need to send requests via POST
64
+ * Check if connected to the SSE endpoint
65
+ */
66
+ isConnected(): boolean;
67
+ getSessions(): Promise<SessionListResult>;
68
+ connectToServer(params: ConnectParams): Promise<ConnectResult>;
69
+ disconnectFromServer(sessionId: string): Promise<DisconnectResult>;
70
+ listTools(sessionId: string): Promise<ListToolsRpcResult>;
71
+ callTool(sessionId: string, toolName: string, toolArgs: Record<string, unknown>): Promise<unknown>;
72
+ restoreSession(sessionId: string): Promise<RestoreSessionResult>;
73
+ finishAuth(sessionId: string, code: string): Promise<FinishAuthResult>;
74
+ listPrompts(sessionId: string): Promise<ListPromptsResult>;
75
+ getPrompt(sessionId: string, name: string, args?: Record<string, string>): Promise<unknown>;
76
+ listResources(sessionId: string): Promise<ListResourcesResult>;
77
+ readResource(sessionId: string, uri: string): Promise<unknown>;
78
+ /**
79
+ * Preload UI resources for tools that have UI metadata.
80
+ * Call this when tools are discovered to enable instant MCP App UI loading.
81
+ */
82
+ preloadToolUiResources(sessionId: string, tools: Array<{
83
+ name: string;
84
+ _meta?: unknown;
85
+ }>): void;
86
+ /**
87
+ * Get a preloaded resource from cache, or fetch if not cached.
88
+ */
89
+ getOrFetchResource(sessionId: string, uri: string): Promise<unknown>;
90
+ /**
91
+ * Check if a resource is already cached
92
+ */
93
+ hasPreloadedResource(uri: string): boolean;
94
+ /**
95
+ * Clear the resource cache
96
+ */
97
+ clearResourceCache(): void;
98
+ /**
99
+ * Send an RPC request and return the response directly from HTTP.
100
+ * This bypasses SSE latency by returning results in the HTTP response body.
63
101
  */
64
102
  private sendRequest;
65
103
  /**
66
- * Handle RPC response
104
+ * Parse RPC response and handle different response formats
67
105
  */
68
- private handleRpcResponse;
106
+ private parseRpcResponse;
69
107
  /**
70
- * Get all user sessions
108
+ * Wait for RPC response via SSE (legacy fallback)
71
109
  */
72
- getSessions(): Promise<SessionListResult>;
110
+ private waitForSseResponse;
73
111
  /**
74
- * Connect to an MCP server
112
+ * Handle RPC response received via SSE (legacy)
75
113
  */
76
- connectToServer(params: ConnectParams): Promise<ConnectResult>;
114
+ private handleRpcResponse;
115
+ private setupEventListeners;
116
+ private attemptReconnect;
117
+ private buildUrl;
118
+ private buildHeaders;
119
+ private rejectAllPendingRequests;
120
+ private extractUiResourceUri;
121
+ private emitUiEventIfPresent;
122
+ private log;
123
+ }
124
+
125
+ /**
126
+ * Abstraction layer for the AppHost's network communication.
127
+ *
128
+ * This interface decouples the `AppHost` from the concrete networking implementation (like `SSEClient`).
129
+ * Implementation can be:
130
+ * 1. `SSEClient`: Direct connection to MCP Server (Browser -> Server).
131
+ * 2. `ProxyClient`: Connection via an intermediary API (Browser -> Next.js API -> Server).
132
+ */
133
+ interface AppHostClient {
77
134
  /**
78
- * Disconnect from an MCP server
135
+ * Check if the client is connected
79
136
  */
80
- disconnectFromServer(sessionId: string): Promise<DisconnectResult>;
137
+ isConnected(): boolean;
81
138
  /**
82
- * List tools from a session
139
+ * Get list of active sessions
83
140
  */
84
- listTools(sessionId: string): Promise<ListToolsRpcResult>;
141
+ getSessions(): Promise<SessionListResult>;
85
142
  /**
86
- * Call a tool
143
+ * Call a tool on a specific session
87
144
  */
88
145
  callTool(sessionId: string, toolName: string, toolArgs: Record<string, unknown>): Promise<unknown>;
89
146
  /**
90
- * Refresh/validate a session
147
+ * Read a resource from a specific session
91
148
  */
92
- restoreSession(sessionId: string): Promise<RestoreSessionResult>;
149
+ readResource(sessionId: string, uri: string): Promise<unknown>;
150
+ }
151
+
152
+ /**
153
+ * MCP App Host
154
+ *
155
+ * Bridges the gap between an iframe (MCP App) and the SSEClient (MCP Server).
156
+ * Handles secure iframe sandboxing, resource loading, and bi-directional
157
+ * communication via the AppBridge protocol.
158
+ *
159
+ * Key features:
160
+ * - Secure iframe sandboxing with minimal permissions
161
+ * - Resource preloading for instant MCP App UI loading
162
+ * - Cache-aware resource fetching (SSEClient cache → local cache → direct fetch)
163
+ * - Support for ui:// and mcp-app:// resource URIs
164
+ */
165
+
166
+ interface AppHostOptions {
167
+ /** Enable debug logging @default false */
168
+ debug?: boolean;
169
+ }
170
+ interface AppMessageParams {
171
+ role: string;
172
+ content: unknown;
173
+ }
174
+ /**
175
+ * Host for MCP Apps embedded in iframes.
176
+ * Manages secure communication between the app and the MCP server.
177
+ */
178
+ declare class AppHost {
179
+ private readonly client;
180
+ private readonly iframe;
181
+ private bridge;
182
+ private sessionId?;
183
+ private resourceCache;
184
+ private debug;
185
+ /** Callback for app messages (e.g., chat messages from the app) */
186
+ onAppMessage?: (params: AppMessageParams) => void;
187
+ constructor(client: AppHostClient, iframe: HTMLIFrameElement, options?: AppHostOptions);
93
188
  /**
94
- * Complete OAuth authorization
189
+ * Start the host. This prepares the bridge handlers but doesn't connect yet.
190
+ * The actual connection happens in launch() after HTML is loaded.
191
+ * @returns Promise that resolves immediately (bridge connects during launch)
95
192
  */
96
- finishAuth(sessionId: string, code: string): Promise<FinishAuthResult>;
193
+ start(): Promise<void>;
97
194
  /**
98
- * List available prompts
195
+ * Preload UI resources to enable instant app loading.
196
+ * Call this when tools are discovered to cache their UI resources.
99
197
  */
100
- listPrompts(sessionId: string): Promise<ListPromptsResult>;
198
+ preload(tools: Array<{
199
+ _meta?: unknown;
200
+ }>): void;
101
201
  /**
102
- * Get a specific prompt with arguments
202
+ * Launch an MCP App from a URL or MCP resource URI.
203
+ * Loads the HTML first, then establishes bridge connection.
103
204
  */
104
- getPrompt(sessionId: string, name: string, args?: Record<string, string>): Promise<unknown>;
205
+ launch(url: string, sessionId?: string): Promise<void>;
105
206
  /**
106
- * List available resources
207
+ * Wait for app to signal initialization complete
107
208
  */
108
- listResources(sessionId: string): Promise<ListResourcesResult>;
209
+ private onAppReady;
109
210
  /**
110
- * Read a specific resource
211
+ * Wait for iframe to finish loading
111
212
  */
112
- readResource(sessionId: string, uri: string): Promise<unknown>;
213
+ private onIframeReady;
113
214
  /**
114
- * Check if connected
215
+ * Send tool input arguments to the MCP App.
216
+ * Call this after launch() when tool input is available.
115
217
  */
116
- isConnected(): boolean;
218
+ sendToolInput(args: Record<string, unknown>): void;
219
+ /**
220
+ * Send tool result to the MCP App.
221
+ * Call this when the tool call completes.
222
+ */
223
+ sendToolResult(result: unknown): void;
224
+ /**
225
+ * Send tool cancellation to the MCP App.
226
+ * Call this when the tool call is cancelled or fails.
227
+ */
228
+ sendToolCancelled(reason: string): void;
229
+ private configureSandbox;
230
+ private initializeBridge;
231
+ private connectBridge;
232
+ private handleToolCall;
233
+ private handleOpenLink;
234
+ private handleMessage;
235
+ private launchMcpApp;
236
+ private fetchResourceWithCache;
237
+ private preloadResource;
238
+ private getSessionId;
239
+ private isMcpUri;
240
+ private hasClientCache;
241
+ private extractUiResourceUri;
242
+ private decodeContent;
243
+ private log;
117
244
  }
118
245
 
119
- export { McpConnectionEvent, McpObservabilityEvent, SSEClient, type SSEClientOptions };
246
+ export { AppHost, McpConnectionEvent, McpObservabilityEvent, SSEClient, type SSEClientOptions };
@@ -1,119 +1,246 @@
1
- import { M as McpConnectionEvent, d as McpObservabilityEvent } from '../events-BP6WyRNh.js';
2
- export { D as Disposable, a as DisposableStore, E as Emitter, b as Event, c as McpConnectionState } from '../events-BP6WyRNh.js';
1
+ import { M as McpConnectionEvent, d as McpObservabilityEvent, e as McpAppsUIEvent } from '../events-BgeztGYZ.js';
2
+ export { D as Disposable, a as DisposableStore, E as Emitter, b as Event, c as McpConnectionState } from '../events-BgeztGYZ.js';
3
3
  import { s as SessionListResult, e as ConnectParams, h as ConnectResult, j as DisconnectResult, n as ListToolsRpcResult, r as RestoreSessionResult, k as FinishAuthResult, L as ListPromptsResult, l as ListResourcesResult } from '../types-CLccx9wW.js';
4
4
  export { p as McpRpcRequest, q as McpRpcResponse, T as ToolInfo } from '../types-CLccx9wW.js';
5
5
  import '@modelcontextprotocol/sdk/types.js';
6
6
 
7
7
  /**
8
8
  * SSE Client for MCP Connections
9
- * Browser-side client that connects to SSE endpoint
9
+ *
10
+ * Browser-side client that manages real-time communication with the MCP server
11
+ * using Server-Sent Events (SSE) for server→client streaming and HTTP POST for
12
+ * client→server RPC requests.
13
+ *
14
+ * Key features:
15
+ * - Direct HTTP response for RPC calls (bypasses SSE latency)
16
+ * - Resource preloading for instant MCP App UI loading
17
+ * - Automatic reconnection with exponential backoff
18
+ * - Type-safe RPC methods
10
19
  */
11
20
 
12
21
  interface SSEClientOptions {
13
- /**
14
- * SSE endpoint URL
15
- */
22
+ /** SSE endpoint URL */
16
23
  url: string;
17
- /**
18
- * User/Client identifier
19
- */
24
+ /** User/Client identifier */
20
25
  identity: string;
21
- /**
22
- * Optional auth token
23
- */
26
+ /** Optional auth token for authenticated requests */
24
27
  authToken?: string;
25
- /**
26
- * Connection event callback
27
- */
28
+ /** Callback for MCP connection state changes */
28
29
  onConnectionEvent?: (event: McpConnectionEvent) => void;
29
- /**
30
- * Observability event callback
31
- */
30
+ /** Callback for observability/logging events */
32
31
  onObservabilityEvent?: (event: McpObservabilityEvent) => void;
33
- /**
34
- * Connection status callback
35
- */
36
- onStatusChange?: (status: 'connecting' | 'connected' | 'disconnected' | 'error') => void;
32
+ /** Callback for connection status changes */
33
+ onStatusChange?: (status: ConnectionStatus) => void;
34
+ /** Callback for MCP App UI events */
35
+ onEvent?: (event: McpAppsUIEvent) => void;
36
+ /** Request timeout in milliseconds @default 60000 */
37
+ requestTimeout?: number;
38
+ /** Enable debug logging @default false */
39
+ debug?: boolean;
37
40
  }
41
+ type ConnectionStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
38
42
  /**
39
43
  * SSE Client for real-time MCP connection management
40
44
  */
41
45
  declare class SSEClient {
42
- private options;
46
+ private readonly options;
43
47
  private eventSource;
44
48
  private pendingRequests;
49
+ private resourceCache;
45
50
  private reconnectAttempts;
46
- private maxReconnectAttempts;
47
- private reconnectDelay;
48
51
  private isManuallyDisconnected;
49
52
  private connectionPromise;
50
53
  private connectionResolver;
51
54
  constructor(options: SSEClientOptions);
52
55
  /**
53
- * Connect to SSE endpoint
56
+ * Connect to the SSE endpoint
54
57
  */
55
58
  connect(): void;
56
59
  /**
57
- * Disconnect from SSE endpoint
60
+ * Disconnect from the SSE endpoint
58
61
  */
59
62
  disconnect(): void;
60
63
  /**
61
- * Send RPC request via SSE
62
- * Note: SSE is unidirectional (server->client), so we need to send requests via POST
64
+ * Check if connected to the SSE endpoint
65
+ */
66
+ isConnected(): boolean;
67
+ getSessions(): Promise<SessionListResult>;
68
+ connectToServer(params: ConnectParams): Promise<ConnectResult>;
69
+ disconnectFromServer(sessionId: string): Promise<DisconnectResult>;
70
+ listTools(sessionId: string): Promise<ListToolsRpcResult>;
71
+ callTool(sessionId: string, toolName: string, toolArgs: Record<string, unknown>): Promise<unknown>;
72
+ restoreSession(sessionId: string): Promise<RestoreSessionResult>;
73
+ finishAuth(sessionId: string, code: string): Promise<FinishAuthResult>;
74
+ listPrompts(sessionId: string): Promise<ListPromptsResult>;
75
+ getPrompt(sessionId: string, name: string, args?: Record<string, string>): Promise<unknown>;
76
+ listResources(sessionId: string): Promise<ListResourcesResult>;
77
+ readResource(sessionId: string, uri: string): Promise<unknown>;
78
+ /**
79
+ * Preload UI resources for tools that have UI metadata.
80
+ * Call this when tools are discovered to enable instant MCP App UI loading.
81
+ */
82
+ preloadToolUiResources(sessionId: string, tools: Array<{
83
+ name: string;
84
+ _meta?: unknown;
85
+ }>): void;
86
+ /**
87
+ * Get a preloaded resource from cache, or fetch if not cached.
88
+ */
89
+ getOrFetchResource(sessionId: string, uri: string): Promise<unknown>;
90
+ /**
91
+ * Check if a resource is already cached
92
+ */
93
+ hasPreloadedResource(uri: string): boolean;
94
+ /**
95
+ * Clear the resource cache
96
+ */
97
+ clearResourceCache(): void;
98
+ /**
99
+ * Send an RPC request and return the response directly from HTTP.
100
+ * This bypasses SSE latency by returning results in the HTTP response body.
63
101
  */
64
102
  private sendRequest;
65
103
  /**
66
- * Handle RPC response
104
+ * Parse RPC response and handle different response formats
67
105
  */
68
- private handleRpcResponse;
106
+ private parseRpcResponse;
69
107
  /**
70
- * Get all user sessions
108
+ * Wait for RPC response via SSE (legacy fallback)
71
109
  */
72
- getSessions(): Promise<SessionListResult>;
110
+ private waitForSseResponse;
73
111
  /**
74
- * Connect to an MCP server
112
+ * Handle RPC response received via SSE (legacy)
75
113
  */
76
- connectToServer(params: ConnectParams): Promise<ConnectResult>;
114
+ private handleRpcResponse;
115
+ private setupEventListeners;
116
+ private attemptReconnect;
117
+ private buildUrl;
118
+ private buildHeaders;
119
+ private rejectAllPendingRequests;
120
+ private extractUiResourceUri;
121
+ private emitUiEventIfPresent;
122
+ private log;
123
+ }
124
+
125
+ /**
126
+ * Abstraction layer for the AppHost's network communication.
127
+ *
128
+ * This interface decouples the `AppHost` from the concrete networking implementation (like `SSEClient`).
129
+ * Implementation can be:
130
+ * 1. `SSEClient`: Direct connection to MCP Server (Browser -> Server).
131
+ * 2. `ProxyClient`: Connection via an intermediary API (Browser -> Next.js API -> Server).
132
+ */
133
+ interface AppHostClient {
77
134
  /**
78
- * Disconnect from an MCP server
135
+ * Check if the client is connected
79
136
  */
80
- disconnectFromServer(sessionId: string): Promise<DisconnectResult>;
137
+ isConnected(): boolean;
81
138
  /**
82
- * List tools from a session
139
+ * Get list of active sessions
83
140
  */
84
- listTools(sessionId: string): Promise<ListToolsRpcResult>;
141
+ getSessions(): Promise<SessionListResult>;
85
142
  /**
86
- * Call a tool
143
+ * Call a tool on a specific session
87
144
  */
88
145
  callTool(sessionId: string, toolName: string, toolArgs: Record<string, unknown>): Promise<unknown>;
89
146
  /**
90
- * Refresh/validate a session
147
+ * Read a resource from a specific session
91
148
  */
92
- restoreSession(sessionId: string): Promise<RestoreSessionResult>;
149
+ readResource(sessionId: string, uri: string): Promise<unknown>;
150
+ }
151
+
152
+ /**
153
+ * MCP App Host
154
+ *
155
+ * Bridges the gap between an iframe (MCP App) and the SSEClient (MCP Server).
156
+ * Handles secure iframe sandboxing, resource loading, and bi-directional
157
+ * communication via the AppBridge protocol.
158
+ *
159
+ * Key features:
160
+ * - Secure iframe sandboxing with minimal permissions
161
+ * - Resource preloading for instant MCP App UI loading
162
+ * - Cache-aware resource fetching (SSEClient cache → local cache → direct fetch)
163
+ * - Support for ui:// and mcp-app:// resource URIs
164
+ */
165
+
166
+ interface AppHostOptions {
167
+ /** Enable debug logging @default false */
168
+ debug?: boolean;
169
+ }
170
+ interface AppMessageParams {
171
+ role: string;
172
+ content: unknown;
173
+ }
174
+ /**
175
+ * Host for MCP Apps embedded in iframes.
176
+ * Manages secure communication between the app and the MCP server.
177
+ */
178
+ declare class AppHost {
179
+ private readonly client;
180
+ private readonly iframe;
181
+ private bridge;
182
+ private sessionId?;
183
+ private resourceCache;
184
+ private debug;
185
+ /** Callback for app messages (e.g., chat messages from the app) */
186
+ onAppMessage?: (params: AppMessageParams) => void;
187
+ constructor(client: AppHostClient, iframe: HTMLIFrameElement, options?: AppHostOptions);
93
188
  /**
94
- * Complete OAuth authorization
189
+ * Start the host. This prepares the bridge handlers but doesn't connect yet.
190
+ * The actual connection happens in launch() after HTML is loaded.
191
+ * @returns Promise that resolves immediately (bridge connects during launch)
95
192
  */
96
- finishAuth(sessionId: string, code: string): Promise<FinishAuthResult>;
193
+ start(): Promise<void>;
97
194
  /**
98
- * List available prompts
195
+ * Preload UI resources to enable instant app loading.
196
+ * Call this when tools are discovered to cache their UI resources.
99
197
  */
100
- listPrompts(sessionId: string): Promise<ListPromptsResult>;
198
+ preload(tools: Array<{
199
+ _meta?: unknown;
200
+ }>): void;
101
201
  /**
102
- * Get a specific prompt with arguments
202
+ * Launch an MCP App from a URL or MCP resource URI.
203
+ * Loads the HTML first, then establishes bridge connection.
103
204
  */
104
- getPrompt(sessionId: string, name: string, args?: Record<string, string>): Promise<unknown>;
205
+ launch(url: string, sessionId?: string): Promise<void>;
105
206
  /**
106
- * List available resources
207
+ * Wait for app to signal initialization complete
107
208
  */
108
- listResources(sessionId: string): Promise<ListResourcesResult>;
209
+ private onAppReady;
109
210
  /**
110
- * Read a specific resource
211
+ * Wait for iframe to finish loading
111
212
  */
112
- readResource(sessionId: string, uri: string): Promise<unknown>;
213
+ private onIframeReady;
113
214
  /**
114
- * Check if connected
215
+ * Send tool input arguments to the MCP App.
216
+ * Call this after launch() when tool input is available.
115
217
  */
116
- isConnected(): boolean;
218
+ sendToolInput(args: Record<string, unknown>): void;
219
+ /**
220
+ * Send tool result to the MCP App.
221
+ * Call this when the tool call completes.
222
+ */
223
+ sendToolResult(result: unknown): void;
224
+ /**
225
+ * Send tool cancellation to the MCP App.
226
+ * Call this when the tool call is cancelled or fails.
227
+ */
228
+ sendToolCancelled(reason: string): void;
229
+ private configureSandbox;
230
+ private initializeBridge;
231
+ private connectBridge;
232
+ private handleToolCall;
233
+ private handleOpenLink;
234
+ private handleMessage;
235
+ private launchMcpApp;
236
+ private fetchResourceWithCache;
237
+ private preloadResource;
238
+ private getSessionId;
239
+ private isMcpUri;
240
+ private hasClientCache;
241
+ private extractUiResourceUri;
242
+ private decodeContent;
243
+ private log;
117
244
  }
118
245
 
119
- export { McpConnectionEvent, McpObservabilityEvent, SSEClient, type SSEClientOptions };
246
+ export { AppHost, McpConnectionEvent, McpObservabilityEvent, SSEClient, type SSEClientOptions };