@mcp-web/core 0.1.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 (102) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +253 -0
  3. package/dist/addTool.typetest.d.ts +11 -0
  4. package/dist/addTool.typetest.d.ts.map +1 -0
  5. package/dist/addTool.typetest.js +248 -0
  6. package/dist/create-state-tools.d.ts +77 -0
  7. package/dist/create-state-tools.d.ts.map +1 -0
  8. package/dist/create-state-tools.js +181 -0
  9. package/dist/create-tool.d.ts +90 -0
  10. package/dist/create-tool.d.ts.map +1 -0
  11. package/dist/create-tool.js +82 -0
  12. package/dist/expanded-schema-tools/generate-fixed-shape-tools.d.ts +8 -0
  13. package/dist/expanded-schema-tools/generate-fixed-shape-tools.d.ts.map +1 -0
  14. package/dist/expanded-schema-tools/generate-fixed-shape-tools.js +53 -0
  15. package/dist/expanded-schema-tools/generate-fixed-shape-tools.test.d.ts +2 -0
  16. package/dist/expanded-schema-tools/generate-fixed-shape-tools.test.d.ts.map +1 -0
  17. package/dist/expanded-schema-tools/generate-fixed-shape-tools.test.js +331 -0
  18. package/dist/expanded-schema-tools/index.d.ts +4 -0
  19. package/dist/expanded-schema-tools/index.d.ts.map +1 -0
  20. package/dist/expanded-schema-tools/index.js +2 -0
  21. package/dist/expanded-schema-tools/integration.test.d.ts +2 -0
  22. package/dist/expanded-schema-tools/integration.test.d.ts.map +1 -0
  23. package/dist/expanded-schema-tools/integration.test.js +599 -0
  24. package/dist/expanded-schema-tools/schema-analysis.d.ts +18 -0
  25. package/dist/expanded-schema-tools/schema-analysis.d.ts.map +1 -0
  26. package/dist/expanded-schema-tools/schema-analysis.js +142 -0
  27. package/dist/expanded-schema-tools/schema-analysis.test.d.ts +2 -0
  28. package/dist/expanded-schema-tools/schema-analysis.test.d.ts.map +1 -0
  29. package/dist/expanded-schema-tools/schema-analysis.test.js +314 -0
  30. package/dist/expanded-schema-tools/schema-helpers.d.ts +69 -0
  31. package/dist/expanded-schema-tools/schema-helpers.d.ts.map +1 -0
  32. package/dist/expanded-schema-tools/schema-helpers.js +139 -0
  33. package/dist/expanded-schema-tools/schema-helpers.test.d.ts +2 -0
  34. package/dist/expanded-schema-tools/schema-helpers.test.d.ts.map +1 -0
  35. package/dist/expanded-schema-tools/schema-helpers.test.js +223 -0
  36. package/dist/expanded-schema-tools/tool-generator.d.ts +10 -0
  37. package/dist/expanded-schema-tools/tool-generator.d.ts.map +1 -0
  38. package/dist/expanded-schema-tools/tool-generator.js +430 -0
  39. package/dist/expanded-schema-tools/tool-generator.test.d.ts +2 -0
  40. package/dist/expanded-schema-tools/tool-generator.test.d.ts.map +1 -0
  41. package/dist/expanded-schema-tools/tool-generator.test.js +689 -0
  42. package/dist/expanded-schema-tools/types.d.ts +26 -0
  43. package/dist/expanded-schema-tools/types.d.ts.map +1 -0
  44. package/dist/expanded-schema-tools/types.js +1 -0
  45. package/dist/expanded-schema-tools/utils.d.ts +16 -0
  46. package/dist/expanded-schema-tools/utils.d.ts.map +1 -0
  47. package/dist/expanded-schema-tools/utils.js +35 -0
  48. package/dist/expanded-schema-tools/utils.test.d.ts +2 -0
  49. package/dist/expanded-schema-tools/utils.test.d.ts.map +1 -0
  50. package/dist/expanded-schema-tools/utils.test.js +169 -0
  51. package/dist/group-state.d.ts +60 -0
  52. package/dist/group-state.d.ts.map +1 -0
  53. package/dist/group-state.js +54 -0
  54. package/dist/index.d.ts +14 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.js +13 -0
  57. package/dist/query.d.ts +104 -0
  58. package/dist/query.d.ts.map +1 -0
  59. package/dist/query.js +128 -0
  60. package/dist/schema-helpers.d.ts +69 -0
  61. package/dist/schema-helpers.d.ts.map +1 -0
  62. package/dist/schema-helpers.js +139 -0
  63. package/dist/schemas.d.ts +140 -0
  64. package/dist/schemas.d.ts.map +1 -0
  65. package/dist/schemas.js +70 -0
  66. package/dist/tool-generators/generate-basic-state-tools.d.ts +23 -0
  67. package/dist/tool-generators/generate-basic-state-tools.d.ts.map +1 -0
  68. package/dist/tool-generators/generate-basic-state-tools.js +95 -0
  69. package/dist/tool-generators/generate-fixed-shape-tools.d.ts +8 -0
  70. package/dist/tool-generators/generate-fixed-shape-tools.d.ts.map +1 -0
  71. package/dist/tool-generators/generate-fixed-shape-tools.js +53 -0
  72. package/dist/tool-generators/index.d.ts +6 -0
  73. package/dist/tool-generators/index.d.ts.map +1 -0
  74. package/dist/tool-generators/index.js +3 -0
  75. package/dist/tool-generators/schema-analysis.d.ts +18 -0
  76. package/dist/tool-generators/schema-analysis.d.ts.map +1 -0
  77. package/dist/tool-generators/schema-analysis.js +142 -0
  78. package/dist/tool-generators/schema-helpers.d.ts +87 -0
  79. package/dist/tool-generators/schema-helpers.d.ts.map +1 -0
  80. package/dist/tool-generators/schema-helpers.js +157 -0
  81. package/dist/tool-generators/tool-generator.d.ts +11 -0
  82. package/dist/tool-generators/tool-generator.d.ts.map +1 -0
  83. package/dist/tool-generators/tool-generator.js +437 -0
  84. package/dist/tool-generators/types.d.ts +26 -0
  85. package/dist/tool-generators/types.d.ts.map +1 -0
  86. package/dist/tool-generators/types.js +1 -0
  87. package/dist/tool-generators/utils.d.ts +16 -0
  88. package/dist/tool-generators/utils.d.ts.map +1 -0
  89. package/dist/tool-generators/utils.js +35 -0
  90. package/dist/types.d.ts +17 -0
  91. package/dist/types.d.ts.map +1 -0
  92. package/dist/types.js +1 -0
  93. package/dist/utils.d.ts +31 -0
  94. package/dist/utils.d.ts.map +1 -0
  95. package/dist/utils.js +108 -0
  96. package/dist/web.d.ts +680 -0
  97. package/dist/web.d.ts.map +1 -0
  98. package/dist/web.js +1312 -0
  99. package/dist/zod-to-tools.d.ts +49 -0
  100. package/dist/zod-to-tools.d.ts.map +1 -0
  101. package/dist/zod-to-tools.js +623 -0
  102. package/package.json +58 -0
