mcp-use 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -496,7 +496,6 @@ __export(index_exports, {
496
496
  Telemetry: () => Telemetry,
497
497
  ToolMessage: () => import_messages3.ToolMessage,
498
498
  WebSocketConnector: () => WebSocketConnector,
499
- createMCPServer: () => createMCPServer,
500
499
  createOAuthMCPConfig: () => createOAuthMCPConfig,
501
500
  createReadableStreamFromGenerator: () => createReadableStreamFromGenerator,
502
501
  loadConfigFile: () => loadConfigFile,
@@ -2685,8 +2684,36 @@ var MCPAgent = class {
2685
2684
  `;
2686
2685
  }
2687
2686
  try {
2688
- const structuredResult = await structuredLlm.invoke(formatPrompt);
2687
+ logger.info(`\u{1F504} Structured output attempt ${attempt} - using streaming approach`);
2688
+ const stream = await structuredLlm.stream(formatPrompt);
2689
+ let structuredResult = null;
2690
+ let chunkCount = 0;
2691
+ for await (const chunk of stream) {
2692
+ chunkCount++;
2693
+ if (typeof chunk === "string") {
2694
+ try {
2695
+ structuredResult = JSON.parse(chunk);
2696
+ } catch (e) {
2697
+ logger.warn(`\u{1F504} Failed to parse string chunk as JSON: ${chunk}`);
2698
+ }
2699
+ } else if (chunk && typeof chunk === "object") {
2700
+ structuredResult = chunk;
2701
+ } else {
2702
+ try {
2703
+ structuredResult = JSON.parse(String(chunk));
2704
+ } catch (e) {
2705
+ logger.warn(`\u{1F504} Failed to parse chunk as JSON: ${chunk}`);
2706
+ }
2707
+ }
2708
+ await new Promise((resolve) => setTimeout(resolve, 0));
2709
+ if (chunkCount % 10 === 0) {
2710
+ logger.info(`\u{1F504} Structured output streaming: ${chunkCount} chunks`);
2711
+ }
2712
+ }
2689
2713
  logger.info(`\u{1F504} Structured result attempt ${attempt}: ${JSON.stringify(structuredResult, null, 2)}`);
2714
+ if (!structuredResult) {
2715
+ throw new Error("No structured result received from stream");
2716
+ }
2690
2717
  const validatedResult = this._validateStructuredResult(structuredResult, outputSchema);
2691
2718
  logger.info(`\u2705 Structured output successful on attempt ${attempt}`);
2692
2719
  return validatedResult;
@@ -3972,643 +3999,6 @@ async function* streamEventsToAISDKWithTools(streamEvents) {
3972
3999
  }
3973
4000
  __name(streamEventsToAISDKWithTools, "streamEventsToAISDKWithTools");
3974
4001
 
3975
- // src/server/mcp-server.ts
3976
- var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
3977
- var import_zod7 = require("zod");
3978
- var import_express = __toESM(require("express"), 1);
3979
- var import_node_fs3 = require("fs");
3980
- var import_node_path2 = require("path");
3981
-
3982
- // src/server/logging.ts
3983
- function requestLogger(req, res, next) {
3984
- const timestamp2 = (/* @__PURE__ */ new Date()).toISOString().substring(11, 23);
3985
- const method = req.method;
3986
- const url = req.url;
3987
- const originalEnd = res.end.bind(res);
3988
- res.end = function(chunk, encoding, cb) {
3989
- const statusCode = res.statusCode;
3990
- let statusColor = "";
3991
- if (statusCode >= 200 && statusCode < 300) {
3992
- statusColor = "\x1B[32m";
3993
- } else if (statusCode >= 300 && statusCode < 400) {
3994
- statusColor = "\x1B[33m";
3995
- } else if (statusCode >= 400 && statusCode < 500) {
3996
- statusColor = "\x1B[31m";
3997
- } else if (statusCode >= 500) {
3998
- statusColor = "\x1B[35m";
3999
- }
4000
- let logMessage = `[${timestamp2}] ${method} \x1B[1m${url}\x1B[0m`;
4001
- if (method === "POST" && url === "/mcp" && req.body?.method) {
4002
- logMessage += ` \x1B[1m[${req.body.method}]\x1B[0m`;
4003
- }
4004
- logMessage += ` ${statusColor}${statusCode}\x1B[0m`;
4005
- console.log(logMessage);
4006
- return originalEnd(chunk, encoding, cb);
4007
- };
4008
- next();
4009
- }
4010
- __name(requestLogger, "requestLogger");
4011
-
4012
- // src/server/mcp-server.ts
4013
- var McpServer = class {
4014
- static {
4015
- __name(this, "McpServer");
4016
- }
4017
- server;
4018
- config;
4019
- app;
4020
- mcpMounted = false;
4021
- inspectorMounted = false;
4022
- serverPort;
4023
- /**
4024
- * Creates a new MCP server instance with Express integration
4025
- *
4026
- * Initializes the server with the provided configuration, sets up CORS headers,
4027
- * configures widget serving routes, and creates a proxy that allows direct
4028
- * access to Express methods while preserving MCP server functionality.
4029
- *
4030
- * @param config - Server configuration including name, version, and description
4031
- * @returns A proxied McpServer instance that supports both MCP and Express methods
4032
- */
4033
- constructor(config2) {
4034
- this.config = config2;
4035
- this.server = new import_mcp.McpServer({
4036
- name: config2.name,
4037
- version: config2.version
4038
- });
4039
- this.app = (0, import_express.default)();
4040
- this.app.use(import_express.default.json());
4041
- this.app.use((req, res, next) => {
4042
- res.header("Access-Control-Allow-Origin", "*");
4043
- res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
4044
- res.header("Access-Control-Allow-Headers", "Content-Type");
4045
- next();
4046
- });
4047
- this.app.use(requestLogger);
4048
- this.setupWidgetRoutes();
4049
- return new Proxy(this, {
4050
- get(target, prop) {
4051
- if (prop in target) {
4052
- return target[prop];
4053
- }
4054
- const value = target.app[prop];
4055
- return typeof value === "function" ? value.bind(target.app) : value;
4056
- }
4057
- });
4058
- }
4059
- /**
4060
- * Define a static resource that can be accessed by clients
4061
- *
4062
- * Registers a resource with the MCP server that clients can access via HTTP.
4063
- * Resources are static content like files, data, or pre-computed results that
4064
- * can be retrieved by clients without requiring parameters.
4065
- *
4066
- * @param resourceDefinition - Configuration object containing resource metadata and handler function
4067
- * @param resourceDefinition.name - Unique identifier for the resource
4068
- * @param resourceDefinition.uri - URI pattern for accessing the resource
4069
- * @param resourceDefinition.title - Optional human-readable title for the resource
4070
- * @param resourceDefinition.description - Optional description of the resource
4071
- * @param resourceDefinition.mimeType - MIME type of the resource content
4072
- * @param resourceDefinition.annotations - Optional annotations (audience, priority, lastModified)
4073
- * @param resourceDefinition.fn - Async function that returns the resource content
4074
- * @returns The server instance for method chaining
4075
- *
4076
- * @example
4077
- * ```typescript
4078
- * server.resource({
4079
- * name: 'config',
4080
- * uri: 'config://app-settings',
4081
- * title: 'Application Settings',
4082
- * mimeType: 'application/json',
4083
- * description: 'Current application configuration',
4084
- * annotations: {
4085
- * audience: ['user'],
4086
- * priority: 0.8
4087
- * },
4088
- * fn: async () => ({
4089
- * contents: [{
4090
- * uri: 'config://app-settings',
4091
- * mimeType: 'application/json',
4092
- * text: JSON.stringify({ theme: 'dark', language: 'en' })
4093
- * }]
4094
- * })
4095
- * })
4096
- * ```
4097
- */
4098
- resource(resourceDefinition) {
4099
- this.server.resource(
4100
- resourceDefinition.name,
4101
- resourceDefinition.uri,
4102
- {
4103
- name: resourceDefinition.name,
4104
- title: resourceDefinition.title,
4105
- description: resourceDefinition.description,
4106
- mimeType: resourceDefinition.mimeType,
4107
- annotations: resourceDefinition.annotations
4108
- },
4109
- async () => {
4110
- return await resourceDefinition.fn();
4111
- }
4112
- );
4113
- return this;
4114
- }
4115
- /**
4116
- * Define a dynamic resource template with parameters
4117
- *
4118
- * Registers a parameterized resource template with the MCP server. Templates use URI
4119
- * patterns with placeholders that can be filled in at request time, allowing dynamic
4120
- * resource generation based on parameters.
4121
- *
4122
- * @param resourceTemplateDefinition - Configuration object for the resource template
4123
- * @param resourceTemplateDefinition.name - Unique identifier for the template
4124
- * @param resourceTemplateDefinition.resourceTemplate - ResourceTemplate object with uriTemplate and metadata
4125
- * @param resourceTemplateDefinition.fn - Async function that generates resource content from URI and params
4126
- * @returns The server instance for method chaining
4127
- *
4128
- * @example
4129
- * ```typescript
4130
- * server.resourceTemplate({
4131
- * name: 'user-profile',
4132
- * resourceTemplate: {
4133
- * uriTemplate: 'user://{userId}/profile',
4134
- * name: 'User Profile',
4135
- * mimeType: 'application/json'
4136
- * },
4137
- * fn: async (uri, params) => ({
4138
- * contents: [{
4139
- * uri: uri.toString(),
4140
- * mimeType: 'application/json',
4141
- * text: JSON.stringify({ userId: params.userId, name: 'John Doe' })
4142
- * }]
4143
- * })
4144
- * })
4145
- * ```
4146
- */
4147
- resourceTemplate(resourceTemplateDefinition) {
4148
- const template = new import_mcp.ResourceTemplate(
4149
- resourceTemplateDefinition.resourceTemplate.uriTemplate,
4150
- {
4151
- list: void 0,
4152
- // Optional: callback to list all matching resources
4153
- complete: void 0
4154
- // Optional: callback for auto-completion
4155
- }
4156
- );
4157
- const metadata = {};
4158
- if (resourceTemplateDefinition.resourceTemplate.name) {
4159
- metadata.name = resourceTemplateDefinition.resourceTemplate.name;
4160
- }
4161
- if (resourceTemplateDefinition.title) {
4162
- metadata.title = resourceTemplateDefinition.title;
4163
- }
4164
- if (resourceTemplateDefinition.description || resourceTemplateDefinition.resourceTemplate.description) {
4165
- metadata.description = resourceTemplateDefinition.description || resourceTemplateDefinition.resourceTemplate.description;
4166
- }
4167
- if (resourceTemplateDefinition.resourceTemplate.mimeType) {
4168
- metadata.mimeType = resourceTemplateDefinition.resourceTemplate.mimeType;
4169
- }
4170
- if (resourceTemplateDefinition.annotations) {
4171
- metadata.annotations = resourceTemplateDefinition.annotations;
4172
- }
4173
- this.server.resource(
4174
- resourceTemplateDefinition.name,
4175
- template,
4176
- metadata,
4177
- async (uri) => {
4178
- const params = this.parseTemplateUri(
4179
- resourceTemplateDefinition.resourceTemplate.uriTemplate,
4180
- uri.toString()
4181
- );
4182
- return await resourceTemplateDefinition.fn(uri, params);
4183
- }
4184
- );
4185
- return this;
4186
- }
4187
- /**
4188
- * Define a tool that can be called by clients
4189
- *
4190
- * Registers a tool with the MCP server that clients can invoke with parameters.
4191
- * Tools are functions that perform actions, computations, or operations and
4192
- * return results. They accept structured input parameters and return structured output.
4193
- *
4194
- * @param toolDefinition - Configuration object containing tool metadata and handler function
4195
- * @param toolDefinition.name - Unique identifier for the tool
4196
- * @param toolDefinition.description - Human-readable description of what the tool does
4197
- * @param toolDefinition.inputs - Array of input parameter definitions with types and validation
4198
- * @param toolDefinition.fn - Async function that executes the tool logic with provided parameters
4199
- * @returns The server instance for method chaining
4200
- *
4201
- * @example
4202
- * ```typescript
4203
- * server.tool({
4204
- * name: 'calculate',
4205
- * description: 'Performs mathematical calculations',
4206
- * inputs: [
4207
- * { name: 'expression', type: 'string', required: true },
4208
- * { name: 'precision', type: 'number', required: false }
4209
- * ],
4210
- * fn: async ({ expression, precision = 2 }) => {
4211
- * const result = eval(expression)
4212
- * return { result: Number(result.toFixed(precision)) }
4213
- * }
4214
- * })
4215
- * ```
4216
- */
4217
- tool(toolDefinition) {
4218
- const inputSchema = this.createToolInputSchema(toolDefinition.inputs || []);
4219
- this.server.tool(
4220
- toolDefinition.name,
4221
- toolDefinition.description ?? "",
4222
- inputSchema,
4223
- async (params) => {
4224
- return await toolDefinition.fn(params);
4225
- }
4226
- );
4227
- return this;
4228
- }
4229
- /**
4230
- * Define a prompt template
4231
- *
4232
- * Registers a prompt template with the MCP server that clients can use to generate
4233
- * structured prompts for AI models. Prompt templates accept parameters and return
4234
- * formatted text that can be used as input to language models or other AI systems.
4235
- *
4236
- * @param promptDefinition - Configuration object containing prompt metadata and handler function
4237
- * @param promptDefinition.name - Unique identifier for the prompt template
4238
- * @param promptDefinition.description - Human-readable description of the prompt's purpose
4239
- * @param promptDefinition.args - Array of argument definitions with types and validation
4240
- * @param promptDefinition.fn - Async function that generates the prompt from provided arguments
4241
- * @returns The server instance for method chaining
4242
- *
4243
- * @example
4244
- * ```typescript
4245
- * server.prompt({
4246
- * name: 'code-review',
4247
- * description: 'Generates a code review prompt',
4248
- * args: [
4249
- * { name: 'language', type: 'string', required: true },
4250
- * { name: 'focus', type: 'string', required: false }
4251
- * ],
4252
- * fn: async ({ language, focus = 'general' }) => {
4253
- * return {
4254
- * messages: [{
4255
- * role: 'user',
4256
- * content: `Please review this ${language} code with focus on ${focus}...`
4257
- * }]
4258
- * }
4259
- * }
4260
- * })
4261
- * ```
4262
- */
4263
- prompt(promptDefinition) {
4264
- const argsSchema = this.createPromptArgsSchema(promptDefinition.args || []);
4265
- this.server.prompt(
4266
- promptDefinition.name,
4267
- promptDefinition.description ?? "",
4268
- argsSchema,
4269
- async (params) => {
4270
- return await promptDefinition.fn(params);
4271
- }
4272
- );
4273
- return this;
4274
- }
4275
- /**
4276
- * Mount MCP server endpoints at /mcp
4277
- *
4278
- * Sets up the HTTP transport layer for the MCP server, creating endpoints for
4279
- * Server-Sent Events (SSE) streaming, POST message handling, and DELETE session cleanup.
4280
- * Uses stateless mode for session management, making it suitable for stateless deployments.
4281
- *
4282
- * This method is called automatically when the server starts listening and ensures
4283
- * that MCP clients can communicate with the server over HTTP.
4284
- *
4285
- * @private
4286
- * @returns Promise that resolves when MCP endpoints are successfully mounted
4287
- *
4288
- * @example
4289
- * Endpoints created:
4290
- * - GET /mcp - SSE streaming endpoint for real-time communication
4291
- * - POST /mcp - Message handling endpoint for MCP protocol messages
4292
- * - DELETE /mcp - Session cleanup endpoint
4293
- */
4294
- async mountMcp() {
4295
- if (this.mcpMounted) return;
4296
- const { StreamableHTTPServerTransport } = await import("@modelcontextprotocol/sdk/server/streamableHttp.js");
4297
- const httpTransport = new StreamableHTTPServerTransport({
4298
- sessionIdGenerator: void 0
4299
- // Stateless mode
4300
- });
4301
- await this.server.connect(httpTransport);
4302
- const endpoint = "/mcp";
4303
- this.app.get(endpoint, async (req, res) => {
4304
- await httpTransport.handleRequest(req, res);
4305
- });
4306
- this.app.post(endpoint, import_express.default.json(), async (req, res) => {
4307
- await httpTransport.handleRequest(req, res, req.body);
4308
- });
4309
- this.app.delete(endpoint, async (req, res) => {
4310
- await httpTransport.handleRequest(req, res);
4311
- });
4312
- this.mcpMounted = true;
4313
- console.log(`[MCP] Server mounted at ${endpoint}`);
4314
- }
4315
- /**
4316
- * Start the Express server with MCP endpoints
4317
- *
4318
- * Initiates the server startup process by mounting MCP endpoints, configuring
4319
- * the inspector UI (if available), and starting the Express server to listen
4320
- * for incoming connections. This is the main entry point for running the server.
4321
- *
4322
- * The server will be accessible at the specified port with MCP endpoints at /mcp
4323
- * and inspector UI at /inspector (if the inspector package is installed).
4324
- *
4325
- * @param port - Port number to listen on (defaults to 3001 if not specified)
4326
- * @returns Promise that resolves when the server is successfully listening
4327
- *
4328
- * @example
4329
- * ```typescript
4330
- * await server.listen(8080)
4331
- * // Server now running at http://localhost:8080
4332
- * // MCP endpoints: http://localhost:8080/mcp
4333
- * // Inspector UI: http://localhost:8080/inspector
4334
- * ```
4335
- */
4336
- async listen(port) {
4337
- await this.mountMcp();
4338
- this.serverPort = port || 3001;
4339
- this.mountInspector();
4340
- this.app.listen(this.serverPort, () => {
4341
- console.log(`[SERVER] Listening on http://localhost:${this.serverPort}`);
4342
- console.log(`[MCP] Endpoints: http://localhost:${this.serverPort}/mcp`);
4343
- });
4344
- }
4345
- /**
4346
- * Mount MCP Inspector UI at /inspector
4347
- *
4348
- * Dynamically loads and mounts the MCP Inspector UI package if available, providing
4349
- * a web-based interface for testing and debugging MCP servers. The inspector
4350
- * automatically connects to the local MCP server endpoints.
4351
- *
4352
- * This method gracefully handles cases where the inspector package is not installed,
4353
- * allowing the server to function without the inspector in production environments.
4354
- *
4355
- * @private
4356
- * @returns void
4357
- *
4358
- * @example
4359
- * If @mcp-use/inspector is installed:
4360
- * - Inspector UI available at http://localhost:PORT/inspector
4361
- * - Automatically connects to http://localhost:PORT/mcp
4362
- *
4363
- * If not installed:
4364
- * - Server continues to function normally
4365
- * - No inspector UI available
4366
- */
4367
- mountInspector() {
4368
- if (this.inspectorMounted) return;
4369
- import("@mcp-use/inspector").then(({ mountInspector }) => {
4370
- const mcpServerUrl = `http://localhost:${this.serverPort}/mcp`;
4371
- mountInspector(this.app, "/inspector", mcpServerUrl);
4372
- this.inspectorMounted = true;
4373
- console.log(`[INSPECTOR] UI available at http://localhost:${this.serverPort}/inspector`);
4374
- }).catch(() => {
4375
- });
4376
- }
4377
- /**
4378
- * Setup default widget serving routes
4379
- *
4380
- * Configures Express routes to serve MCP UI widgets and their static assets.
4381
- * Widgets are served from the dist/resources/mcp-use/widgets directory and can
4382
- * be accessed via HTTP endpoints for embedding in web applications.
4383
- *
4384
- * Routes created:
4385
- * - GET /mcp-use/widgets/:widget - Serves widget's index.html
4386
- * - GET /mcp-use/widgets/:widget/assets/* - Serves widget-specific assets
4387
- * - GET /mcp-use/widgets/assets/* - Fallback asset serving with auto-discovery
4388
- *
4389
- * @private
4390
- * @returns void
4391
- *
4392
- * @example
4393
- * Widget routes:
4394
- * - http://localhost:3001/mcp-use/widgets/kanban-board
4395
- * - http://localhost:3001/mcp-use/widgets/todo-list/assets/style.css
4396
- * - http://localhost:3001/mcp-use/widgets/assets/script.js (auto-discovered)
4397
- */
4398
- setupWidgetRoutes() {
4399
- this.app.get("/mcp-use/widgets/:widget/assets/*", (req, res, next) => {
4400
- const widget = req.params.widget;
4401
- const assetFile = req.params[0];
4402
- const assetPath = (0, import_node_path2.join)(process.cwd(), "dist", "resources", "mcp-use", "widgets", widget, "assets", assetFile);
4403
- res.sendFile(assetPath, (err) => err ? next() : void 0);
4404
- });
4405
- this.app.get("/mcp-use/widgets/assets/*", (req, res, next) => {
4406
- const assetFile = req.params[0];
4407
- const widgetsDir = (0, import_node_path2.join)(process.cwd(), "dist", "resources", "mcp-use", "widgets");
4408
- try {
4409
- const widgets = (0, import_node_fs3.readdirSync)(widgetsDir);
4410
- for (const widget of widgets) {
4411
- const assetPath = (0, import_node_path2.join)(widgetsDir, widget, "assets", assetFile);
4412
- if ((0, import_node_fs3.existsSync)(assetPath)) {
4413
- return res.sendFile(assetPath);
4414
- }
4415
- }
4416
- next();
4417
- } catch {
4418
- next();
4419
- }
4420
- });
4421
- this.app.get("/mcp-use/widgets/:widget", (req, res, next) => {
4422
- const filePath = (0, import_node_path2.join)(process.cwd(), "dist", "resources", "mcp-use", "widgets", req.params.widget, "index.html");
4423
- res.sendFile(filePath, (err) => err ? next() : void 0);
4424
- });
4425
- }
4426
- /**
4427
- * Create input schema for resource templates
4428
- *
4429
- * Parses a URI template string to extract parameter names and generates a Zod
4430
- * validation schema for those parameters. Used internally for validating resource
4431
- * template parameters before processing requests.
4432
- *
4433
- * @param uriTemplate - URI template string with parameter placeholders (e.g., "/users/{id}/posts/{postId}")
4434
- * @returns Object mapping parameter names to Zod string schemas
4435
- *
4436
- * @example
4437
- * ```typescript
4438
- * const schema = this.createInputSchema("/users/{id}/posts/{postId}")
4439
- * // Returns: { id: z.string(), postId: z.string() }
4440
- * ```
4441
- */
4442
- createInputSchema(uriTemplate) {
4443
- const params = this.extractTemplateParams(uriTemplate);
4444
- const schema = {};
4445
- params.forEach((param) => {
4446
- schema[param] = import_zod7.z.string();
4447
- });
4448
- return schema;
4449
- }
4450
- /**
4451
- * Create input schema for tools
4452
- *
4453
- * Converts tool input definitions into Zod validation schemas for runtime validation.
4454
- * Supports common data types (string, number, boolean, object, array) and optional
4455
- * parameters. Used internally when registering tools with the MCP server.
4456
- *
4457
- * @param inputs - Array of input parameter definitions with name, type, and optional flag
4458
- * @returns Object mapping parameter names to Zod validation schemas
4459
- *
4460
- * @example
4461
- * ```typescript
4462
- * const schema = this.createToolInputSchema([
4463
- * { name: 'query', type: 'string', required: true },
4464
- * { name: 'limit', type: 'number', required: false }
4465
- * ])
4466
- * // Returns: { query: z.string(), limit: z.number().optional() }
4467
- * ```
4468
- */
4469
- createToolInputSchema(inputs) {
4470
- const schema = {};
4471
- inputs.forEach((input) => {
4472
- let zodType;
4473
- switch (input.type) {
4474
- case "string":
4475
- zodType = import_zod7.z.string();
4476
- break;
4477
- case "number":
4478
- zodType = import_zod7.z.number();
4479
- break;
4480
- case "boolean":
4481
- zodType = import_zod7.z.boolean();
4482
- break;
4483
- case "object":
4484
- zodType = import_zod7.z.object({});
4485
- break;
4486
- case "array":
4487
- zodType = import_zod7.z.array(import_zod7.z.any());
4488
- break;
4489
- default:
4490
- zodType = import_zod7.z.any();
4491
- }
4492
- if (!input.required) {
4493
- zodType = zodType.optional();
4494
- }
4495
- schema[input.name] = zodType;
4496
- });
4497
- return schema;
4498
- }
4499
- /**
4500
- * Create arguments schema for prompts
4501
- *
4502
- * Converts prompt argument definitions into Zod validation schemas for runtime validation.
4503
- * Supports common data types (string, number, boolean, object, array) and optional
4504
- * parameters. Used internally when registering prompt templates with the MCP server.
4505
- *
4506
- * @param inputs - Array of argument definitions with name, type, and optional flag
4507
- * @returns Object mapping argument names to Zod validation schemas
4508
- *
4509
- * @example
4510
- * ```typescript
4511
- * const schema = this.createPromptArgsSchema([
4512
- * { name: 'topic', type: 'string', required: true },
4513
- * { name: 'style', type: 'string', required: false }
4514
- * ])
4515
- * // Returns: { topic: z.string(), style: z.string().optional() }
4516
- * ```
4517
- */
4518
- createPromptArgsSchema(inputs) {
4519
- const schema = {};
4520
- inputs.forEach((input) => {
4521
- let zodType;
4522
- switch (input.type) {
4523
- case "string":
4524
- zodType = import_zod7.z.string();
4525
- break;
4526
- case "number":
4527
- zodType = import_zod7.z.number();
4528
- break;
4529
- case "boolean":
4530
- zodType = import_zod7.z.boolean();
4531
- break;
4532
- case "object":
4533
- zodType = import_zod7.z.object({});
4534
- break;
4535
- case "array":
4536
- zodType = import_zod7.z.array(import_zod7.z.any());
4537
- break;
4538
- default:
4539
- zodType = import_zod7.z.any();
4540
- }
4541
- if (!input.required) {
4542
- zodType = zodType.optional();
4543
- }
4544
- schema[input.name] = zodType;
4545
- });
4546
- return schema;
4547
- }
4548
- /**
4549
- * Extract parameter names from URI template
4550
- *
4551
- * Parses a URI template string to extract parameter names enclosed in curly braces.
4552
- * Used internally to identify dynamic parameters in resource templates and generate
4553
- * appropriate validation schemas.
4554
- *
4555
- * @param uriTemplate - URI template string with parameter placeholders (e.g., "/users/{id}/posts/{postId}")
4556
- * @returns Array of parameter names found in the template
4557
- *
4558
- * @example
4559
- * ```typescript
4560
- * const params = this.extractTemplateParams("/users/{id}/posts/{postId}")
4561
- * // Returns: ["id", "postId"]
4562
- * ```
4563
- */
4564
- extractTemplateParams(uriTemplate) {
4565
- const matches = uriTemplate.match(/\{([^}]+)\}/g);
4566
- return matches ? matches.map((match) => match.slice(1, -1)) : [];
4567
- }
4568
- /**
4569
- * Parse parameter values from a URI based on a template
4570
- *
4571
- * Extracts parameter values from an actual URI by matching it against a URI template.
4572
- * The template contains placeholders like {param} which are extracted as key-value pairs.
4573
- *
4574
- * @param template - URI template with placeholders (e.g., "user://{userId}/posts/{postId}")
4575
- * @param uri - Actual URI to parse (e.g., "user://123/posts/456")
4576
- * @returns Object mapping parameter names to their values
4577
- *
4578
- * @example
4579
- * ```typescript
4580
- * const params = this.parseTemplateUri("user://{userId}/posts/{postId}", "user://123/posts/456")
4581
- * // Returns: { userId: "123", postId: "456" }
4582
- * ```
4583
- */
4584
- parseTemplateUri(template, uri) {
4585
- const params = {};
4586
- let regexPattern = template.replace(/[.*+?^$()[\]\\|]/g, "\\$&");
4587
- const paramNames = [];
4588
- regexPattern = regexPattern.replace(/\\\{([^}]+)\\\}/g, (_, paramName) => {
4589
- paramNames.push(paramName);
4590
- return "([^/]+)";
4591
- });
4592
- const regex = new RegExp(`^${regexPattern}$`);
4593
- const match = uri.match(regex);
4594
- if (match) {
4595
- paramNames.forEach((paramName, index) => {
4596
- params[paramName] = match[index + 1];
4597
- });
4598
- }
4599
- return params;
4600
- }
4601
- };
4602
- function createMCPServer(name, config2 = {}) {
4603
- const instance = new McpServer({
4604
- name,
4605
- version: config2.version || "1.0.0",
4606
- description: config2.description
4607
- });
4608
- return instance;
4609
- }
4610
- __name(createMCPServer, "createMCPServer");
4611
-
4612
4002
  // src/oauth-helper.ts
4613
4003
  var OAuthHelper = class {
4614
4004
  static {
@@ -5957,7 +5347,6 @@ var import_messages3 = require("@langchain/core/messages");
5957
5347
  Telemetry,
5958
5348
  ToolMessage,
5959
5349
  WebSocketConnector,
5960
- createMCPServer,
5961
5350
  createOAuthMCPConfig,
5962
5351
  createReadableStreamFromGenerator,
5963
5352
  loadConfigFile,