@mastra/mcp 0.13.3 → 0.13.4

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
@@ -36,13 +36,50 @@ var equal__default = /*#__PURE__*/_interopDefault(equal);
36
36
  var ElicitationClientActions = class {
37
37
  client;
38
38
  logger;
39
+ /**
40
+ * @internal
41
+ */
39
42
  constructor({ client, logger }) {
40
43
  this.client = client;
41
44
  this.logger = logger;
42
45
  }
43
46
  /**
44
- * Set a handler for elicitation requests.
45
- * @param handler The callback function to handle the elicitation request.
47
+ * Sets a handler function for processing elicitation requests from the server.
48
+ *
49
+ * The handler is called when the server needs to collect user input during tool execution.
50
+ * The handler must return a response with action ('accept', 'decline', or 'cancel') and
51
+ * optional content matching the requested schema.
52
+ *
53
+ * @param handler - Callback function to handle elicitation requests
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * client.elicitation.onRequest(async (request) => {
58
+ * console.log('Server message:', request.message);
59
+ * console.log('Requested schema:', request.requestedSchema);
60
+ *
61
+ * // Collect user input (e.g., via CLI prompt or UI form)
62
+ * const userInput = await collectUserInput(request.requestedSchema);
63
+ *
64
+ * return {
65
+ * action: 'accept',
66
+ * content: userInput
67
+ * };
68
+ * });
69
+ * ```
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * // Declining an elicitation request
74
+ * client.elicitation.onRequest(async (request) => {
75
+ * if (!shouldAcceptRequest(request)) {
76
+ * return { action: 'decline' };
77
+ * }
78
+ *
79
+ * const input = await getInput();
80
+ * return { action: 'accept', content: input };
81
+ * });
82
+ * ```
46
83
  */
47
84
  onRequest(handler) {
48
85
  this.client.setElicitationRequestHandler(handler);
@@ -51,13 +88,28 @@ var ElicitationClientActions = class {
51
88
  var PromptClientActions = class {
52
89
  client;
53
90
  logger;
91
+ /**
92
+ * @internal
93
+ */
54
94
  constructor({ client, logger }) {
55
95
  this.client = client;
56
96
  this.logger = logger;
57
97
  }
58
98
  /**
59
- * Get all prompts from the connected MCP server.
60
- * @returns A list of prompts with their versions.
99
+ * Retrieves all available prompts from the connected MCP server.
100
+ *
101
+ * Returns an empty array if the server doesn't support prompts (MethodNotFound error).
102
+ *
103
+ * @returns Promise resolving to array of prompts with their metadata
104
+ * @throws {Error} If fetching prompts fails (excluding MethodNotFound)
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * const prompts = await client.prompts.list();
109
+ * prompts.forEach(prompt => {
110
+ * console.log(`${prompt.name} (v${prompt.version}): ${prompt.description}`);
111
+ * });
112
+ * ```
61
113
  */
62
114
  async list() {
63
115
  try {
@@ -83,11 +135,32 @@ var PromptClientActions = class {
83
135
  }
84
136
  }
85
137
  /**
86
- * Get a specific prompt.
87
- * @param name The name of the prompt to get.
88
- * @param args Optional arguments for the prompt.
89
- * @param version Optional version of the prompt to get.
90
- * @returns The prompt content.
138
+ * Retrieves a specific prompt with its messages from the MCP server.
139
+ *
140
+ * Prompts can accept arguments to parameterize the template. The returned messages
141
+ * can be used directly in AI chat completions.
142
+ *
143
+ * @param params - Parameters for the prompt request
144
+ * @param params.name - Name of the prompt to retrieve
145
+ * @param params.args - Optional arguments to populate the prompt template
146
+ * @param params.version - Optional specific version of the prompt to retrieve
147
+ * @returns Promise resolving to the prompt result with messages
148
+ * @throws {Error} If fetching the prompt fails or prompt not found
149
+ *
150
+ * @example
151
+ * ```typescript
152
+ * const prompt = await client.prompts.get({
153
+ * name: 'code-review',
154
+ * args: {
155
+ * language: 'typescript',
156
+ * code: 'const x = 1;'
157
+ * },
158
+ * version: '1.0'
159
+ * });
160
+ *
161
+ * // Use prompt messages in AI completion
162
+ * console.log(prompt.messages);
163
+ * ```
91
164
  */
92
165
  async get({
93
166
  name,
@@ -97,8 +170,20 @@ var PromptClientActions = class {
97
170
  return this.client.getPrompt({ name, args, version });
98
171
  }
99
172
  /**
100
- * Set a notification handler for when the list of available prompts changes.
101
- * @param handler The callback function to handle the notification.
173
+ * Sets a notification handler for when the list of available prompts changes.
174
+ *
175
+ * The handler is called when prompts are added, removed, or modified on the server.
176
+ *
177
+ * @param handler - Callback function invoked when the prompt list changes
178
+ *
179
+ * @example
180
+ * ```typescript
181
+ * await client.prompts.onListChanged(async () => {
182
+ * console.log('Prompt list changed, re-fetching...');
183
+ * const prompts = await client.prompts.list();
184
+ * console.log('Available prompts:', prompts.map(p => p.name));
185
+ * });
186
+ * ```
102
187
  */
103
188
  async onListChanged(handler) {
104
189
  this.client.setPromptListChangedNotificationHandler(handler);
@@ -107,13 +192,28 @@ var PromptClientActions = class {
107
192
  var ResourceClientActions = class {
108
193
  client;
109
194
  logger;
195
+ /**
196
+ * @internal
197
+ */
110
198
  constructor({ client, logger }) {
111
199
  this.client = client;
112
200
  this.logger = logger;
113
201
  }
114
202
  /**
115
- * Get all resources from the connected MCP server.
116
- * @returns A list of resources.
203
+ * Retrieves all available resources from the connected MCP server.
204
+ *
205
+ * Returns an empty array if the server doesn't support resources (MethodNotFound error).
206
+ *
207
+ * @returns Promise resolving to array of resources
208
+ * @throws {Error} If fetching resources fails (excluding MethodNotFound)
209
+ *
210
+ * @example
211
+ * ```typescript
212
+ * const resources = await client.resources.list();
213
+ * resources.forEach(resource => {
214
+ * console.log(`${resource.name}: ${resource.uri}`);
215
+ * });
216
+ * ```
117
217
  */
118
218
  async list() {
119
219
  try {
@@ -139,8 +239,21 @@ var ResourceClientActions = class {
139
239
  }
140
240
  }
141
241
  /**
142
- * Get all resource templates from the connected MCP server.
143
- * @returns A list of resource templates.
242
+ * Retrieves all available resource templates from the connected MCP server.
243
+ *
244
+ * Resource templates are URI templates (RFC 6570) that describe dynamic resources.
245
+ * Returns an empty array if the server doesn't support resource templates.
246
+ *
247
+ * @returns Promise resolving to array of resource templates
248
+ * @throws {Error} If fetching resource templates fails (excluding MethodNotFound)
249
+ *
250
+ * @example
251
+ * ```typescript
252
+ * const templates = await client.resources.templates();
253
+ * templates.forEach(template => {
254
+ * console.log(`${template.name}: ${template.uriTemplate}`);
255
+ * });
256
+ * ```
144
257
  */
145
258
  async templates() {
146
259
  try {
@@ -167,37 +280,92 @@ var ResourceClientActions = class {
167
280
  }
168
281
  }
169
282
  /**
170
- * Read a specific resource.
171
- * @param uri The URI of the resource to read.
172
- * @returns The resource content.
283
+ * Reads the content of a specific resource from the MCP server.
284
+ *
285
+ * @param uri - URI of the resource to read (e.g., 'file://path/to/file.txt')
286
+ * @returns Promise resolving to the resource content
287
+ * @throws {Error} If reading the resource fails or resource not found
288
+ *
289
+ * @example
290
+ * ```typescript
291
+ * const result = await client.resources.read('file://data/config.json');
292
+ * console.log(result.contents[0].text); // Resource text content
293
+ * ```
173
294
  */
174
295
  async read(uri) {
175
296
  return this.client.readResource(uri);
176
297
  }
177
298
  /**
178
- * Subscribe to a specific resource.
179
- * @param uri The URI of the resource to subscribe to.
299
+ * Subscribes to updates for a specific resource.
300
+ *
301
+ * After subscribing, you'll receive notifications via the `onUpdated` handler
302
+ * when the resource content changes.
303
+ *
304
+ * @param uri - URI of the resource to subscribe to
305
+ * @returns Promise resolving when subscription is established
306
+ * @throws {Error} If subscription fails
307
+ *
308
+ * @example
309
+ * ```typescript
310
+ * await client.resources.subscribe('file://data/config.json');
311
+ * ```
180
312
  */
181
313
  async subscribe(uri) {
182
314
  return this.client.subscribeResource(uri);
183
315
  }
184
316
  /**
185
- * Unsubscribe from a specific resource.
186
- * @param uri The URI of the resource to unsubscribe from.
317
+ * Unsubscribes from updates for a specific resource.
318
+ *
319
+ * Stops receiving notifications for this resource URI.
320
+ *
321
+ * @param uri - URI of the resource to unsubscribe from
322
+ * @returns Promise resolving when unsubscription is complete
323
+ * @throws {Error} If unsubscription fails
324
+ *
325
+ * @example
326
+ * ```typescript
327
+ * await client.resources.unsubscribe('file://data/config.json');
328
+ * ```
187
329
  */
188
330
  async unsubscribe(uri) {
189
331
  return this.client.unsubscribeResource(uri);
190
332
  }
191
333
  /**
192
- * Set a notification handler for when a specific resource is updated.
193
- * @param handler The callback function to handle the notification.
334
+ * Sets a notification handler for when subscribed resources are updated.
335
+ *
336
+ * The handler is called whenever the server sends a resource update notification
337
+ * for any resource you've subscribed to.
338
+ *
339
+ * @param handler - Callback function receiving the updated resource URI
340
+ *
341
+ * @example
342
+ * ```typescript
343
+ * await client.resources.onUpdated(async (params) => {
344
+ * console.log(`Resource updated: ${params.uri}`);
345
+ * // Re-fetch the resource
346
+ * const content = await client.resources.read(params.uri);
347
+ * console.log('New content:', content);
348
+ * });
349
+ * ```
194
350
  */
195
351
  async onUpdated(handler) {
196
352
  this.client.setResourceUpdatedNotificationHandler(handler);
197
353
  }
198
354
  /**
199
- * Set a notification handler for when the list of available resources changes.
200
- * @param handler The callback function to handle the notification.
355
+ * Sets a notification handler for when the list of available resources changes.
356
+ *
357
+ * The handler is called when resources are added or removed from the server.
358
+ *
359
+ * @param handler - Callback function invoked when the resource list changes
360
+ *
361
+ * @example
362
+ * ```typescript
363
+ * await client.resources.onListChanged(async () => {
364
+ * console.log('Resource list changed, re-fetching...');
365
+ * const resources = await client.resources.list();
366
+ * console.log('Updated resource count:', resources.length);
367
+ * });
368
+ * ```
201
369
  */
202
370
  async onListChanged(handler) {
203
371
  this.client.setResourceListChangedNotificationHandler(handler);
@@ -232,9 +400,15 @@ var InternalMastraMCPClient = class extends base.MastraBase {
232
400
  serverConfig;
233
401
  transport;
234
402
  currentOperationContext = null;
403
+ /** Provides access to resource operations (list, read, subscribe, etc.) */
235
404
  resources;
405
+ /** Provides access to prompt operations (list, get, notifications) */
236
406
  prompts;
407
+ /** Provides access to elicitation operations (request handling) */
237
408
  elicitation;
409
+ /**
410
+ * @internal
411
+ */
238
412
  constructor({
239
413
  name,
240
414
  version = "1.0.0",
@@ -357,6 +531,17 @@ var InternalMastraMCPClient = class extends base.MastraBase {
357
531
  }
358
532
  }
359
533
  isConnected = null;
534
+ /**
535
+ * Connects to the MCP server using the configured transport.
536
+ *
537
+ * Automatically detects transport type based on configuration (stdio vs HTTP).
538
+ * Safe to call multiple times - returns existing connection if already connected.
539
+ *
540
+ * @returns Promise resolving to true when connected
541
+ * @throws {MastraError} If connection fails
542
+ *
543
+ * @internal
544
+ */
360
545
  async connect() {
361
546
  if (await this.isConnected) {
362
547
  return true;
@@ -397,8 +582,13 @@ var InternalMastraMCPClient = class extends base.MastraBase {
397
582
  return this.isConnected;
398
583
  }
399
584
  /**
400
- * Get the current session ID if using the Streamable HTTP transport.
401
- * Returns undefined if not connected or not using Streamable HTTP.
585
+ * Gets the current session ID if using Streamable HTTP transport.
586
+ *
587
+ * Returns undefined if not connected or not using Streamable HTTP transport.
588
+ *
589
+ * @returns Session ID string or undefined
590
+ *
591
+ * @internal
402
592
  */
403
593
  get sessionId() {
404
594
  if (this.transport instanceof streamableHttp_js$1.StreamableHTTPClientTransport) {
@@ -650,6 +840,34 @@ var MCPClient = class extends base.MastraBase {
650
840
  defaultTimeout;
651
841
  mcpClientsById = /* @__PURE__ */ new Map();
652
842
  disconnectPromise = null;
843
+ /**
844
+ * Creates a new MCPClient instance for managing MCP server connections.
845
+ *
846
+ * The client automatically manages connection lifecycle and prevents memory leaks by
847
+ * caching instances with identical configurations.
848
+ *
849
+ * @param args - Configuration options
850
+ * @param args.id - Optional unique identifier to allow multiple instances with same config
851
+ * @param args.servers - Map of server names to server configurations
852
+ * @param args.timeout - Optional global timeout in milliseconds (default: 60000)
853
+ *
854
+ * @throws {Error} If multiple instances with identical config are created without an ID
855
+ *
856
+ * @example
857
+ * ```typescript
858
+ * const mcp = new MCPClient({
859
+ * servers: {
860
+ * weatherServer: {
861
+ * url: new URL('http://localhost:8080/sse'),
862
+ * requestInit: {
863
+ * headers: { Authorization: 'Bearer token' }
864
+ * }
865
+ * }
866
+ * },
867
+ * timeout: 30000
868
+ * });
869
+ * ```
870
+ */
653
871
  constructor(args) {
654
872
  super({ name: "MCPClient" });
655
873
  this.defaultTimeout = args.timeout ?? protocol_js.DEFAULT_REQUEST_TIMEOUT_MSEC;
@@ -687,9 +905,48 @@ To fix this you have three different options:
687
905
  this.addToInstanceCache();
688
906
  return this;
689
907
  }
908
+ /**
909
+ * Provides access to elicitation-related operations for interactive user input collection.
910
+ *
911
+ * Elicitation allows MCP servers to request structured information from users during tool execution.
912
+ *
913
+ * @example
914
+ * ```typescript
915
+ * // Set up handler for elicitation requests from a server
916
+ * await mcp.elicitation.onRequest('serverName', async (request) => {
917
+ * console.log(`Server requests: ${request.message}`);
918
+ * console.log('Schema:', request.requestedSchema);
919
+ *
920
+ * // Collect user input and return response
921
+ * return {
922
+ * action: 'accept',
923
+ * content: { name: 'John Doe', email: 'john@example.com' }
924
+ * };
925
+ * });
926
+ * ```
927
+ */
690
928
  get elicitation() {
691
929
  this.addToInstanceCache();
692
930
  return {
931
+ /**
932
+ * Sets up a handler function for elicitation requests from a specific server.
933
+ *
934
+ * The handler receives requests for user input and must return a response with
935
+ * action ('accept', 'decline', or 'cancel') and optional content.
936
+ *
937
+ * @param serverName - Name of the server to handle elicitation requests for
938
+ * @param handler - Function to handle elicitation requests
939
+ * @throws {MastraError} If setting up the handler fails
940
+ *
941
+ * @example
942
+ * ```typescript
943
+ * await mcp.elicitation.onRequest('weatherServer', async (request) => {
944
+ * // Prompt user for input
945
+ * const userInput = await promptUser(request.requestedSchema);
946
+ * return { action: 'accept', content: userInput };
947
+ * });
948
+ * ```
949
+ */
693
950
  onRequest: async (serverName, handler) => {
694
951
  try {
695
952
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -710,9 +967,46 @@ To fix this you have three different options:
710
967
  }
711
968
  };
712
969
  }
970
+ /**
971
+ * Provides access to resource-related operations across all configured servers.
972
+ *
973
+ * Resources represent data exposed by MCP servers (files, database records, API responses, etc.).
974
+ *
975
+ * @example
976
+ * ```typescript
977
+ * // List all resources from all servers
978
+ * const allResources = await mcp.resources.list();
979
+ * Object.entries(allResources).forEach(([serverName, resources]) => {
980
+ * console.log(`${serverName}: ${resources.length} resources`);
981
+ * });
982
+ *
983
+ * // Read a specific resource
984
+ * const content = await mcp.resources.read('weatherServer', 'file://data.json');
985
+ *
986
+ * // Subscribe to resource updates
987
+ * await mcp.resources.subscribe('weatherServer', 'file://data.json');
988
+ * await mcp.resources.onUpdated('weatherServer', async (params) => {
989
+ * console.log(`Resource updated: ${params.uri}`);
990
+ * });
991
+ * ```
992
+ */
713
993
  get resources() {
714
994
  this.addToInstanceCache();
715
995
  return {
996
+ /**
997
+ * Lists all available resources from all configured servers.
998
+ *
999
+ * Returns a map of server names to their resource arrays. Errors for individual
1000
+ * servers are logged but don't throw - failed servers return empty arrays.
1001
+ *
1002
+ * @returns Promise resolving to object mapping server names to resource arrays
1003
+ *
1004
+ * @example
1005
+ * ```typescript
1006
+ * const resources = await mcp.resources.list();
1007
+ * console.log(resources.weatherServer); // Array of resources
1008
+ * ```
1009
+ */
716
1010
  list: async () => {
717
1011
  const allResources = {};
718
1012
  for (const serverName of Object.keys(this.serverConfigs)) {
@@ -737,6 +1031,20 @@ To fix this you have three different options:
737
1031
  }
738
1032
  return allResources;
739
1033
  },
1034
+ /**
1035
+ * Lists all available resource templates from all configured servers.
1036
+ *
1037
+ * Resource templates are URI templates (RFC 6570) describing dynamic resources.
1038
+ * Errors for individual servers are logged but don't throw.
1039
+ *
1040
+ * @returns Promise resolving to object mapping server names to template arrays
1041
+ *
1042
+ * @example
1043
+ * ```typescript
1044
+ * const templates = await mcp.resources.templates();
1045
+ * console.log(templates.weatherServer); // Array of resource templates
1046
+ * ```
1047
+ */
740
1048
  templates: async () => {
741
1049
  const allTemplates = {};
742
1050
  for (const serverName of Object.keys(this.serverConfigs)) {
@@ -761,6 +1069,20 @@ To fix this you have three different options:
761
1069
  }
762
1070
  return allTemplates;
763
1071
  },
1072
+ /**
1073
+ * Reads the content of a specific resource from a server.
1074
+ *
1075
+ * @param serverName - Name of the server to read from
1076
+ * @param uri - URI of the resource to read
1077
+ * @returns Promise resolving to the resource content
1078
+ * @throws {MastraError} If reading the resource fails
1079
+ *
1080
+ * @example
1081
+ * ```typescript
1082
+ * const content = await mcp.resources.read('weatherServer', 'file://config.json');
1083
+ * console.log(content.contents[0].text);
1084
+ * ```
1085
+ */
764
1086
  read: async (serverName, uri) => {
765
1087
  try {
766
1088
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -780,6 +1102,19 @@ To fix this you have three different options:
780
1102
  );
781
1103
  }
782
1104
  },
1105
+ /**
1106
+ * Subscribes to updates for a specific resource on a server.
1107
+ *
1108
+ * @param serverName - Name of the server
1109
+ * @param uri - URI of the resource to subscribe to
1110
+ * @returns Promise resolving when subscription is established
1111
+ * @throws {MastraError} If subscription fails
1112
+ *
1113
+ * @example
1114
+ * ```typescript
1115
+ * await mcp.resources.subscribe('weatherServer', 'file://config.json');
1116
+ * ```
1117
+ */
783
1118
  subscribe: async (serverName, uri) => {
784
1119
  try {
785
1120
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -799,6 +1134,19 @@ To fix this you have three different options:
799
1134
  );
800
1135
  }
801
1136
  },
1137
+ /**
1138
+ * Unsubscribes from updates for a specific resource on a server.
1139
+ *
1140
+ * @param serverName - Name of the server
1141
+ * @param uri - URI of the resource to unsubscribe from
1142
+ * @returns Promise resolving when unsubscription is complete
1143
+ * @throws {MastraError} If unsubscription fails
1144
+ *
1145
+ * @example
1146
+ * ```typescript
1147
+ * await mcp.resources.unsubscribe('weatherServer', 'file://config.json');
1148
+ * ```
1149
+ */
802
1150
  unsubscribe: async (serverName, uri) => {
803
1151
  try {
804
1152
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -818,6 +1166,22 @@ To fix this you have three different options:
818
1166
  );
819
1167
  }
820
1168
  },
1169
+ /**
1170
+ * Sets a notification handler for when subscribed resources are updated on a server.
1171
+ *
1172
+ * @param serverName - Name of the server to monitor
1173
+ * @param handler - Callback function receiving the updated resource URI
1174
+ * @returns Promise resolving when handler is registered
1175
+ * @throws {MastraError} If setting up the handler fails
1176
+ *
1177
+ * @example
1178
+ * ```typescript
1179
+ * await mcp.resources.onUpdated('weatherServer', async (params) => {
1180
+ * console.log(`Resource updated: ${params.uri}`);
1181
+ * const content = await mcp.resources.read('weatherServer', params.uri);
1182
+ * });
1183
+ * ```
1184
+ */
821
1185
  onUpdated: async (serverName, handler) => {
822
1186
  try {
823
1187
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -836,6 +1200,22 @@ To fix this you have three different options:
836
1200
  );
837
1201
  }
838
1202
  },
1203
+ /**
1204
+ * Sets a notification handler for when the resource list changes on a server.
1205
+ *
1206
+ * @param serverName - Name of the server to monitor
1207
+ * @param handler - Callback function invoked when resources are added/removed
1208
+ * @returns Promise resolving when handler is registered
1209
+ * @throws {MastraError} If setting up the handler fails
1210
+ *
1211
+ * @example
1212
+ * ```typescript
1213
+ * await mcp.resources.onListChanged('weatherServer', async () => {
1214
+ * console.log('Resource list changed, re-fetching...');
1215
+ * const resources = await mcp.resources.list();
1216
+ * });
1217
+ * ```
1218
+ */
839
1219
  onListChanged: async (serverName, handler) => {
840
1220
  try {
841
1221
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -856,9 +1236,45 @@ To fix this you have three different options:
856
1236
  }
857
1237
  };
858
1238
  }
1239
+ /**
1240
+ * Provides access to prompt-related operations across all configured servers.
1241
+ *
1242
+ * Prompts are reusable message templates exposed by MCP servers that can be parameterized
1243
+ * and used for AI interactions.
1244
+ *
1245
+ * @example
1246
+ * ```typescript
1247
+ * // List all prompts from all servers
1248
+ * const allPrompts = await mcp.prompts.list();
1249
+ * Object.entries(allPrompts).forEach(([serverName, prompts]) => {
1250
+ * console.log(`${serverName}: ${prompts.map(p => p.name).join(', ')}`);
1251
+ * });
1252
+ *
1253
+ * // Get a specific prompt with arguments
1254
+ * const prompt = await mcp.prompts.get({
1255
+ * serverName: 'weatherServer',
1256
+ * name: 'forecast-template',
1257
+ * args: { city: 'London', days: 7 }
1258
+ * });
1259
+ * ```
1260
+ */
859
1261
  get prompts() {
860
1262
  this.addToInstanceCache();
861
1263
  return {
1264
+ /**
1265
+ * Lists all available prompts from all configured servers.
1266
+ *
1267
+ * Returns a map of server names to their prompt arrays. Errors for individual
1268
+ * servers are logged but don't throw - failed servers return empty arrays.
1269
+ *
1270
+ * @returns Promise resolving to object mapping server names to prompt arrays
1271
+ *
1272
+ * @example
1273
+ * ```typescript
1274
+ * const prompts = await mcp.prompts.list();
1275
+ * console.log(prompts.weatherServer); // Array of prompts
1276
+ * ```
1277
+ */
862
1278
  list: async () => {
863
1279
  const allPrompts = {};
864
1280
  for (const serverName of Object.keys(this.serverConfigs)) {
@@ -883,6 +1299,28 @@ To fix this you have three different options:
883
1299
  }
884
1300
  return allPrompts;
885
1301
  },
1302
+ /**
1303
+ * Retrieves a specific prompt with its messages from a server.
1304
+ *
1305
+ * @param params - Parameters for the prompt request
1306
+ * @param params.serverName - Name of the server to retrieve from
1307
+ * @param params.name - Name of the prompt to retrieve
1308
+ * @param params.args - Optional arguments to populate the prompt template
1309
+ * @param params.version - Optional specific version of the prompt
1310
+ * @returns Promise resolving to the prompt result with messages
1311
+ * @throws {MastraError} If fetching the prompt fails
1312
+ *
1313
+ * @example
1314
+ * ```typescript
1315
+ * const prompt = await mcp.prompts.get({
1316
+ * serverName: 'weatherServer',
1317
+ * name: 'forecast',
1318
+ * args: { city: 'London' },
1319
+ * version: '1.0'
1320
+ * });
1321
+ * console.log(prompt.messages);
1322
+ * ```
1323
+ */
886
1324
  get: async ({
887
1325
  serverName,
888
1326
  name,
@@ -907,6 +1345,22 @@ To fix this you have three different options:
907
1345
  );
908
1346
  }
909
1347
  },
1348
+ /**
1349
+ * Sets a notification handler for when the prompt list changes on a server.
1350
+ *
1351
+ * @param serverName - Name of the server to monitor
1352
+ * @param handler - Callback function invoked when prompts are added/removed/modified
1353
+ * @returns Promise resolving when handler is registered
1354
+ * @throws {MastraError} If setting up the handler fails
1355
+ *
1356
+ * @example
1357
+ * ```typescript
1358
+ * await mcp.prompts.onListChanged('weatherServer', async () => {
1359
+ * console.log('Prompt list changed, re-fetching...');
1360
+ * const prompts = await mcp.prompts.list();
1361
+ * });
1362
+ * ```
1363
+ */
910
1364
  onListChanged: async (serverName, handler) => {
911
1365
  try {
912
1366
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -937,6 +1391,21 @@ To fix this you have three different options:
937
1391
  const idNamespace = uuid.v5(`MCPClient`, uuid.v5.DNS);
938
1392
  return uuid.v5(text, idNamespace);
939
1393
  }
1394
+ /**
1395
+ * Disconnects from all MCP servers and cleans up resources.
1396
+ *
1397
+ * This method gracefully closes all server connections and clears internal caches.
1398
+ * Safe to call multiple times - subsequent calls will wait for the first disconnect to complete.
1399
+ *
1400
+ * @example
1401
+ * ```typescript
1402
+ * // Cleanup on application shutdown
1403
+ * process.on('SIGTERM', async () => {
1404
+ * await mcp.disconnect();
1405
+ * process.exit(0);
1406
+ * });
1407
+ * ```
1408
+ */
940
1409
  async disconnect() {
941
1410
  if (this.disconnectPromise) {
942
1411
  return this.disconnectPromise;
@@ -952,6 +1421,25 @@ To fix this you have three different options:
952
1421
  })();
953
1422
  return this.disconnectPromise;
954
1423
  }
1424
+ /**
1425
+ * Retrieves all tools from all configured servers with namespaced names.
1426
+ *
1427
+ * Tool names are namespaced as `serverName_toolName` to prevent conflicts between servers.
1428
+ * This method is intended to be passed directly to an Agent definition.
1429
+ *
1430
+ * @returns Object mapping namespaced tool names to tool implementations
1431
+ * @throws {MastraError} If retrieving tools fails
1432
+ *
1433
+ * @example
1434
+ * ```typescript
1435
+ * const agent = new Agent({
1436
+ * name: 'Multi-tool Agent',
1437
+ * instructions: 'You have access to weather and stock tools.',
1438
+ * model: openai('gpt-4'),
1439
+ * tools: await mcp.getTools(), // weather_getWeather, stockPrice_getPrice
1440
+ * });
1441
+ * ```
1442
+ */
955
1443
  async getTools() {
956
1444
  this.addToInstanceCache();
957
1445
  const connectedTools = {};
@@ -973,6 +1461,28 @@ To fix this you have three different options:
973
1461
  }
974
1462
  return connectedTools;
975
1463
  }
1464
+ /**
1465
+ * Returns toolsets organized by server name for dynamic tool injection.
1466
+ *
1467
+ * Unlike getTools(), this returns tools grouped by server without namespacing.
1468
+ * This is intended to be passed dynamically to the generate() or stream() method.
1469
+ *
1470
+ * @returns Object mapping server names to their tool collections
1471
+ * @throws {MastraError} If retrieving toolsets fails
1472
+ *
1473
+ * @example
1474
+ * ```typescript
1475
+ * const agent = new Agent({
1476
+ * name: 'Dynamic Agent',
1477
+ * instructions: 'You can use tools dynamically.',
1478
+ * model: openai('gpt-4'),
1479
+ * });
1480
+ *
1481
+ * const response = await agent.stream(prompt, {
1482
+ * toolsets: await mcp.getToolsets(), // { weather: {...}, stockPrice: {...} }
1483
+ * });
1484
+ * ```
1485
+ */
976
1486
  async getToolsets() {
977
1487
  this.addToInstanceCache();
978
1488
  const connectedToolsets = {};
@@ -1001,8 +1511,19 @@ To fix this you have three different options:
1001
1511
  return this.resources.list();
1002
1512
  }
1003
1513
  /**
1004
- * Get the current session IDs for all connected MCP clients using the Streamable HTTP transport.
1005
- * Returns an object mapping server names to their session IDs.
1514
+ * Gets current session IDs for all connected MCP clients using Streamable HTTP transport.
1515
+ *
1516
+ * Returns an object mapping server names to their session IDs. Only includes servers
1517
+ * that are currently connected via Streamable HTTP transport.
1518
+ *
1519
+ * @returns Object mapping server names to session IDs
1520
+ *
1521
+ * @example
1522
+ * ```typescript
1523
+ * const sessions = mcp.sessionIds;
1524
+ * console.log(sessions);
1525
+ * // { weatherServer: 'abc-123', stockServer: 'def-456' }
1526
+ * ```
1006
1527
  */
1007
1528
  get sessionIds() {
1008
1529
  const sessionIds = {};
@@ -1076,6 +1597,9 @@ To fix this you have three different options:
1076
1597
  }
1077
1598
  };
1078
1599
  var MCPConfiguration = class extends MCPClient {
1600
+ /**
1601
+ * @deprecated Use MCPClient constructor instead
1602
+ */
1079
1603
  constructor(args) {
1080
1604
  super(args);
1081
1605
  this.logger.warn(
@@ -1334,14 +1858,27 @@ var ServerPromptActions = class {
1334
1858
  getLogger;
1335
1859
  getSdkServer;
1336
1860
  clearDefinedPrompts;
1861
+ /**
1862
+ * @internal
1863
+ */
1337
1864
  constructor(dependencies) {
1338
1865
  this.getLogger = dependencies.getLogger;
1339
1866
  this.getSdkServer = dependencies.getSdkServer;
1340
1867
  this.clearDefinedPrompts = dependencies.clearDefinedPrompts;
1341
1868
  }
1342
1869
  /**
1343
- * Notifies the server that the overall list of available prompts has changed.
1344
- * This will clear the internal cache of defined prompts and send a list_changed notification to clients.
1870
+ * Notifies clients that the overall list of available prompts has changed.
1871
+ *
1872
+ * This clears the internal prompt cache and sends a `notifications/prompts/list_changed`
1873
+ * message to all clients, prompting them to re-fetch the prompt list.
1874
+ *
1875
+ * @throws {MastraError} If sending the notification fails
1876
+ *
1877
+ * @example
1878
+ * ```typescript
1879
+ * // After adding or modifying prompts
1880
+ * await server.prompts.notifyListChanged();
1881
+ * ```
1345
1882
  */
1346
1883
  async notifyListChanged() {
1347
1884
  this.getLogger().info("Prompt list change externally notified. Clearing definedPrompts and sending notification.");
@@ -1372,6 +1909,9 @@ var ServerResourceActions = class {
1372
1909
  getSdkServer;
1373
1910
  clearDefinedResources;
1374
1911
  clearDefinedResourceTemplates;
1912
+ /**
1913
+ * @internal
1914
+ */
1375
1915
  constructor(dependencies) {
1376
1916
  this.getSubscriptions = dependencies.getSubscriptions;
1377
1917
  this.getLogger = dependencies.getLogger;
@@ -1380,8 +1920,20 @@ var ServerResourceActions = class {
1380
1920
  this.clearDefinedResourceTemplates = dependencies.clearDefinedResourceTemplates;
1381
1921
  }
1382
1922
  /**
1383
- * Checks if any resources have been updated.
1384
- * If the resource is subscribed to by clients, an update notification will be sent.
1923
+ * Notifies subscribed clients that a specific resource has been updated.
1924
+ *
1925
+ * If clients are subscribed to the resource URI, they will receive a
1926
+ * `notifications/resources/updated` message to re-fetch the resource content.
1927
+ *
1928
+ * @param params - Notification parameters
1929
+ * @param params.uri - URI of the resource that was updated
1930
+ * @throws {MastraError} If sending the notification fails
1931
+ *
1932
+ * @example
1933
+ * ```typescript
1934
+ * // After updating a file resource
1935
+ * await server.resources.notifyUpdated({ uri: 'file://data.txt' });
1936
+ * ```
1385
1937
  */
1386
1938
  async notifyUpdated({ uri }) {
1387
1939
  if (this.getSubscriptions().has(uri)) {
@@ -1412,8 +1964,18 @@ var ServerResourceActions = class {
1412
1964
  }
1413
1965
  }
1414
1966
  /**
1415
- * Notifies the server that the overall list of available resources has changed.
1416
- * This will clear the internal cache of defined resources and send a list_changed notification to clients.
1967
+ * Notifies clients that the overall list of available resources has changed.
1968
+ *
1969
+ * This clears the internal resource cache and sends a `notifications/resources/list_changed`
1970
+ * message to all clients, prompting them to re-fetch the resource list.
1971
+ *
1972
+ * @throws {MastraError} If sending the notification fails
1973
+ *
1974
+ * @example
1975
+ * ```typescript
1976
+ * // After adding a new resource to your resource handler
1977
+ * await server.resources.notifyListChanged();
1978
+ * ```
1417
1979
  */
1418
1980
  async notifyListChanged() {
1419
1981
  this.getLogger().info(
@@ -1458,36 +2020,134 @@ var MCPServer = class extends mcp.MCPServerBase {
1458
2020
  promptOptions;
1459
2021
  subscriptions = /* @__PURE__ */ new Set();
1460
2022
  currentLoggingLevel;
2023
+ /**
2024
+ * Provides methods to notify clients about resource changes.
2025
+ *
2026
+ * @example
2027
+ * ```typescript
2028
+ * // Notify that a specific resource was updated
2029
+ * await server.resources.notifyUpdated({ uri: 'file://data.txt' });
2030
+ *
2031
+ * // Notify that the resource list changed
2032
+ * await server.resources.notifyListChanged();
2033
+ * ```
2034
+ */
1461
2035
  resources;
2036
+ /**
2037
+ * Provides methods to notify clients about prompt changes.
2038
+ *
2039
+ * @example
2040
+ * ```typescript
2041
+ * // Notify that the prompt list changed
2042
+ * await server.prompts.notifyListChanged();
2043
+ * ```
2044
+ */
1462
2045
  prompts;
2046
+ /**
2047
+ * Provides methods for interactive user input collection during tool execution.
2048
+ *
2049
+ * @example
2050
+ * ```typescript
2051
+ * // Within a tool's execute function
2052
+ * const result = await options.elicitation.sendRequest({
2053
+ * message: 'Please provide your email address',
2054
+ * requestedSchema: {
2055
+ * type: 'object',
2056
+ * properties: {
2057
+ * email: { type: 'string', format: 'email' }
2058
+ * },
2059
+ * required: ['email']
2060
+ * }
2061
+ * });
2062
+ * ```
2063
+ */
1463
2064
  elicitation;
1464
2065
  /**
1465
- * Get the current stdio transport.
2066
+ * Gets the stdio transport instance if the server was started using stdio.
2067
+ *
2068
+ * This is primarily for internal checks or testing purposes.
2069
+ *
2070
+ * @returns The stdio transport instance, or undefined if not using stdio transport
1466
2071
  */
1467
2072
  getStdioTransport() {
1468
2073
  return this.stdioTransport;
1469
2074
  }
1470
2075
  /**
1471
- * Get the current SSE transport.
2076
+ * Gets the SSE transport instance if the server was started using SSE.
2077
+ *
2078
+ * This is primarily for internal checks or testing purposes.
2079
+ *
2080
+ * @returns The SSE transport instance, or undefined if not using SSE transport
1472
2081
  */
1473
2082
  getSseTransport() {
1474
2083
  return this.sseTransport;
1475
2084
  }
1476
2085
  /**
1477
- * Get the current SSE Hono transport.
2086
+ * Gets the Hono SSE transport instance for a specific session.
2087
+ *
2088
+ * This is primarily for internal checks or testing purposes.
2089
+ *
2090
+ * @param sessionId - The session identifier
2091
+ * @returns The Hono SSE transport instance, or undefined if session not found
1478
2092
  */
1479
2093
  getSseHonoTransport(sessionId) {
1480
2094
  return this.sseHonoTransports.get(sessionId);
1481
2095
  }
1482
2096
  /**
1483
- * Get the current server instance.
2097
+ * Gets the underlying MCP SDK Server instance.
2098
+ *
2099
+ * This provides access to the low-level server instance for advanced use cases.
2100
+ *
2101
+ * @returns The Server instance from @modelcontextprotocol/sdk
1484
2102
  */
1485
2103
  getServer() {
1486
2104
  return this.server;
1487
2105
  }
1488
2106
  /**
1489
- * Construct a new MCPServer instance.
1490
- * @param opts - Configuration options for the server, including registry metadata.
2107
+ * Creates a new MCPServer instance.
2108
+ *
2109
+ * The server exposes tools, agents, and workflows to MCP clients. Agents are automatically
2110
+ * converted to tools named `ask_<agentKey>`, and workflows become tools named `run_<workflowKey>`.
2111
+ *
2112
+ * @param opts - Configuration options for the server
2113
+ * @param opts.name - Descriptive name for the server (e.g., 'My Weather Server')
2114
+ * @param opts.version - Semantic version of the server (e.g., '1.0.0')
2115
+ * @param opts.tools - Object mapping tool names to tool definitions
2116
+ * @param opts.agents - Optional object mapping agent identifiers to Agent instances
2117
+ * @param opts.workflows - Optional object mapping workflow identifiers to Workflow instances
2118
+ * @param opts.resources - Optional resource configuration for exposing data and content
2119
+ * @param opts.prompts - Optional prompt configuration for exposing reusable templates
2120
+ * @param opts.id - Optional unique identifier (generated if not provided)
2121
+ * @param opts.description - Optional description of what the server does
2122
+ *
2123
+ * @example
2124
+ * ```typescript
2125
+ * import { MCPServer } from '@mastra/mcp';
2126
+ * import { Agent } from '@mastra/core/agent';
2127
+ * import { createTool } from '@mastra/core/tools';
2128
+ * import { z } from 'zod';
2129
+ *
2130
+ * const myAgent = new Agent({
2131
+ * name: 'Helper',
2132
+ * description: 'A helpful assistant',
2133
+ * instructions: 'You are helpful.',
2134
+ * model: openai('gpt-4o-mini'),
2135
+ * });
2136
+ *
2137
+ * const server = new MCPServer({
2138
+ * name: 'My Server',
2139
+ * version: '1.0.0',
2140
+ * tools: {
2141
+ * weatherTool: createTool({
2142
+ * id: 'getWeather',
2143
+ * description: 'Gets weather',
2144
+ * inputSchema: z.object({ location: z.string() }),
2145
+ * execute: async ({ context }) => `Sunny in ${context.location}`,
2146
+ * })
2147
+ * },
2148
+ * agents: { myAgent },
2149
+ * });
2150
+ * ```
1491
2151
  */
1492
2152
  constructor(opts) {
1493
2153
  super(opts);
@@ -2091,7 +2751,23 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2091
2751
  return allConvertedTools;
2092
2752
  }
2093
2753
  /**
2094
- * Start the MCP server using stdio transport (for Windsurf integration).
2754
+ * Starts the MCP server using standard input/output (stdio) transport.
2755
+ *
2756
+ * This is typically used when running the server as a command-line program that MCP clients
2757
+ * spawn as a subprocess (e.g., integration with Windsurf, Cursor, or Claude Desktop).
2758
+ *
2759
+ * @throws {MastraError} If the stdio connection fails
2760
+ *
2761
+ * @example
2762
+ * ```typescript
2763
+ * const server = new MCPServer({
2764
+ * name: 'My Server',
2765
+ * version: '1.0.0',
2766
+ * tools: { weatherTool },
2767
+ * });
2768
+ *
2769
+ * await server.startStdio();
2770
+ * ```
2095
2771
  */
2096
2772
  async startStdio() {
2097
2773
  this.stdioTransport = new stdio_js.StdioServerTransport();
@@ -2115,14 +2791,38 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2115
2791
  this.logger.info("Started MCP Server (stdio)");
2116
2792
  }
2117
2793
  /**
2118
- * Handles MCP-over-SSE protocol for user-provided HTTP servers.
2119
- * Call this from your HTTP server for both the SSE and message endpoints.
2794
+ * Integrates the MCP server with an existing HTTP server using Server-Sent Events (SSE).
2120
2795
  *
2121
- * @param url Parsed URL of the incoming request
2122
- * @param ssePath Path for establishing the SSE connection (e.g. '/sse')
2123
- * @param messagePath Path for POSTing client messages (e.g. '/message')
2124
- * @param req Incoming HTTP request
2125
- * @param res HTTP response (must support .write/.end)
2796
+ * Call this method from your web server's request handler for both the SSE and message paths.
2797
+ * This enables web-based MCP clients to connect to your server.
2798
+ *
2799
+ * @param options - Configuration for SSE integration
2800
+ * @param options.url - Parsed URL of the incoming request
2801
+ * @param options.ssePath - Path for establishing SSE connection (e.g., '/sse')
2802
+ * @param options.messagePath - Path for POSTing client messages (e.g., '/message')
2803
+ * @param options.req - Incoming HTTP request object
2804
+ * @param options.res - HTTP response object (must support .write/.end)
2805
+ *
2806
+ * @throws {MastraError} If SSE connection setup fails
2807
+ *
2808
+ * @example
2809
+ * ```typescript
2810
+ * import http from 'http';
2811
+ *
2812
+ * const httpServer = http.createServer(async (req, res) => {
2813
+ * await server.startSSE({
2814
+ * url: new URL(req.url || '', `http://localhost:1234`),
2815
+ * ssePath: '/sse',
2816
+ * messagePath: '/message',
2817
+ * req,
2818
+ * res,
2819
+ * });
2820
+ * });
2821
+ *
2822
+ * httpServer.listen(1234, () => {
2823
+ * console.log('MCP server listening on http://localhost:1234/sse');
2824
+ * });
2825
+ * ```
2126
2826
  */
2127
2827
  async startSSE({ url, ssePath, messagePath, req, res }) {
2128
2828
  try {
@@ -2164,13 +2864,37 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2164
2864
  }
2165
2865
  }
2166
2866
  /**
2167
- * Handles MCP-over-SSE protocol for user-provided HTTP servers.
2168
- * Call this from your HTTP server for both the SSE and message endpoints.
2867
+ * Integrates the MCP server with a Hono web framework using Server-Sent Events (SSE).
2868
+ *
2869
+ * Call this method from your Hono server's request handler for both the SSE and message paths.
2870
+ * This enables Hono-based web applications to expose MCP servers.
2871
+ *
2872
+ * @param options - Configuration for Hono SSE integration
2873
+ * @param options.url - Parsed URL of the incoming request
2874
+ * @param options.ssePath - Path for establishing SSE connection (e.g., '/hono-sse')
2875
+ * @param options.messagePath - Path for POSTing client messages (e.g., '/message')
2876
+ * @param options.context - Hono context object
2877
+ *
2878
+ * @throws {MastraError} If Hono SSE connection setup fails
2879
+ *
2880
+ * @example
2881
+ * ```typescript
2882
+ * import { Hono } from 'hono';
2883
+ *
2884
+ * const app = new Hono();
2885
+ *
2886
+ * app.all('*', async (c) => {
2887
+ * const url = new URL(c.req.url);
2888
+ * return await server.startHonoSSE({
2889
+ * url,
2890
+ * ssePath: '/hono-sse',
2891
+ * messagePath: '/message',
2892
+ * context: c,
2893
+ * });
2894
+ * });
2169
2895
  *
2170
- * @param url Parsed URL of the incoming request
2171
- * @param ssePath Path for establishing the SSE connection (e.g. '/sse')
2172
- * @param messagePath Path for POSTing client messages (e.g. '/message')
2173
- * @param context Incoming Hono context
2896
+ * export default app;
2897
+ * ```
2174
2898
  */
2175
2899
  async startHonoSSE({ url, ssePath, messagePath, context }) {
2176
2900
  try {
@@ -2220,14 +2944,46 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2220
2944
  }
2221
2945
  }
2222
2946
  /**
2223
- * Handles MCP-over-StreamableHTTP protocol for user-provided HTTP servers.
2224
- * Call this from your HTTP server for the streamable HTTP endpoint.
2947
+ * Integrates the MCP server with an existing HTTP server using streamable HTTP transport.
2225
2948
  *
2226
- * @param url Parsed URL of the incoming request
2227
- * @param httpPath Path for establishing the streamable HTTP connection (e.g. '/mcp')
2228
- * @param req Incoming HTTP request
2229
- * @param res HTTP response (must support .write/.end)
2230
- * @param options Optional options to pass to the transport (e.g. sessionIdGenerator)
2949
+ * This is the recommended modern transport method, providing better session management and
2950
+ * reliability compared to SSE. Call this from your HTTP server's request handler.
2951
+ *
2952
+ * @param options - Configuration for HTTP integration
2953
+ * @param options.url - Parsed URL of the incoming request
2954
+ * @param options.httpPath - Path for the MCP endpoint (e.g., '/mcp')
2955
+ * @param options.req - Incoming HTTP request (http.IncomingMessage)
2956
+ * @param options.res - HTTP response object (http.ServerResponse)
2957
+ * @param options.options - Optional transport options
2958
+ * @param options.options.sessionIdGenerator - Function to generate unique session IDs (defaults to randomUUID)
2959
+ * @param options.options.onsessioninitialized - Callback when a new session is initialized
2960
+ * @param options.options.enableJsonResponse - If true, return JSON instead of SSE streaming
2961
+ * @param options.options.eventStore - Event store for message resumability
2962
+ *
2963
+ * @throws {MastraError} If HTTP connection setup fails
2964
+ *
2965
+ * @example
2966
+ * ```typescript
2967
+ * import http from 'http';
2968
+ * import { randomUUID } from 'crypto';
2969
+ *
2970
+ * const httpServer = http.createServer(async (req, res) => {
2971
+ * await server.startHTTP({
2972
+ * url: new URL(req.url || '', 'http://localhost:1234'),
2973
+ * httpPath: '/mcp',
2974
+ * req,
2975
+ * res,
2976
+ * options: {
2977
+ * sessionIdGenerator: () => randomUUID(),
2978
+ * onsessioninitialized: (sessionId) => {
2979
+ * console.log(`New MCP session: ${sessionId}`);
2980
+ * },
2981
+ * },
2982
+ * });
2983
+ * });
2984
+ *
2985
+ * httpServer.listen(1234);
2986
+ * ```
2231
2987
  */
2232
2988
  async startHTTP({
2233
2989
  url,
@@ -2378,6 +3134,27 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2378
3134
  }
2379
3135
  }
2380
3136
  }
3137
+ /**
3138
+ * Establishes the SSE connection for the MCP server.
3139
+ *
3140
+ * This is a lower-level method called internally by `startSSE()`. In most cases,
3141
+ * you should use `startSSE()` instead which handles both connection establishment
3142
+ * and message routing.
3143
+ *
3144
+ * @param params - Connection parameters
3145
+ * @param params.messagePath - Path for POST requests from the client
3146
+ * @param params.res - HTTP response object for the SSE stream
3147
+ * @throws {MastraError} If SSE connection establishment fails
3148
+ *
3149
+ * @example
3150
+ * ```typescript
3151
+ * // Usually called internally by startSSE()
3152
+ * await server.connectSSE({
3153
+ * messagePath: '/message',
3154
+ * res: response
3155
+ * });
3156
+ * ```
3157
+ */
2381
3158
  async connectSSE({
2382
3159
  messagePath,
2383
3160
  res
@@ -2410,6 +3187,27 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2410
3187
  throw mastraError;
2411
3188
  }
2412
3189
  }
3190
+ /**
3191
+ * Establishes the Hono SSE connection for the MCP server.
3192
+ *
3193
+ * This is a lower-level method called internally by `startHonoSSE()`. In most cases,
3194
+ * you should use `startHonoSSE()` instead which handles both connection establishment
3195
+ * and message routing.
3196
+ *
3197
+ * @param params - Connection parameters
3198
+ * @param params.messagePath - Path for POST requests from the client
3199
+ * @param params.stream - Hono SSE streaming API object
3200
+ * @throws {MastraError} If Hono SSE connection establishment fails
3201
+ *
3202
+ * @example
3203
+ * ```typescript
3204
+ * // Usually called internally by startHonoSSE()
3205
+ * await server.connectHonoSSE({
3206
+ * messagePath: '/message',
3207
+ * stream: sseStream
3208
+ * });
3209
+ * ```
3210
+ */
2413
3211
  async connectHonoSSE({ messagePath, stream: stream2 }) {
2414
3212
  this.logger.debug("Received SSE connection");
2415
3213
  const sseTransport = new SSETransport(messagePath, stream2);
@@ -2451,7 +3249,21 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2451
3249
  }
2452
3250
  }
2453
3251
  /**
2454
- * Close the MCP server and all its connections
3252
+ * Closes the MCP server and releases all resources.
3253
+ *
3254
+ * This method cleanly shuts down all active transports (stdio, SSE, HTTP) and their
3255
+ * associated connections. Call this when your application is shutting down.
3256
+ *
3257
+ * @throws {MastraError} If closing the server fails
3258
+ *
3259
+ * @example
3260
+ * ```typescript
3261
+ * // Graceful shutdown
3262
+ * process.on('SIGTERM', async () => {
3263
+ * await server.close();
3264
+ * process.exit(0);
3265
+ * });
3266
+ * ```
2455
3267
  */
2456
3268
  async close() {
2457
3269
  try {
@@ -2498,8 +3310,19 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2498
3310
  }
2499
3311
  }
2500
3312
  /**
2501
- * Gets the basic information about the server, conforming to the Server schema.
2502
- * @returns ServerInfo object.
3313
+ * Gets basic information about the server.
3314
+ *
3315
+ * Returns metadata including server ID, name, description, repository, and version details.
3316
+ * This information conforms to the MCP Server schema.
3317
+ *
3318
+ * @returns Server information object
3319
+ *
3320
+ * @example
3321
+ * ```typescript
3322
+ * const info = server.getServerInfo();
3323
+ * console.log(`${info.name} v${info.version_detail.version}`);
3324
+ * // Output: My Weather Server v1.0.0
3325
+ * ```
2503
3326
  */
2504
3327
  getServerInfo() {
2505
3328
  return {
@@ -2515,8 +3338,19 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2515
3338
  };
2516
3339
  }
2517
3340
  /**
2518
- * Gets detailed information about the server, conforming to the ServerDetail schema.
2519
- * @returns ServerDetailInfo object.
3341
+ * Gets detailed information about the server including packaging and deployment metadata.
3342
+ *
3343
+ * Returns extended server information with package details, remotes, and deployment configurations.
3344
+ * This information conforms to the MCP ServerDetail schema.
3345
+ *
3346
+ * @returns Detailed server information object
3347
+ *
3348
+ * @example
3349
+ * ```typescript
3350
+ * const detail = server.getServerDetail();
3351
+ * console.log(detail.package_canonical); // 'npm'
3352
+ * console.log(detail.packages); // Package installation info
3353
+ * ```
2520
3354
  */
2521
3355
  getServerDetail() {
2522
3356
  return {
@@ -2527,9 +3361,21 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2527
3361
  };
2528
3362
  }
2529
3363
  /**
2530
- * Gets a list of tools provided by this MCP server, including their schemas.
2531
- * This leverages the same tool information used by the internal ListTools MCP request.
2532
- * @returns An object containing an array of tool information.
3364
+ * Gets a list of all tools provided by this MCP server with their schemas.
3365
+ *
3366
+ * Returns information about all registered tools including explicit tools, agent-derived tools,
3367
+ * and workflow-derived tools. Includes input/output schemas and tool types.
3368
+ *
3369
+ * @returns Object containing array of tool information
3370
+ *
3371
+ * @example
3372
+ * ```typescript
3373
+ * const toolList = server.getToolListInfo();
3374
+ * toolList.tools.forEach(tool => {
3375
+ * console.log(`${tool.name}: ${tool.description}`);
3376
+ * console.log(`Type: ${tool.toolType || 'tool'}`);
3377
+ * });
3378
+ * ```
2533
3379
  */
2534
3380
  getToolListInfo() {
2535
3381
  this.logger.debug(`Getting tool list information for MCPServer '${this.name}'`);
@@ -2546,8 +3392,21 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2546
3392
  }
2547
3393
  /**
2548
3394
  * Gets information for a specific tool provided by this MCP server.
2549
- * @param toolId The ID/name of the tool to retrieve.
2550
- * @returns Tool information (name, description, inputSchema) or undefined if not found.
3395
+ *
3396
+ * Returns detailed information about a single tool including its name, description, schemas, and type.
3397
+ * Returns undefined if the tool is not found.
3398
+ *
3399
+ * @param toolId - The ID/name of the tool to retrieve
3400
+ * @returns Tool information object or undefined if not found
3401
+ *
3402
+ * @example
3403
+ * ```typescript
3404
+ * const toolInfo = server.getToolInfo('getWeather');
3405
+ * if (toolInfo) {
3406
+ * console.log(toolInfo.description);
3407
+ * console.log(toolInfo.inputSchema);
3408
+ * }
3409
+ * ```
2551
3410
  */
2552
3411
  getToolInfo(toolId) {
2553
3412
  const tool = this.convertedTools[toolId];
@@ -2566,11 +3425,25 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2566
3425
  }
2567
3426
  /**
2568
3427
  * Executes a specific tool provided by this MCP server.
2569
- * @param toolId The ID/name of the tool to execute.
2570
- * @param args The arguments to pass to the tool's execute function.
2571
- * @param executionContext Optional context for the tool execution.
2572
- * @returns A promise that resolves to the result of the tool execution.
2573
- * @throws Error if the tool is not found, validation fails, or execution fails.
3428
+ *
3429
+ * This method validates the tool arguments against the input schema and executes the tool.
3430
+ * If validation fails, returns an error object instead of throwing.
3431
+ *
3432
+ * @param toolId - The ID/name of the tool to execute
3433
+ * @param args - The arguments to pass to the tool's execute function
3434
+ * @param executionContext - Optional context including messages and toolCallId
3435
+ * @returns Promise resolving to the tool execution result
3436
+ * @throws {MastraError} If the tool is not found or execution fails
3437
+ *
3438
+ * @example
3439
+ * ```typescript
3440
+ * const result = await server.executeTool(
3441
+ * 'getWeather',
3442
+ * { location: 'London' },
3443
+ * { toolCallId: 'call_123' }
3444
+ * );
3445
+ * console.log(result);
3446
+ * ```
2574
3447
  */
2575
3448
  async executeTool(toolId, args, executionContext) {
2576
3449
  const tool = this.convertedTools[toolId];