package/dist/web.d.ts ADDED
@@ -0,0 +1,680 @@
1
+ import type { SplitPlan } from '@mcp-web/decompose-zod-schema';
2
+ import type { AppDefinition, CreatedApp, MCPWebConfig, ProcessedAppDefinition, ProcessedToolDefinition, ResourceDefinition, ToolDefinition, ToolRegistrationError } from '@mcp-web/types';
3
+ import { type z } from 'zod';
4
+ import { type CreatedStateTools } from './create-state-tools.js';
5
+ import { type CreatedTool } from './create-tool.js';
6
+ import { QueryResponse } from './query.js';
7
+ import type { QueryRequest } from './types.js';
8
+ /**
9
+ * Main class for integrating web applications with AI agents via the Model Context Protocol (MCP).
10
+ *
11
+ * MCPWeb enables your web application to expose state and actions as tools that AI agents can
12
+ * interact with. It handles the WebSocket connection to the bridge server, tool registration,
13
+ * and bi-directional communication between your frontend and AI agents.
14
+ *
15
+ * @example Basic Usage
16
+ * ```typescript
17
+ * import { MCPWeb } from '@mcp-web/core';
18
+ *
19
+ * const mcp = new MCPWeb({
20
+ * name: 'My Todo App',
21
+ * description: 'A todo application that AI agents can control',
22
+ * autoConnect: true,
23
+ * });
24
+ *
25
+ * // Register a tool
26
+ * mcp.addTool({
27
+ * name: 'create_todo',
28
+ * description: 'Create a new todo item',
29
+ * handler: (input) => {
30
+ * const todo = { id: crypto.randomUUID(), ...input };
31
+ * todos.push(todo);
32
+ * return todo;
33
+ * },
34
+ * });
35
+ * ```
36
+ *
37
+ * @example With Full Configuration
38
+ * ```typescript
39
+ * const mcp = new MCPWeb({
40
+ * name: 'Checkers Game',
41
+ * description: 'Interactive checkers game controllable by AI agents',
42
+ * bridgeUrl: 'localhost:3001',
43
+ * icon: 'https://example.com/icon.png',
44
+ * agentUrl: 'localhost:3003',
45
+ * autoConnect: true,
46
+ * });
47
+ * ```
48
+ */
49
+ export declare class MCPWeb {
50
+ #private;
51
+ /**
52
+ * Creates a new MCPWeb instance with the specified configuration.
53
+ *
54
+ * The constructor initializes the WebSocket connection settings, generates or loads
55
+ * authentication credentials, and optionally auto-connects to the bridge server.
56
+ *
57
+ * @param config - Configuration object for MCPWeb
58
+ * @throws {Error} If configuration validation fails
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * const mcp = new MCPWeb({
63
+ * name: 'My Todo App',
64
+ * description: 'A todo application that AI agents can control',
65
+ * bridgeUrl: 'localhost:3001',
66
+ * autoConnect: true,
67
+ * });
68
+ * ```
69
+ */
70
+ constructor(config: MCPWebConfig);
71
+ /**
72
+ * Unique session identifier for this frontend instance.
73
+ *
74
+ * The session ID is automatically generated on construction.
75
+ * It's used to identify this specific frontend instance in the bridge server.
76
+ *
77
+ * @returns The session ID string
78
+ */
79
+ get sessionId(): string;
80
+ /**
81
+ * Authentication token for this session.
82
+ *
83
+ * The auth token is either auto-generated, loaded from localStorage, or provided via config.
84
+ * By default, it's persisted in localStorage to maintain the same token across page reloads.
85
+ *
86
+ * @returns The authentication token string
87
+ */
88
+ get authToken(): string;
89
+ /**
90
+ * Map of all registered tools.
91
+ *
92
+ * Provides access to the internal tool registry. Each tool is keyed by its name.
93
+ *
94
+ * @returns Map of tool names to processed tool definitions
95
+ */
96
+ get tools(): Map<string, ProcessedToolDefinition>;
97
+ /**
98
+ * Map of all registered resources.
99
+ *
100
+ * Provides access to the internal resource registry. Each resource is keyed by its URI.
101
+ *
102
+ * @returns Map of resource URIs to resource definitions
103
+ */
104
+ get resources(): Map<string, ResourceDefinition>;
105
+ /**
106
+ * Map of all registered MCP Apps.
107
+ *
108
+ * Provides access to the internal app registry. Each app is keyed by its name.
109
+ *
110
+ * @returns Map of app names to processed app definitions
111
+ */
112
+ get apps(): Map<string, ProcessedAppDefinition>;
113
+ /**
114
+ * The processed MCPWeb configuration.
115
+ *
116
+ * Returns the validated and processed configuration with all defaults applied.
117
+ *
118
+ * @returns The complete configuration object
119
+ */
120
+ get config(): {
121
+ name: string;
122
+ description: string;
123
+ bridgeUrl: string;
124
+ agentUrl: string | undefined;
125
+ persistAuthToken: boolean;
126
+ autoConnect: boolean;
127
+ onSessionLimitExceeded: "reject" | "close_oldest";
128
+ debug: boolean;
129
+ icon?: string | undefined;
130
+ authToken?: string | undefined;
131
+ maxSessionsPerToken?: number | undefined;
132
+ maxInFlightQueriesPerToken?: number | undefined;
133
+ sessionMaxDurationMs?: number | undefined;
134
+ sessionName?: string | undefined;
135
+ };
136
+ /**
137
+ * Configuration object for the AI host app (e.g., Claude Desktop) using stdio transport.
138
+ *
139
+ * Use this to configure the MCP client in your AI host application.
140
+ * It contains the connection details and authentication credentials needed
141
+ * for the AI agent to connect to the bridge server via the `@mcp-web/client` stdio wrapper.
142
+ *
143
+ * For a simpler configuration, consider using `remoteMcpConfig` instead, which
144
+ * uses Remote MCP (Streamable HTTP) and doesn't require an intermediate process.
145
+ *
146
+ * @returns MCP client configuration object for stdio transport
147
+ *
148
+ * @example
149
+ * ```typescript
150
+ * console.log('Add this to your Claude Desktop config:');
151
+ * console.log(JSON.stringify(mcp.mcpConfig, null, 2));
152
+ * ```
153
+ */
154
+ get mcpConfig(): {
155
+ [serverName: string]: {
156
+ command: "npx";
157
+ args: ["@mcp-web/client"];
158
+ env: {
159
+ MCP_SERVER_URL: string;
160
+ AUTH_TOKEN: string;
161
+ };
162
+ };
163
+ };
164
+ /**
165
+ * Configuration object for the AI host app (e.g., Claude Desktop) using Remote MCP.
166
+ *
167
+ * This is the recommended configuration method. It uses Remote MCP (Streamable HTTP)
168
+ * to connect directly to the bridge server via URL, without needing an intermediate
169
+ * stdio process like `@mcp-web/client`.
170
+ *
171
+ * @returns MCP client configuration object for Remote MCP (URL-based)
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * console.log('Add this to your Claude Desktop config:');
176
+ * console.log(JSON.stringify(mcp.remoteMcpConfig, null, 2));
177
+ * // Output:
178
+ * // {
179
+ * // "my-app": {
180
+ * // "url": "https://localhost:3001?token=your-auth-token"
181
+ * // }
182
+ * // }
183
+ * ```
184
+ */
185
+ get remoteMcpConfig(): {
186
+ [x: string]: {
187
+ url: string;
188
+ };
189
+ };
190
+ /**
191
+ * Establishes connection to the bridge server.
192
+ *
193
+ * Opens a WebSocket connection to the bridge server and authenticates using the session's
194
+ * auth token. If `autoConnect` is enabled in the config, this is called automatically
195
+ * during construction.
196
+ *
197
+ * This method is idempotent - calling it multiple times while already connected or
198
+ * connecting will return the same promise.
199
+ *
200
+ * @returns Promise that resolves to `true` when authenticated and ready
201
+ * @throws {Error} If WebSocket connection fails
202
+ *
203
+ * @example Manual Connection
204
+ * ```typescript
205
+ * const mcp = new MCPWeb({
206
+ * name: 'My App',
207
+ * description: 'My application',
208
+ * autoConnect: false, // Disable auto-connect
209
+ * });
210
+ *
211
+ * // Connect when ready
212
+ * await mcp.connect();
213
+ * console.log('Connected to bridge');
214
+ * ```
215
+ *
216
+ * @example Check Connection Status
217
+ * ```typescript
218
+ * if (!mcp.connected) {
219
+ * await mcp.connect();
220
+ * }
221
+ * ```
222
+ */
223
+ connect(): Promise<true>;
224
+ private authenticate;
225
+ private handleMessage;
226
+ private handleToolCall;
227
+ private sendToolResponse;
228
+ private registerAllTools;
229
+ private registerTool;
230
+ private registerAllResources;
231
+ private registerResource;
232
+ private handleResourceRead;
233
+ private sendResourceResponse;
234
+ private handleToolRegistrationError;
235
+ private scheduleReconnect;
236
+ private setupActivityTracking;
237
+ /**
238
+ * Registers a tool that AI agents can call.
239
+ *
240
+ * Supports both Zod schemas (recommended for type safety) and JSON schemas.
241
+ * When using Zod schemas, TypeScript enforces that your handler signature matches the schemas.
242
+ *
243
+ * Can also accept pre-created tools from `createTool()`.
244
+ *
245
+ * @param tool - Tool configuration including name, description, handler, and schemas, or a CreatedTool
246
+ * @returns The registered tool definition that can be used as context or responseTool in queries
247
+ * @throws {Error} If tool definition is invalid
248
+ *
249
+ * @example Basic Tool
250
+ * ```typescript
251
+ * mcp.addTool({
252
+ * name: 'get_current_time',
253
+ * description: 'Get the current time in ISO format',
254
+ * handler: () => ({ time: new Date().toISOString() }),
255
+ * });
256
+ * ```
257
+ *
258
+ * @example With Pre-Created Tool
259
+ * ```typescript
260
+ * import { createTool } from '@mcp-web/core';
261
+ *
262
+ * const timeTool = createTool({
263
+ * name: 'get_current_time',
264
+ * description: 'Get the current time',
265
+ * handler: () => ({ time: new Date().toISOString() }),
266
+ * });
267
+ *
268
+ * mcp.addTool(timeTool);
269
+ * ```
270
+ *
271
+ * @example With Zod Schema (Recommended)
272
+ * ```typescript
273
+ * import { z } from 'zod';
274
+ *
275
+ * const CreateTodoSchema = z.object({
276
+ * title: z.string().describe('Todo title'),
277
+ * description: z.string().optional().describe('Optional description'),
278
+ * });
279
+ *
280
+ * mcp.addTool({
281
+ * name: 'create_todo',
282
+ * description: 'Create a new todo item',
283
+ * handler: (input) => {
284
+ * const todo = {
285
+ * id: crypto.randomUUID(),
286
+ * ...input,
287
+ * completed: false,
288
+ * };
289
+ * todos.push(todo);
290
+ * return todo;
291
+ * },
292
+ * inputSchema: CreateTodoSchema,
293
+ * outputSchema: z.object({
294
+ * id: z.string(),
295
+ * title: z.string(),
296
+ * description: z.string(),
297
+ * completed: z.boolean(),
298
+ * }),
299
+ * });
300
+ * ```
301
+ *
302
+ * @example With JSON Schema
303
+ * ```typescript
304
+ * mcp.addTool({
305
+ * name: 'search_items',
306
+ * description: 'Search for items by keyword',
307
+ * handler: ({ keyword }) => {
308
+ * return items.filter(item => item.name.includes(keyword));
309
+ * },
310
+ * inputSchema: {
311
+ * type: 'object',
312
+ * properties: {
313
+ * keyword: { type: 'string', description: 'Search keyword' }
314
+ * },
315
+ * required: ['keyword']
316
+ * },
317
+ * });
318
+ * ```
319
+ */
320
+ addTool<TInput extends z.ZodObject | undefined = undefined, TOutput extends z.ZodType | undefined = undefined>(tool: CreatedTool<TInput, TOutput>, options?: {
321
+ /** Called if the bridge rejects the tool registration (e.g., schema conflict with a sibling session). */
322
+ onRegistrationError?: (error: ToolRegistrationError) => void;
323
+ }): ToolDefinition;
324
+ addTool<TInput extends z.ZodObject | undefined = undefined, TOutput extends z.ZodType | undefined = undefined>(tool: {
325
+ name: string;
326
+ description: string;
327
+ handler: TInput extends z.ZodObject ? (input: z.infer<TInput>) => TOutput extends z.ZodType ? z.infer<TOutput> | Promise<z.infer<TOutput>> : void | Promise<void> : TOutput extends z.ZodType ? () => z.infer<TOutput> | Promise<z.infer<TOutput>> : () => void | Promise<void>;
328
+ inputSchema?: TInput;
329
+ outputSchema?: TOutput;
330
+ }, options?: {
331
+ /** Called if the bridge rejects the tool registration (e.g., schema conflict with a sibling session). */
332
+ onRegistrationError?: (error: ToolRegistrationError) => void;
333
+ }): ToolDefinition;
334
+ addTool(tool: {
335
+ name: string;
336
+ description: string;
337
+ handler: (input?: unknown) => unknown | Promise<unknown> | void | Promise<void>;
338
+ inputSchema?: {
339
+ type: string;
340
+ [key: string]: unknown;
341
+ };
342
+ outputSchema?: {
343
+ type: string;
344
+ [key: string]: unknown;
345
+ };
346
+ _meta?: Record<string, unknown>;
347
+ }, options?: {
348
+ /** Called if the bridge rejects the tool registration (e.g., schema conflict with a sibling session). */
349
+ onRegistrationError?: (error: ToolRegistrationError) => void;
350
+ }): ToolDefinition;
351
+ /**
352
+ * Removes a registered tool.
353
+ *
354
+ * After removal, AI agents will no longer be able to call this tool.
355
+ * Useful for dynamically disabling features or cleaning up when tools are no longer needed.
356
+ *
357
+ * @param name - Name of the tool to remove
358
+ *
359
+ * @example
360
+ * ```typescript
361
+ * // Remove a specific tool
362
+ * mcp.removeTool('create_todo');
363
+ * ```
364
+ */
365
+ removeTool(name: string): void;
366
+ /**
367
+ * Registers a resource that AI agents can read.
368
+ *
369
+ * Resources are content that AI agents can request, such as HTML for MCP Apps.
370
+ * The handler function is called when the AI requests the resource content.
371
+ *
372
+ * @param resource - Resource configuration including URI, name, description, and handler
373
+ * @returns The registered resource definition
374
+ * @throws {Error} If resource definition is invalid
375
+ *
376
+ * @example Basic Resource
377
+ * ```typescript
378
+ * mcp.addResource({
379
+ * uri: 'ui://my-app/statistics.html',
380
+ * name: 'Statistics View',
381
+ * description: 'Statistics visualization for the app',
382
+ * mimeType: 'text/html',
383
+ * handler: async () => {
384
+ * const response = await fetch('/mcp-web-apps/statistics.html');
385
+ * return response.text();
386
+ * },
387
+ * });
388
+ * ```
389
+ *
390
+ * @example Resource from URL
391
+ * ```typescript
392
+ * mcp.addResource({
393
+ * uri: 'ui://my-app/chart.html',
394
+ * name: 'Chart Component',
395
+ * handler: () => fetch('/components/chart.html').then(r => r.text()),
396
+ * });
397
+ * ```
398
+ */
399
+ addResource(resource: ResourceDefinition): ResourceDefinition;
400
+ /**
401
+ * Removes a registered resource.
402
+ *
403
+ * After removal, AI agents will no longer be able to read this resource.
404
+ *
405
+ * @param uri - URI of the resource to remove
406
+ *
407
+ * @example
408
+ * ```typescript
409
+ * mcp.removeResource('ui://my-app/statistics.html');
410
+ * ```
411
+ */
412
+ removeResource(uri: string): void;
413
+ /**
414
+ * Registers an MCP App that AI agents can invoke to show visual UI.
415
+ *
416
+ * An MCP App combines a tool (that AI calls to get props) with a resource (the HTML UI).
417
+ * When AI calls the tool, the handler returns props. The tool response includes
418
+ * `_meta.ui.resourceUri` which tells the host to fetch and render the app HTML.
419
+ *
420
+ * @param app - App configuration including name, description, handler, and optional URL
421
+ * @returns The registered app definition
422
+ * @throws {Error} If app definition is invalid
423
+ *
424
+ * @example Basic App
425
+ * ```typescript
426
+ * mcp.addApp({
427
+ * name: 'show_statistics',
428
+ * description: 'Display statistics visualization',
429
+ * handler: () => ({
430
+ * completionRate: 0.75,
431
+ * totalTasks: 100,
432
+ * completedTasks: 75,
433
+ * }),
434
+ * });
435
+ * ```
436
+ *
437
+ * @example With Input Schema
438
+ * ```typescript
439
+ * mcp.addApp({
440
+ * name: 'show_chart',
441
+ * description: 'Display a chart with the given data',
442
+ * inputSchema: z.object({
443
+ * chartType: z.enum(['bar', 'line', 'pie']).describe('Type of chart'),
444
+ * title: z.string().describe('Chart title'),
445
+ * }),
446
+ * handler: ({ chartType, title }) => ({
447
+ * chartType,
448
+ * title,
449
+ * data: getChartData(),
450
+ * }),
451
+ * });
452
+ * ```
453
+ *
454
+ * @example With Custom URL
455
+ * ```typescript
456
+ * mcp.addApp({
457
+ * name: 'show_dashboard',
458
+ * description: 'Display the main dashboard',
459
+ * handler: () => getDashboardData(),
460
+ * url: '/custom/path/dashboard.html',
461
+ * });
462
+ * ```
463
+ *
464
+ * @example With Pre-Created App
465
+ * ```typescript
466
+ * import { createApp } from '@mcp-web/app';
467
+ *
468
+ * const statisticsApp = createApp({
469
+ * name: 'show_statistics',
470
+ * description: 'Display statistics',
471
+ * handler: () => ({ rate: 0.75 }),
472
+ * });
473
+ *
474
+ * mcp.addApp(statisticsApp);
475
+ * ```
476
+ */
477
+ addApp(app: AppDefinition | CreatedApp): AppDefinition;
478
+ /**
479
+ * Removes a registered MCP App.
480
+ *
481
+ * After removal, AI agents will no longer be able to invoke this app.
482
+ * This also removes the associated tool and resource.
483
+ *
484
+ * @param name - Name of the app to remove
485
+ *
486
+ * @example
487
+ * ```typescript
488
+ * mcp.removeApp('show_statistics');
489
+ * ```
490
+ */
491
+ removeApp(name: string): void;
492
+ /**
493
+ * Add state management tools with optional expanded tool generation.
494
+ * When `expand` is true, automatically generates targeted tools for
495
+ * arrays and records instead of a single setter.
496
+ *
497
+ * Can also accept pre-created state tools from `createStateTools()`.
498
+ *
499
+ * @returns Tuple of [getter tool, setter tool(s), cleanup function]
500
+ * - Without schemaSplit and expand: [ToolDefinition, ToolDefinition, () => void]
501
+ * - With schemaSplit or expand: [ToolDefinition, ToolDefinition[], () => void]
502
+ *
503
+ * @example
504
+ * ```typescript
505
+ * // Basic read-write state (returns single setter)
506
+ * const [getTodos, setTodos, cleanup] = mcp.addStateTools({
507
+ * name: 'todos',
508
+ * description: 'List of all todos',
509
+ * get: () => todos,
510
+ * set: (val) => { todos = val },
511
+ * schema: TodoListSchema
512
+ * });
513
+ *
514
+ * // With pre-created state tools
515
+ * import { createStateTools } from '@mcp-web/core';
516
+ *
517
+ * const todoTools = createStateTools({
518
+ * name: 'todos',
519
+ * description: 'Todo list',
520
+ * get: () => store.get(todosAtom),
521
+ * set: (value) => store.set(todosAtom, value),
522
+ * schema: TodosSchema,
523
+ * expand: true,
524
+ * });
525
+ *
526
+ * const [getter, setters, cleanup] = mcp.addStateTools(todoTools);
527
+ *
528
+ * // With schema decomposition (returns array of setters)
529
+ * const [getGameState, setters, cleanup] = mcp.addStateTools({
530
+ * name: 'game_state',
531
+ * description: 'Game board state',
532
+ * get: () => gameState,
533
+ * set: (val) => { gameState = val },
534
+ * schema: GameStateSchema,
535
+ * schemaSplit: ['board', ['currentPlayer'], ['redScore', 'blackScore']]
536
+ * });
537
+ *
538
+ * // With expanded tools for collections (returns array of setters)
539
+ * const [getApp, tools, cleanup] = mcp.addStateTools({
540
+ * name: 'app',
541
+ * description: 'App state',
542
+ * get: () => appState,
543
+ * set: (val) => { appState = val },
544
+ * schema: AppSchema,
545
+ * expand: true
546
+ * });
547
+ * ```
548
+ */
549
+ addStateTools<T>(created: CreatedStateTools<T> & {
550
+ isExpanded: false;
551
+ }): [ToolDefinition, ToolDefinition, () => void];
552
+ addStateTools<T>(created: CreatedStateTools<T> & {
553
+ isExpanded: true;
554
+ }): [ToolDefinition, ToolDefinition[], () => void];
555
+ addStateTools<T>(created: CreatedStateTools<T>): [ToolDefinition, ToolDefinition | ToolDefinition[], () => void];
556
+ addStateTools<T>(options: {
557
+ name: string;
558
+ description: string;
559
+ get: () => T;
560
+ set: (value: T) => void;
561
+ schema: z.ZodType<T>;
562
+ schemaSplit?: undefined;
563
+ expand?: false;
564
+ }): [ToolDefinition, ToolDefinition, () => void];
565
+ addStateTools<T>(options: {
566
+ name: string;
567
+ description: string;
568
+ get: () => T;
569
+ set: (value: T) => void;
570
+ schema: z.ZodType<T>;
571
+ schemaSplit: SplitPlan;
572
+ expand?: boolean;
573
+ }): [ToolDefinition, ToolDefinition[], () => void];
574
+ addStateTools<T>(options: {
575
+ name: string;
576
+ description: string;
577
+ get: () => T;
578
+ set: (value: T) => void;
579
+ schema: z.ZodType<T>;
580
+ schemaSplit?: SplitPlan;
581
+ expand: true;
582
+ }): [ToolDefinition, ToolDefinition[], () => void];
583
+ /**
584
+ * Whether the client is currently connected to the bridge server.
585
+ *
586
+ * @returns `true` if connected, `false` otherwise
587
+ *
588
+ * @example
589
+ * ```typescript
590
+ * if (mcp.connected) {
591
+ * console.log('Ready to receive tool calls');
592
+ * } else {
593
+ * await mcp.connect();
594
+ * }
595
+ * ```
596
+ */
597
+ get connected(): boolean;
598
+ /**
599
+ * Disconnects from the bridge server.
600
+ *
601
+ * Closes the WebSocket connection and cleans up event handlers.
602
+ * Useful for cleanup when unmounting components or closing the application.
603
+ *
604
+ * @example
605
+ * ```typescript
606
+ * // In a Vue component lifecycle hook
607
+ * onUnmounted(() => {
608
+ * mcp.disconnect();
609
+ * });
610
+ * ```
611
+ */
612
+ disconnect(): void;
613
+ /**
614
+ * Gets list of all registered tool names.
615
+ *
616
+ * @returns Array of tool names
617
+ *
618
+ * @example
619
+ * ```typescript
620
+ * const toolNames = mcp.getTools();
621
+ * console.log('Available tools:', toolNames);
622
+ * ```
623
+ */
624
+ getTools(): string[];
625
+ /**
626
+ * Triggers an AI agent query from your frontend code.
627
+ *
628
+ * Requires `agentUrl` to be configured in MCPWeb config. Sends a query to the AI agent
629
+ * and returns a QueryResponse object that can be iterated to stream events.
630
+ *
631
+ * @param request - Query request with prompt and optional context
632
+ * @param signal - Optional AbortSignal for canceling the query
633
+ * @returns QueryResponse object that streams events
634
+ * @throws {Error} If `agentUrl` is not configured or not connected to bridge
635
+ *
636
+ * @example Basic Query
637
+ * ```typescript
638
+ * const query = mcp.query({
639
+ * prompt: 'Analyze the current todos and suggest priorities',
640
+ * });
641
+ *
642
+ * for await (const event of query) {
643
+ * if (event.type === 'query_complete') {
644
+ * console.log('Result:', event.result);
645
+ * }
646
+ * }
647
+ * ```
648
+ *
649
+ * @example With Context
650
+ * ```typescript
651
+ * const query = mcp.query({
652
+ * prompt: 'Update the todo with highest priority',
653
+ * context: [todosTool], // Provide specific tools as context
654
+ * });
655
+ *
656
+ * for await (const event of query) {
657
+ * console.log('Event:', event);
658
+ * }
659
+ * ```
660
+ *
661
+ * @example With Cancellation
662
+ * ```typescript
663
+ * const abortController = new AbortController();
664
+ * const query = mcp.query(
665
+ * { prompt: 'Long running task' },
666
+ * abortController.signal
667
+ * );
668
+ *
669
+ * // Cancel after 5 seconds
670
+ * setTimeout(() => abortController.abort(), 5000);
671
+ * ```
672
+ */
673
+ query(request: QueryRequest, signal?: AbortSignal): QueryResponse;
674
+ /**
675
+ * Internal method to create the query stream
676
+ */
677
+ private createQueryStream;
678
+ }
679
+ export default MCPWeb;
680
+ //# sourceMappingURL=web.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web.d.ts","sourceRoot":"","sources":["../src/web.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAoB,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAEjF,OAAO,KAAK,EACV,aAAa,EACb,UAAU,EACV,YAAY,EAEZ,sBAAsB,EAEtB,uBAAuB,EAEvB,kBAAkB,EAClB,cAAc,EACd,qBAAqB,EACtB,MAAM,gBAAgB,CAAC;AAYxB,OAAO,EAAa,KAAK,CAAC,EAAE,MAAM,KAAK,CAAC;AACxC,OAAO,EAAE,KAAK,iBAAiB,EAAuB,MAAM,yBAAyB,CAAC;AACtF,OAAO,EAAE,KAAK,WAAW,EAAiB,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAG3C,OAAO,KAAK,EAAE,YAAY,EAAuB,MAAM,YAAY,CAAC;AAGpE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,qBAAa,MAAM;;IAuBjB;;;;;;;;;;;;;;;;;;OAkBG;gBACS,MAAM,EAAE,YAAY;IAuBhC;;;;;;;OAOG;IACH,IAAI,SAAS,WAEZ;IAED;;;;;;;OAOG;IACH,IAAI,SAAS,WAEZ;IAED;;;;;;OAMG;IACH,IAAI,KAAK,yCAER;IAED;;;;;;OAMG;IACH,IAAI,SAAS,oCAEZ;IAED;;;;;;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