mcp-use 1.0.4 → 1.0.5

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 (33) hide show
  1. package/README.md +98 -1
  2. package/dist/index.cjs +0 -640
  3. package/dist/index.d.ts +10 -2
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +0 -5
  6. package/dist/src/agents/mcp_agent.d.ts.map +1 -1
  7. package/dist/src/server/adapters/mcp-ui-adapter.d.ts +66 -0
  8. package/dist/src/server/adapters/mcp-ui-adapter.d.ts.map +1 -0
  9. package/dist/src/server/index.cjs +292 -14
  10. package/dist/src/server/index.d.ts +4 -2
  11. package/dist/src/server/index.d.ts.map +1 -1
  12. package/dist/src/server/index.js +913 -4
  13. package/dist/src/server/mcp-server.d.ts +91 -2
  14. package/dist/src/server/mcp-server.d.ts.map +1 -1
  15. package/dist/src/server/types/common.d.ts +27 -0
  16. package/dist/src/server/types/common.d.ts.map +1 -0
  17. package/dist/src/server/types/index.d.ts +8 -0
  18. package/dist/src/server/types/index.d.ts.map +1 -0
  19. package/dist/src/server/types/prompt.d.ts +14 -0
  20. package/dist/src/server/types/prompt.d.ts.map +1 -0
  21. package/dist/src/server/types/resource.d.ts +155 -0
  22. package/dist/src/server/types/resource.d.ts.map +1 -0
  23. package/dist/src/server/types/tool.d.ts +14 -0
  24. package/dist/src/server/types/tool.d.ts.map +1 -0
  25. package/dist/src/server/types.d.ts +3 -76
  26. package/dist/src/server/types.d.ts.map +1 -1
  27. package/dist/tests/helpers/widget-generators.d.ts +24 -0
  28. package/dist/tests/helpers/widget-generators.d.ts.map +1 -0
  29. package/dist/tests/mcp-ui-adapter.test.d.ts +8 -0
  30. package/dist/tests/mcp-ui-adapter.test.d.ts.map +1 -0
  31. package/dist/tsconfig.tsbuildinfo +1 -1
  32. package/package.json +33 -36
  33. package/dist/chunk-MZPKOZE4.js +0 -644
@@ -1,644 +0,0 @@
1
- import {
2
- __name
3
- } from "./chunk-SHUYVCID.js";
4
-
5
- // src/server/mcp-server.ts
6
- import { McpServer as OfficialMcpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
7
- import { z } from "zod";
8
- import express from "express";
9
- import { existsSync, readdirSync } from "fs";
10
- import { join } from "path";
11
-
12
- // src/server/logging.ts
13
- function requestLogger(req, res, next) {
14
- const timestamp = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
15
- const method = req.method;
16
- const url = req.url;
17
- const originalEnd = res.end.bind(res);
18
- res.end = function(chunk, encoding, cb) {
19
- const statusCode = res.statusCode;
20
- let statusColor = "";
21
- if (statusCode >= 200 && statusCode < 300) {
22
- statusColor = "\x1B[32m";
23
- } else if (statusCode >= 300 && statusCode < 400) {
24
- statusColor = "\x1B[33m";
25
- } else if (statusCode >= 400 && statusCode < 500) {
26
- statusColor = "\x1B[31m";
27
- } else if (statusCode >= 500) {
28
- statusColor = "\x1B[35m";
29
- }
30
- let logMessage = `[${timestamp}] ${method} \x1B[1m${url}\x1B[0m`;
31
- if (method === "POST" && url === "/mcp" && req.body?.method) {
32
- logMessage += ` \x1B[1m[${req.body.method}]\x1B[0m`;
33
- }
34
- logMessage += ` ${statusColor}${statusCode}\x1B[0m`;
35
- console.log(logMessage);
36
- return originalEnd(chunk, encoding, cb);
37
- };
38
- next();
39
- }
40
- __name(requestLogger, "requestLogger");
41
-
42
- // src/server/mcp-server.ts
43
- var McpServer = class {
44
- static {
45
- __name(this, "McpServer");
46
- }
47
- server;
48
- config;
49
- app;
50
- mcpMounted = false;
51
- inspectorMounted = false;
52
- serverPort;
53
- /**
54
- * Creates a new MCP server instance with Express integration
55
- *
56
- * Initializes the server with the provided configuration, sets up CORS headers,
57
- * configures widget serving routes, and creates a proxy that allows direct
58
- * access to Express methods while preserving MCP server functionality.
59
- *
60
- * @param config - Server configuration including name, version, and description
61
- * @returns A proxied McpServer instance that supports both MCP and Express methods
62
- */
63
- constructor(config) {
64
- this.config = config;
65
- this.server = new OfficialMcpServer({
66
- name: config.name,
67
- version: config.version
68
- });
69
- this.app = express();
70
- this.app.use(express.json());
71
- this.app.use((req, res, next) => {
72
- res.header("Access-Control-Allow-Origin", "*");
73
- res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
74
- res.header("Access-Control-Allow-Headers", "Content-Type");
75
- next();
76
- });
77
- this.app.use(requestLogger);
78
- this.setupWidgetRoutes();
79
- return new Proxy(this, {
80
- get(target, prop) {
81
- if (prop in target) {
82
- return target[prop];
83
- }
84
- const value = target.app[prop];
85
- return typeof value === "function" ? value.bind(target.app) : value;
86
- }
87
- });
88
- }
89
- /**
90
- * Define a static resource that can be accessed by clients
91
- *
92
- * Registers a resource with the MCP server that clients can access via HTTP.
93
- * Resources are static content like files, data, or pre-computed results that
94
- * can be retrieved by clients without requiring parameters.
95
- *
96
- * @param resourceDefinition - Configuration object containing resource metadata and handler function
97
- * @param resourceDefinition.name - Unique identifier for the resource
98
- * @param resourceDefinition.uri - URI pattern for accessing the resource
99
- * @param resourceDefinition.title - Optional human-readable title for the resource
100
- * @param resourceDefinition.description - Optional description of the resource
101
- * @param resourceDefinition.mimeType - MIME type of the resource content
102
- * @param resourceDefinition.annotations - Optional annotations (audience, priority, lastModified)
103
- * @param resourceDefinition.fn - Async function that returns the resource content
104
- * @returns The server instance for method chaining
105
- *
106
- * @example
107
- * ```typescript
108
- * server.resource({
109
- * name: 'config',
110
- * uri: 'config://app-settings',
111
- * title: 'Application Settings',
112
- * mimeType: 'application/json',
113
- * description: 'Current application configuration',
114
- * annotations: {
115
- * audience: ['user'],
116
- * priority: 0.8
117
- * },
118
- * fn: async () => ({
119
- * contents: [{
120
- * uri: 'config://app-settings',
121
- * mimeType: 'application/json',
122
- * text: JSON.stringify({ theme: 'dark', language: 'en' })
123
- * }]
124
- * })
125
- * })
126
- * ```
127
- */
128
- resource(resourceDefinition) {
129
- this.server.resource(
130
- resourceDefinition.name,
131
- resourceDefinition.uri,
132
- {
133
- name: resourceDefinition.name,
134
- title: resourceDefinition.title,
135
- description: resourceDefinition.description,
136
- mimeType: resourceDefinition.mimeType,
137
- annotations: resourceDefinition.annotations
138
- },
139
- async () => {
140
- return await resourceDefinition.fn();
141
- }
142
- );
143
- return this;
144
- }
145
- /**
146
- * Define a dynamic resource template with parameters
147
- *
148
- * Registers a parameterized resource template with the MCP server. Templates use URI
149
- * patterns with placeholders that can be filled in at request time, allowing dynamic
150
- * resource generation based on parameters.
151
- *
152
- * @param resourceTemplateDefinition - Configuration object for the resource template
153
- * @param resourceTemplateDefinition.name - Unique identifier for the template
154
- * @param resourceTemplateDefinition.resourceTemplate - ResourceTemplate object with uriTemplate and metadata
155
- * @param resourceTemplateDefinition.fn - Async function that generates resource content from URI and params
156
- * @returns The server instance for method chaining
157
- *
158
- * @example
159
- * ```typescript
160
- * server.resourceTemplate({
161
- * name: 'user-profile',
162
- * resourceTemplate: {
163
- * uriTemplate: 'user://{userId}/profile',
164
- * name: 'User Profile',
165
- * mimeType: 'application/json'
166
- * },
167
- * fn: async (uri, params) => ({
168
- * contents: [{
169
- * uri: uri.toString(),
170
- * mimeType: 'application/json',
171
- * text: JSON.stringify({ userId: params.userId, name: 'John Doe' })
172
- * }]
173
- * })
174
- * })
175
- * ```
176
- */
177
- resourceTemplate(resourceTemplateDefinition) {
178
- const template = new ResourceTemplate(
179
- resourceTemplateDefinition.resourceTemplate.uriTemplate,
180
- {
181
- list: void 0,
182
- // Optional: callback to list all matching resources
183
- complete: void 0
184
- // Optional: callback for auto-completion
185
- }
186
- );
187
- const metadata = {};
188
- if (resourceTemplateDefinition.resourceTemplate.name) {
189
- metadata.name = resourceTemplateDefinition.resourceTemplate.name;
190
- }
191
- if (resourceTemplateDefinition.title) {
192
- metadata.title = resourceTemplateDefinition.title;
193
- }
194
- if (resourceTemplateDefinition.description || resourceTemplateDefinition.resourceTemplate.description) {
195
- metadata.description = resourceTemplateDefinition.description || resourceTemplateDefinition.resourceTemplate.description;
196
- }
197
- if (resourceTemplateDefinition.resourceTemplate.mimeType) {
198
- metadata.mimeType = resourceTemplateDefinition.resourceTemplate.mimeType;
199
- }
200
- if (resourceTemplateDefinition.annotations) {
201
- metadata.annotations = resourceTemplateDefinition.annotations;
202
- }
203
- this.server.resource(
204
- resourceTemplateDefinition.name,
205
- template,
206
- metadata,
207
- async (uri) => {
208
- const params = this.parseTemplateUri(
209
- resourceTemplateDefinition.resourceTemplate.uriTemplate,
210
- uri.toString()
211
- );
212
- return await resourceTemplateDefinition.fn(uri, params);
213
- }
214
- );
215
- return this;
216
- }
217
- /**
218
- * Define a tool that can be called by clients
219
- *
220
- * Registers a tool with the MCP server that clients can invoke with parameters.
221
- * Tools are functions that perform actions, computations, or operations and
222
- * return results. They accept structured input parameters and return structured output.
223
- *
224
- * @param toolDefinition - Configuration object containing tool metadata and handler function
225
- * @param toolDefinition.name - Unique identifier for the tool
226
- * @param toolDefinition.description - Human-readable description of what the tool does
227
- * @param toolDefinition.inputs - Array of input parameter definitions with types and validation
228
- * @param toolDefinition.fn - Async function that executes the tool logic with provided parameters
229
- * @returns The server instance for method chaining
230
- *
231
- * @example
232
- * ```typescript
233
- * server.tool({
234
- * name: 'calculate',
235
- * description: 'Performs mathematical calculations',
236
- * inputs: [
237
- * { name: 'expression', type: 'string', required: true },
238
- * { name: 'precision', type: 'number', required: false }
239
- * ],
240
- * fn: async ({ expression, precision = 2 }) => {
241
- * const result = eval(expression)
242
- * return { result: Number(result.toFixed(precision)) }
243
- * }
244
- * })
245
- * ```
246
- */
247
- tool(toolDefinition) {
248
- const inputSchema = this.createToolInputSchema(toolDefinition.inputs || []);
249
- this.server.tool(
250
- toolDefinition.name,
251
- toolDefinition.description ?? "",
252
- inputSchema,
253
- async (params) => {
254
- return await toolDefinition.fn(params);
255
- }
256
- );
257
- return this;
258
- }
259
- /**
260
- * Define a prompt template
261
- *
262
- * Registers a prompt template with the MCP server that clients can use to generate
263
- * structured prompts for AI models. Prompt templates accept parameters and return
264
- * formatted text that can be used as input to language models or other AI systems.
265
- *
266
- * @param promptDefinition - Configuration object containing prompt metadata and handler function
267
- * @param promptDefinition.name - Unique identifier for the prompt template
268
- * @param promptDefinition.description - Human-readable description of the prompt's purpose
269
- * @param promptDefinition.args - Array of argument definitions with types and validation
270
- * @param promptDefinition.fn - Async function that generates the prompt from provided arguments
271
- * @returns The server instance for method chaining
272
- *
273
- * @example
274
- * ```typescript
275
- * server.prompt({
276
- * name: 'code-review',
277
- * description: 'Generates a code review prompt',
278
- * args: [
279
- * { name: 'language', type: 'string', required: true },
280
- * { name: 'focus', type: 'string', required: false }
281
- * ],
282
- * fn: async ({ language, focus = 'general' }) => {
283
- * return {
284
- * messages: [{
285
- * role: 'user',
286
- * content: `Please review this ${language} code with focus on ${focus}...`
287
- * }]
288
- * }
289
- * }
290
- * })
291
- * ```
292
- */
293
- prompt(promptDefinition) {
294
- const argsSchema = this.createPromptArgsSchema(promptDefinition.args || []);
295
- this.server.prompt(
296
- promptDefinition.name,
297
- promptDefinition.description ?? "",
298
- argsSchema,
299
- async (params) => {
300
- return await promptDefinition.fn(params);
301
- }
302
- );
303
- return this;
304
- }
305
- /**
306
- * Mount MCP server endpoints at /mcp
307
- *
308
- * Sets up the HTTP transport layer for the MCP server, creating endpoints for
309
- * Server-Sent Events (SSE) streaming, POST message handling, and DELETE session cleanup.
310
- * Uses stateless mode for session management, making it suitable for stateless deployments.
311
- *
312
- * This method is called automatically when the server starts listening and ensures
313
- * that MCP clients can communicate with the server over HTTP.
314
- *
315
- * @private
316
- * @returns Promise that resolves when MCP endpoints are successfully mounted
317
- *
318
- * @example
319
- * Endpoints created:
320
- * - GET /mcp - SSE streaming endpoint for real-time communication
321
- * - POST /mcp - Message handling endpoint for MCP protocol messages
322
- * - DELETE /mcp - Session cleanup endpoint
323
- */
324
- async mountMcp() {
325
- if (this.mcpMounted) return;
326
- const { StreamableHTTPServerTransport } = await import("@modelcontextprotocol/sdk/server/streamableHttp.js");
327
- const httpTransport = new StreamableHTTPServerTransport({
328
- sessionIdGenerator: void 0
329
- // Stateless mode
330
- });
331
- await this.server.connect(httpTransport);
332
- const endpoint = "/mcp";
333
- this.app.get(endpoint, async (req, res) => {
334
- await httpTransport.handleRequest(req, res);
335
- });
336
- this.app.post(endpoint, express.json(), async (req, res) => {
337
- await httpTransport.handleRequest(req, res, req.body);
338
- });
339
- this.app.delete(endpoint, async (req, res) => {
340
- await httpTransport.handleRequest(req, res);
341
- });
342
- this.mcpMounted = true;
343
- console.log(`[MCP] Server mounted at ${endpoint}`);
344
- }
345
- /**
346
- * Start the Express server with MCP endpoints
347
- *
348
- * Initiates the server startup process by mounting MCP endpoints, configuring
349
- * the inspector UI (if available), and starting the Express server to listen
350
- * for incoming connections. This is the main entry point for running the server.
351
- *
352
- * The server will be accessible at the specified port with MCP endpoints at /mcp
353
- * and inspector UI at /inspector (if the inspector package is installed).
354
- *
355
- * @param port - Port number to listen on (defaults to 3001 if not specified)
356
- * @returns Promise that resolves when the server is successfully listening
357
- *
358
- * @example
359
- * ```typescript
360
- * await server.listen(8080)
361
- * // Server now running at http://localhost:8080
362
- * // MCP endpoints: http://localhost:8080/mcp
363
- * // Inspector UI: http://localhost:8080/inspector
364
- * ```
365
- */
366
- async listen(port) {
367
- await this.mountMcp();
368
- this.serverPort = port || 3001;
369
- this.mountInspector();
370
- this.app.listen(this.serverPort, () => {
371
- console.log(`[SERVER] Listening on http://localhost:${this.serverPort}`);
372
- console.log(`[MCP] Endpoints: http://localhost:${this.serverPort}/mcp`);
373
- });
374
- }
375
- /**
376
- * Mount MCP Inspector UI at /inspector
377
- *
378
- * Dynamically loads and mounts the MCP Inspector UI package if available, providing
379
- * a web-based interface for testing and debugging MCP servers. The inspector
380
- * automatically connects to the local MCP server endpoints.
381
- *
382
- * This method gracefully handles cases where the inspector package is not installed,
383
- * allowing the server to function without the inspector in production environments.
384
- *
385
- * @private
386
- * @returns void
387
- *
388
- * @example
389
- * If @mcp-use/inspector is installed:
390
- * - Inspector UI available at http://localhost:PORT/inspector
391
- * - Automatically connects to http://localhost:PORT/mcp
392
- *
393
- * If not installed:
394
- * - Server continues to function normally
395
- * - No inspector UI available
396
- */
397
- mountInspector() {
398
- if (this.inspectorMounted) return;
399
- import("@mcp-use/inspector").then(({ mountInspector }) => {
400
- const mcpServerUrl = `http://localhost:${this.serverPort}/mcp`;
401
- mountInspector(this.app, "/inspector", mcpServerUrl);
402
- this.inspectorMounted = true;
403
- console.log(`[INSPECTOR] UI available at http://localhost:${this.serverPort}/inspector`);
404
- }).catch(() => {
405
- });
406
- }
407
- /**
408
- * Setup default widget serving routes
409
- *
410
- * Configures Express routes to serve MCP UI widgets and their static assets.
411
- * Widgets are served from the dist/resources/mcp-use/widgets directory and can
412
- * be accessed via HTTP endpoints for embedding in web applications.
413
- *
414
- * Routes created:
415
- * - GET /mcp-use/widgets/:widget - Serves widget's index.html
416
- * - GET /mcp-use/widgets/:widget/assets/* - Serves widget-specific assets
417
- * - GET /mcp-use/widgets/assets/* - Fallback asset serving with auto-discovery
418
- *
419
- * @private
420
- * @returns void
421
- *
422
- * @example
423
- * Widget routes:
424
- * - http://localhost:3001/mcp-use/widgets/kanban-board
425
- * - http://localhost:3001/mcp-use/widgets/todo-list/assets/style.css
426
- * - http://localhost:3001/mcp-use/widgets/assets/script.js (auto-discovered)
427
- */
428
- setupWidgetRoutes() {
429
- this.app.get("/mcp-use/widgets/:widget/assets/*", (req, res, next) => {
430
- const widget = req.params.widget;
431
- const assetFile = req.params[0];
432
- const assetPath = join(process.cwd(), "dist", "resources", "mcp-use", "widgets", widget, "assets", assetFile);
433
- res.sendFile(assetPath, (err) => err ? next() : void 0);
434
- });
435
- this.app.get("/mcp-use/widgets/assets/*", (req, res, next) => {
436
- const assetFile = req.params[0];
437
- const widgetsDir = join(process.cwd(), "dist", "resources", "mcp-use", "widgets");
438
- try {
439
- const widgets = readdirSync(widgetsDir);
440
- for (const widget of widgets) {
441
- const assetPath = join(widgetsDir, widget, "assets", assetFile);
442
- if (existsSync(assetPath)) {
443
- return res.sendFile(assetPath);
444
- }
445
- }
446
- next();
447
- } catch {
448
- next();
449
- }
450
- });
451
- this.app.get("/mcp-use/widgets/:widget", (req, res, next) => {
452
- const filePath = join(process.cwd(), "dist", "resources", "mcp-use", "widgets", req.params.widget, "index.html");
453
- res.sendFile(filePath, (err) => err ? next() : void 0);
454
- });
455
- }
456
- /**
457
- * Create input schema for resource templates
458
- *
459
- * Parses a URI template string to extract parameter names and generates a Zod
460
- * validation schema for those parameters. Used internally for validating resource
461
- * template parameters before processing requests.
462
- *
463
- * @param uriTemplate - URI template string with parameter placeholders (e.g., "/users/{id}/posts/{postId}")
464
- * @returns Object mapping parameter names to Zod string schemas
465
- *
466
- * @example
467
- * ```typescript
468
- * const schema = this.createInputSchema("/users/{id}/posts/{postId}")
469
- * // Returns: { id: z.string(), postId: z.string() }
470
- * ```
471
- */
472
- createInputSchema(uriTemplate) {
473
- const params = this.extractTemplateParams(uriTemplate);
474
- const schema = {};
475
- params.forEach((param) => {
476
- schema[param] = z.string();
477
- });
478
- return schema;
479
- }
480
- /**
481
- * Create input schema for tools
482
- *
483
- * Converts tool input definitions into Zod validation schemas for runtime validation.
484
- * Supports common data types (string, number, boolean, object, array) and optional
485
- * parameters. Used internally when registering tools with the MCP server.
486
- *
487
- * @param inputs - Array of input parameter definitions with name, type, and optional flag
488
- * @returns Object mapping parameter names to Zod validation schemas
489
- *
490
- * @example
491
- * ```typescript
492
- * const schema = this.createToolInputSchema([
493
- * { name: 'query', type: 'string', required: true },
494
- * { name: 'limit', type: 'number', required: false }
495
- * ])
496
- * // Returns: { query: z.string(), limit: z.number().optional() }
497
- * ```
498
- */
499
- createToolInputSchema(inputs) {
500
- const schema = {};
501
- inputs.forEach((input) => {
502
- let zodType;
503
- switch (input.type) {
504
- case "string":
505
- zodType = z.string();
506
- break;
507
- case "number":
508
- zodType = z.number();
509
- break;
510
- case "boolean":
511
- zodType = z.boolean();
512
- break;
513
- case "object":
514
- zodType = z.object({});
515
- break;
516
- case "array":
517
- zodType = z.array(z.any());
518
- break;
519
- default:
520
- zodType = z.any();
521
- }
522
- if (!input.required) {
523
- zodType = zodType.optional();
524
- }
525
- schema[input.name] = zodType;
526
- });
527
- return schema;
528
- }
529
- /**
530
- * Create arguments schema for prompts
531
- *
532
- * Converts prompt argument definitions into Zod validation schemas for runtime validation.
533
- * Supports common data types (string, number, boolean, object, array) and optional
534
- * parameters. Used internally when registering prompt templates with the MCP server.
535
- *
536
- * @param inputs - Array of argument definitions with name, type, and optional flag
537
- * @returns Object mapping argument names to Zod validation schemas
538
- *
539
- * @example
540
- * ```typescript
541
- * const schema = this.createPromptArgsSchema([
542
- * { name: 'topic', type: 'string', required: true },
543
- * { name: 'style', type: 'string', required: false }
544
- * ])
545
- * // Returns: { topic: z.string(), style: z.string().optional() }
546
- * ```
547
- */
548
- createPromptArgsSchema(inputs) {
549
- const schema = {};
550
- inputs.forEach((input) => {
551
- let zodType;
552
- switch (input.type) {
553
- case "string":
554
- zodType = z.string();
555
- break;
556
- case "number":
557
- zodType = z.number();
558
- break;
559
- case "boolean":
560
- zodType = z.boolean();
561
- break;
562
- case "object":
563
- zodType = z.object({});
564
- break;
565
- case "array":
566
- zodType = z.array(z.any());
567
- break;
568
- default:
569
- zodType = z.any();
570
- }
571
- if (!input.required) {
572
- zodType = zodType.optional();
573
- }
574
- schema[input.name] = zodType;
575
- });
576
- return schema;
577
- }
578
- /**
579
- * Extract parameter names from URI template
580
- *
581
- * Parses a URI template string to extract parameter names enclosed in curly braces.
582
- * Used internally to identify dynamic parameters in resource templates and generate
583
- * appropriate validation schemas.
584
- *
585
- * @param uriTemplate - URI template string with parameter placeholders (e.g., "/users/{id}/posts/{postId}")
586
- * @returns Array of parameter names found in the template
587
- *
588
- * @example
589
- * ```typescript
590
- * const params = this.extractTemplateParams("/users/{id}/posts/{postId}")
591
- * // Returns: ["id", "postId"]
592
- * ```
593
- */
594
- extractTemplateParams(uriTemplate) {
595
- const matches = uriTemplate.match(/\{([^}]+)\}/g);
596
- return matches ? matches.map((match) => match.slice(1, -1)) : [];
597
- }
598
- /**
599
- * Parse parameter values from a URI based on a template
600
- *
601
- * Extracts parameter values from an actual URI by matching it against a URI template.
602
- * The template contains placeholders like {param} which are extracted as key-value pairs.
603
- *
604
- * @param template - URI template with placeholders (e.g., "user://{userId}/posts/{postId}")
605
- * @param uri - Actual URI to parse (e.g., "user://123/posts/456")
606
- * @returns Object mapping parameter names to their values
607
- *
608
- * @example
609
- * ```typescript
610
- * const params = this.parseTemplateUri("user://{userId}/posts/{postId}", "user://123/posts/456")
611
- * // Returns: { userId: "123", postId: "456" }
612
- * ```
613
- */
614
- parseTemplateUri(template, uri) {
615
- const params = {};
616
- let regexPattern = template.replace(/[.*+?^$()[\]\\|]/g, "\\$&");
617
- const paramNames = [];
618
- regexPattern = regexPattern.replace(/\\\{([^}]+)\\\}/g, (_, paramName) => {
619
- paramNames.push(paramName);
620
- return "([^/]+)";
621
- });
622
- const regex = new RegExp(`^${regexPattern}$`);
623
- const match = uri.match(regex);
624
- if (match) {
625
- paramNames.forEach((paramName, index) => {
626
- params[paramName] = match[index + 1];
627
- });
628
- }
629
- return params;
630
- }
631
- };
632
- function createMCPServer(name, config = {}) {
633
- const instance = new McpServer({
634
- name,
635
- version: config.version || "1.0.0",
636
- description: config.description
637
- });
638
- return instance;
639
- }
640
- __name(createMCPServer, "createMCPServer");
641
-
642
- export {
643
- createMCPServer
644
- };