@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.js CHANGED
@@ -29,13 +29,50 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/
29
29
  var ElicitationClientActions = class {
30
30
  client;
31
31
  logger;
32
+ /**
33
+ * @internal
34
+ */
32
35
  constructor({ client, logger }) {
33
36
  this.client = client;
34
37
  this.logger = logger;
35
38
  }
36
39
  /**
37
- * Set a handler for elicitation requests.
38
- * @param handler The callback function to handle the elicitation request.
40
+ * Sets a handler function for processing elicitation requests from the server.
41
+ *
42
+ * The handler is called when the server needs to collect user input during tool execution.
43
+ * The handler must return a response with action ('accept', 'decline', or 'cancel') and
44
+ * optional content matching the requested schema.
45
+ *
46
+ * @param handler - Callback function to handle elicitation requests
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * client.elicitation.onRequest(async (request) => {
51
+ * console.log('Server message:', request.message);
52
+ * console.log('Requested schema:', request.requestedSchema);
53
+ *
54
+ * // Collect user input (e.g., via CLI prompt or UI form)
55
+ * const userInput = await collectUserInput(request.requestedSchema);
56
+ *
57
+ * return {
58
+ * action: 'accept',
59
+ * content: userInput
60
+ * };
61
+ * });
62
+ * ```
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * // Declining an elicitation request
67
+ * client.elicitation.onRequest(async (request) => {
68
+ * if (!shouldAcceptRequest(request)) {
69
+ * return { action: 'decline' };
70
+ * }
71
+ *
72
+ * const input = await getInput();
73
+ * return { action: 'accept', content: input };
74
+ * });
75
+ * ```
39
76
  */
40
77
  onRequest(handler) {
41
78
  this.client.setElicitationRequestHandler(handler);
@@ -44,13 +81,28 @@ var ElicitationClientActions = class {
44
81
  var PromptClientActions = class {
45
82
  client;
46
83
  logger;
84
+ /**
85
+ * @internal
86
+ */
47
87
  constructor({ client, logger }) {
48
88
  this.client = client;
49
89
  this.logger = logger;
50
90
  }
51
91
  /**
52
- * Get all prompts from the connected MCP server.
53
- * @returns A list of prompts with their versions.
92
+ * Retrieves all available prompts from the connected MCP server.
93
+ *
94
+ * Returns an empty array if the server doesn't support prompts (MethodNotFound error).
95
+ *
96
+ * @returns Promise resolving to array of prompts with their metadata
97
+ * @throws {Error} If fetching prompts fails (excluding MethodNotFound)
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * const prompts = await client.prompts.list();
102
+ * prompts.forEach(prompt => {
103
+ * console.log(`${prompt.name} (v${prompt.version}): ${prompt.description}`);
104
+ * });
105
+ * ```
54
106
  */
55
107
  async list() {
56
108
  try {
@@ -76,11 +128,32 @@ var PromptClientActions = class {
76
128
  }
77
129
  }
78
130
  /**
79
- * Get a specific prompt.
80
- * @param name The name of the prompt to get.
81
- * @param args Optional arguments for the prompt.
82
- * @param version Optional version of the prompt to get.
83
- * @returns The prompt content.
131
+ * Retrieves a specific prompt with its messages from the MCP server.
132
+ *
133
+ * Prompts can accept arguments to parameterize the template. The returned messages
134
+ * can be used directly in AI chat completions.
135
+ *
136
+ * @param params - Parameters for the prompt request
137
+ * @param params.name - Name of the prompt to retrieve
138
+ * @param params.args - Optional arguments to populate the prompt template
139
+ * @param params.version - Optional specific version of the prompt to retrieve
140
+ * @returns Promise resolving to the prompt result with messages
141
+ * @throws {Error} If fetching the prompt fails or prompt not found
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * const prompt = await client.prompts.get({
146
+ * name: 'code-review',
147
+ * args: {
148
+ * language: 'typescript',
149
+ * code: 'const x = 1;'
150
+ * },
151
+ * version: '1.0'
152
+ * });
153
+ *
154
+ * // Use prompt messages in AI completion
155
+ * console.log(prompt.messages);
156
+ * ```
84
157
  */
85
158
  async get({
86
159
  name,
@@ -90,8 +163,20 @@ var PromptClientActions = class {
90
163
  return this.client.getPrompt({ name, args, version });
91
164
  }
92
165
  /**
93
- * Set a notification handler for when the list of available prompts changes.
94
- * @param handler The callback function to handle the notification.
166
+ * Sets a notification handler for when the list of available prompts changes.
167
+ *
168
+ * The handler is called when prompts are added, removed, or modified on the server.
169
+ *
170
+ * @param handler - Callback function invoked when the prompt list changes
171
+ *
172
+ * @example
173
+ * ```typescript
174
+ * await client.prompts.onListChanged(async () => {
175
+ * console.log('Prompt list changed, re-fetching...');
176
+ * const prompts = await client.prompts.list();
177
+ * console.log('Available prompts:', prompts.map(p => p.name));
178
+ * });
179
+ * ```
95
180
  */
96
181
  async onListChanged(handler) {
97
182
  this.client.setPromptListChangedNotificationHandler(handler);
@@ -100,13 +185,28 @@ var PromptClientActions = class {
100
185
  var ResourceClientActions = class {
101
186
  client;
102
187
  logger;
188
+ /**
189
+ * @internal
190
+ */
103
191
  constructor({ client, logger }) {
104
192
  this.client = client;
105
193
  this.logger = logger;
106
194
  }
107
195
  /**
108
- * Get all resources from the connected MCP server.
109
- * @returns A list of resources.
196
+ * Retrieves all available resources from the connected MCP server.
197
+ *
198
+ * Returns an empty array if the server doesn't support resources (MethodNotFound error).
199
+ *
200
+ * @returns Promise resolving to array of resources
201
+ * @throws {Error} If fetching resources fails (excluding MethodNotFound)
202
+ *
203
+ * @example
204
+ * ```typescript
205
+ * const resources = await client.resources.list();
206
+ * resources.forEach(resource => {
207
+ * console.log(`${resource.name}: ${resource.uri}`);
208
+ * });
209
+ * ```
110
210
  */
111
211
  async list() {
112
212
  try {
@@ -132,8 +232,21 @@ var ResourceClientActions = class {
132
232
  }
133
233
  }
134
234
  /**
135
- * Get all resource templates from the connected MCP server.
136
- * @returns A list of resource templates.
235
+ * Retrieves all available resource templates from the connected MCP server.
236
+ *
237
+ * Resource templates are URI templates (RFC 6570) that describe dynamic resources.
238
+ * Returns an empty array if the server doesn't support resource templates.
239
+ *
240
+ * @returns Promise resolving to array of resource templates
241
+ * @throws {Error} If fetching resource templates fails (excluding MethodNotFound)
242
+ *
243
+ * @example
244
+ * ```typescript
245
+ * const templates = await client.resources.templates();
246
+ * templates.forEach(template => {
247
+ * console.log(`${template.name}: ${template.uriTemplate}`);
248
+ * });
249
+ * ```
137
250
  */
138
251
  async templates() {
139
252
  try {
@@ -160,37 +273,92 @@ var ResourceClientActions = class {
160
273
  }
161
274
  }
162
275
  /**
163
- * Read a specific resource.
164
- * @param uri The URI of the resource to read.
165
- * @returns The resource content.
276
+ * Reads the content of a specific resource from the MCP server.
277
+ *
278
+ * @param uri - URI of the resource to read (e.g., 'file://path/to/file.txt')
279
+ * @returns Promise resolving to the resource content
280
+ * @throws {Error} If reading the resource fails or resource not found
281
+ *
282
+ * @example
283
+ * ```typescript
284
+ * const result = await client.resources.read('file://data/config.json');
285
+ * console.log(result.contents[0].text); // Resource text content
286
+ * ```
166
287
  */
167
288
  async read(uri) {
168
289
  return this.client.readResource(uri);
169
290
  }
170
291
  /**
171
- * Subscribe to a specific resource.
172
- * @param uri The URI of the resource to subscribe to.
292
+ * Subscribes to updates for a specific resource.
293
+ *
294
+ * After subscribing, you'll receive notifications via the `onUpdated` handler
295
+ * when the resource content changes.
296
+ *
297
+ * @param uri - URI of the resource to subscribe to
298
+ * @returns Promise resolving when subscription is established
299
+ * @throws {Error} If subscription fails
300
+ *
301
+ * @example
302
+ * ```typescript
303
+ * await client.resources.subscribe('file://data/config.json');
304
+ * ```
173
305
  */
174
306
  async subscribe(uri) {
175
307
  return this.client.subscribeResource(uri);
176
308
  }
177
309
  /**
178
- * Unsubscribe from a specific resource.
179
- * @param uri The URI of the resource to unsubscribe from.
310
+ * Unsubscribes from updates for a specific resource.
311
+ *
312
+ * Stops receiving notifications for this resource URI.
313
+ *
314
+ * @param uri - URI of the resource to unsubscribe from
315
+ * @returns Promise resolving when unsubscription is complete
316
+ * @throws {Error} If unsubscription fails
317
+ *
318
+ * @example
319
+ * ```typescript
320
+ * await client.resources.unsubscribe('file://data/config.json');
321
+ * ```
180
322
  */
181
323
  async unsubscribe(uri) {
182
324
  return this.client.unsubscribeResource(uri);
183
325
  }
184
326
  /**
185
- * Set a notification handler for when a specific resource is updated.
186
- * @param handler The callback function to handle the notification.
327
+ * Sets a notification handler for when subscribed resources are updated.
328
+ *
329
+ * The handler is called whenever the server sends a resource update notification
330
+ * for any resource you've subscribed to.
331
+ *
332
+ * @param handler - Callback function receiving the updated resource URI
333
+ *
334
+ * @example
335
+ * ```typescript
336
+ * await client.resources.onUpdated(async (params) => {
337
+ * console.log(`Resource updated: ${params.uri}`);
338
+ * // Re-fetch the resource
339
+ * const content = await client.resources.read(params.uri);
340
+ * console.log('New content:', content);
341
+ * });
342
+ * ```
187
343
  */
188
344
  async onUpdated(handler) {
189
345
  this.client.setResourceUpdatedNotificationHandler(handler);
190
346
  }
191
347
  /**
192
- * Set a notification handler for when the list of available resources changes.
193
- * @param handler The callback function to handle the notification.
348
+ * Sets a notification handler for when the list of available resources changes.
349
+ *
350
+ * The handler is called when resources are added or removed from the server.
351
+ *
352
+ * @param handler - Callback function invoked when the resource list changes
353
+ *
354
+ * @example
355
+ * ```typescript
356
+ * await client.resources.onListChanged(async () => {
357
+ * console.log('Resource list changed, re-fetching...');
358
+ * const resources = await client.resources.list();
359
+ * console.log('Updated resource count:', resources.length);
360
+ * });
361
+ * ```
194
362
  */
195
363
  async onListChanged(handler) {
196
364
  this.client.setResourceListChangedNotificationHandler(handler);
@@ -225,9 +393,15 @@ var InternalMastraMCPClient = class extends MastraBase {
225
393
  serverConfig;
226
394
  transport;
227
395
  currentOperationContext = null;
396
+ /** Provides access to resource operations (list, read, subscribe, etc.) */
228
397
  resources;
398
+ /** Provides access to prompt operations (list, get, notifications) */
229
399
  prompts;
400
+ /** Provides access to elicitation operations (request handling) */
230
401
  elicitation;
402
+ /**
403
+ * @internal
404
+ */
231
405
  constructor({
232
406
  name,
233
407
  version = "1.0.0",
@@ -350,6 +524,17 @@ var InternalMastraMCPClient = class extends MastraBase {
350
524
  }
351
525
  }
352
526
  isConnected = null;
527
+ /**
528
+ * Connects to the MCP server using the configured transport.
529
+ *
530
+ * Automatically detects transport type based on configuration (stdio vs HTTP).
531
+ * Safe to call multiple times - returns existing connection if already connected.
532
+ *
533
+ * @returns Promise resolving to true when connected
534
+ * @throws {MastraError} If connection fails
535
+ *
536
+ * @internal
537
+ */
353
538
  async connect() {
354
539
  if (await this.isConnected) {
355
540
  return true;
@@ -390,8 +575,13 @@ var InternalMastraMCPClient = class extends MastraBase {
390
575
  return this.isConnected;
391
576
  }
392
577
  /**
393
- * Get the current session ID if using the Streamable HTTP transport.
394
- * Returns undefined if not connected or not using Streamable HTTP.
578
+ * Gets the current session ID if using Streamable HTTP transport.
579
+ *
580
+ * Returns undefined if not connected or not using Streamable HTTP transport.
581
+ *
582
+ * @returns Session ID string or undefined
583
+ *
584
+ * @internal
395
585
  */
396
586
  get sessionId() {
397
587
  if (this.transport instanceof StreamableHTTPClientTransport) {
@@ -643,6 +833,34 @@ var MCPClient = class extends MastraBase {
643
833
  defaultTimeout;
644
834
  mcpClientsById = /* @__PURE__ */ new Map();
645
835
  disconnectPromise = null;
836
+ /**
837
+ * Creates a new MCPClient instance for managing MCP server connections.
838
+ *
839
+ * The client automatically manages connection lifecycle and prevents memory leaks by
840
+ * caching instances with identical configurations.
841
+ *
842
+ * @param args - Configuration options
843
+ * @param args.id - Optional unique identifier to allow multiple instances with same config
844
+ * @param args.servers - Map of server names to server configurations
845
+ * @param args.timeout - Optional global timeout in milliseconds (default: 60000)
846
+ *
847
+ * @throws {Error} If multiple instances with identical config are created without an ID
848
+ *
849
+ * @example
850
+ * ```typescript
851
+ * const mcp = new MCPClient({
852
+ * servers: {
853
+ * weatherServer: {
854
+ * url: new URL('http://localhost:8080/sse'),
855
+ * requestInit: {
856
+ * headers: { Authorization: 'Bearer token' }
857
+ * }
858
+ * }
859
+ * },
860
+ * timeout: 30000
861
+ * });
862
+ * ```
863
+ */
646
864
  constructor(args) {
647
865
  super({ name: "MCPClient" });
648
866
  this.defaultTimeout = args.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
@@ -680,9 +898,48 @@ To fix this you have three different options:
680
898
  this.addToInstanceCache();
681
899
  return this;
682
900
  }
901
+ /**
902
+ * Provides access to elicitation-related operations for interactive user input collection.
903
+ *
904
+ * Elicitation allows MCP servers to request structured information from users during tool execution.
905
+ *
906
+ * @example
907
+ * ```typescript
908
+ * // Set up handler for elicitation requests from a server
909
+ * await mcp.elicitation.onRequest('serverName', async (request) => {
910
+ * console.log(`Server requests: ${request.message}`);
911
+ * console.log('Schema:', request.requestedSchema);
912
+ *
913
+ * // Collect user input and return response
914
+ * return {
915
+ * action: 'accept',
916
+ * content: { name: 'John Doe', email: 'john@example.com' }
917
+ * };
918
+ * });
919
+ * ```
920
+ */
683
921
  get elicitation() {
684
922
  this.addToInstanceCache();
685
923
  return {
924
+ /**
925
+ * Sets up a handler function for elicitation requests from a specific server.
926
+ *
927
+ * The handler receives requests for user input and must return a response with
928
+ * action ('accept', 'decline', or 'cancel') and optional content.
929
+ *
930
+ * @param serverName - Name of the server to handle elicitation requests for
931
+ * @param handler - Function to handle elicitation requests
932
+ * @throws {MastraError} If setting up the handler fails
933
+ *
934
+ * @example
935
+ * ```typescript
936
+ * await mcp.elicitation.onRequest('weatherServer', async (request) => {
937
+ * // Prompt user for input
938
+ * const userInput = await promptUser(request.requestedSchema);
939
+ * return { action: 'accept', content: userInput };
940
+ * });
941
+ * ```
942
+ */
686
943
  onRequest: async (serverName, handler) => {
687
944
  try {
688
945
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -703,9 +960,46 @@ To fix this you have three different options:
703
960
  }
704
961
  };
705
962
  }
963
+ /**
964
+ * Provides access to resource-related operations across all configured servers.
965
+ *
966
+ * Resources represent data exposed by MCP servers (files, database records, API responses, etc.).
967
+ *
968
+ * @example
969
+ * ```typescript
970
+ * // List all resources from all servers
971
+ * const allResources = await mcp.resources.list();
972
+ * Object.entries(allResources).forEach(([serverName, resources]) => {
973
+ * console.log(`${serverName}: ${resources.length} resources`);
974
+ * });
975
+ *
976
+ * // Read a specific resource
977
+ * const content = await mcp.resources.read('weatherServer', 'file://data.json');
978
+ *
979
+ * // Subscribe to resource updates
980
+ * await mcp.resources.subscribe('weatherServer', 'file://data.json');
981
+ * await mcp.resources.onUpdated('weatherServer', async (params) => {
982
+ * console.log(`Resource updated: ${params.uri}`);
983
+ * });
984
+ * ```
985
+ */
706
986
  get resources() {
707
987
  this.addToInstanceCache();
708
988
  return {
989
+ /**
990
+ * Lists all available resources from all configured servers.
991
+ *
992
+ * Returns a map of server names to their resource arrays. Errors for individual
993
+ * servers are logged but don't throw - failed servers return empty arrays.
994
+ *
995
+ * @returns Promise resolving to object mapping server names to resource arrays
996
+ *
997
+ * @example
998
+ * ```typescript
999
+ * const resources = await mcp.resources.list();
1000
+ * console.log(resources.weatherServer); // Array of resources
1001
+ * ```
1002
+ */
709
1003
  list: async () => {
710
1004
  const allResources = {};
711
1005
  for (const serverName of Object.keys(this.serverConfigs)) {
@@ -730,6 +1024,20 @@ To fix this you have three different options:
730
1024
  }
731
1025
  return allResources;
732
1026
  },
1027
+ /**
1028
+ * Lists all available resource templates from all configured servers.
1029
+ *
1030
+ * Resource templates are URI templates (RFC 6570) describing dynamic resources.
1031
+ * Errors for individual servers are logged but don't throw.
1032
+ *
1033
+ * @returns Promise resolving to object mapping server names to template arrays
1034
+ *
1035
+ * @example
1036
+ * ```typescript
1037
+ * const templates = await mcp.resources.templates();
1038
+ * console.log(templates.weatherServer); // Array of resource templates
1039
+ * ```
1040
+ */
733
1041
  templates: async () => {
734
1042
  const allTemplates = {};
735
1043
  for (const serverName of Object.keys(this.serverConfigs)) {
@@ -754,6 +1062,20 @@ To fix this you have three different options:
754
1062
  }
755
1063
  return allTemplates;
756
1064
  },
1065
+ /**
1066
+ * Reads the content of a specific resource from a server.
1067
+ *
1068
+ * @param serverName - Name of the server to read from
1069
+ * @param uri - URI of the resource to read
1070
+ * @returns Promise resolving to the resource content
1071
+ * @throws {MastraError} If reading the resource fails
1072
+ *
1073
+ * @example
1074
+ * ```typescript
1075
+ * const content = await mcp.resources.read('weatherServer', 'file://config.json');
1076
+ * console.log(content.contents[0].text);
1077
+ * ```
1078
+ */
757
1079
  read: async (serverName, uri) => {
758
1080
  try {
759
1081
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -773,6 +1095,19 @@ To fix this you have three different options:
773
1095
  );
774
1096
  }
775
1097
  },
1098
+ /**
1099
+ * Subscribes to updates for a specific resource on a server.
1100
+ *
1101
+ * @param serverName - Name of the server
1102
+ * @param uri - URI of the resource to subscribe to
1103
+ * @returns Promise resolving when subscription is established
1104
+ * @throws {MastraError} If subscription fails
1105
+ *
1106
+ * @example
1107
+ * ```typescript
1108
+ * await mcp.resources.subscribe('weatherServer', 'file://config.json');
1109
+ * ```
1110
+ */
776
1111
  subscribe: async (serverName, uri) => {
777
1112
  try {
778
1113
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -792,6 +1127,19 @@ To fix this you have three different options:
792
1127
  );
793
1128
  }
794
1129
  },
1130
+ /**
1131
+ * Unsubscribes from updates for a specific resource on a server.
1132
+ *
1133
+ * @param serverName - Name of the server
1134
+ * @param uri - URI of the resource to unsubscribe from
1135
+ * @returns Promise resolving when unsubscription is complete
1136
+ * @throws {MastraError} If unsubscription fails
1137
+ *
1138
+ * @example
1139
+ * ```typescript
1140
+ * await mcp.resources.unsubscribe('weatherServer', 'file://config.json');
1141
+ * ```
1142
+ */
795
1143
  unsubscribe: async (serverName, uri) => {
796
1144
  try {
797
1145
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -811,6 +1159,22 @@ To fix this you have three different options:
811
1159
  );
812
1160
  }
813
1161
  },
1162
+ /**
1163
+ * Sets a notification handler for when subscribed resources are updated on a server.
1164
+ *
1165
+ * @param serverName - Name of the server to monitor
1166
+ * @param handler - Callback function receiving the updated resource URI
1167
+ * @returns Promise resolving when handler is registered
1168
+ * @throws {MastraError} If setting up the handler fails
1169
+ *
1170
+ * @example
1171
+ * ```typescript
1172
+ * await mcp.resources.onUpdated('weatherServer', async (params) => {
1173
+ * console.log(`Resource updated: ${params.uri}`);
1174
+ * const content = await mcp.resources.read('weatherServer', params.uri);
1175
+ * });
1176
+ * ```
1177
+ */
814
1178
  onUpdated: async (serverName, handler) => {
815
1179
  try {
816
1180
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -829,6 +1193,22 @@ To fix this you have three different options:
829
1193
  );
830
1194
  }
831
1195
  },
1196
+ /**
1197
+ * Sets a notification handler for when the resource list changes on a server.
1198
+ *
1199
+ * @param serverName - Name of the server to monitor
1200
+ * @param handler - Callback function invoked when resources are added/removed
1201
+ * @returns Promise resolving when handler is registered
1202
+ * @throws {MastraError} If setting up the handler fails
1203
+ *
1204
+ * @example
1205
+ * ```typescript
1206
+ * await mcp.resources.onListChanged('weatherServer', async () => {
1207
+ * console.log('Resource list changed, re-fetching...');
1208
+ * const resources = await mcp.resources.list();
1209
+ * });
1210
+ * ```
1211
+ */
832
1212
  onListChanged: async (serverName, handler) => {
833
1213
  try {
834
1214
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -849,9 +1229,45 @@ To fix this you have three different options:
849
1229
  }
850
1230
  };
851
1231
  }
1232
+ /**
1233
+ * Provides access to prompt-related operations across all configured servers.
1234
+ *
1235
+ * Prompts are reusable message templates exposed by MCP servers that can be parameterized
1236
+ * and used for AI interactions.
1237
+ *
1238
+ * @example
1239
+ * ```typescript
1240
+ * // List all prompts from all servers
1241
+ * const allPrompts = await mcp.prompts.list();
1242
+ * Object.entries(allPrompts).forEach(([serverName, prompts]) => {
1243
+ * console.log(`${serverName}: ${prompts.map(p => p.name).join(', ')}`);
1244
+ * });
1245
+ *
1246
+ * // Get a specific prompt with arguments
1247
+ * const prompt = await mcp.prompts.get({
1248
+ * serverName: 'weatherServer',
1249
+ * name: 'forecast-template',
1250
+ * args: { city: 'London', days: 7 }
1251
+ * });
1252
+ * ```
1253
+ */
852
1254
  get prompts() {
853
1255
  this.addToInstanceCache();
854
1256
  return {
1257
+ /**
1258
+ * Lists all available prompts from all configured servers.
1259
+ *
1260
+ * Returns a map of server names to their prompt arrays. Errors for individual
1261
+ * servers are logged but don't throw - failed servers return empty arrays.
1262
+ *
1263
+ * @returns Promise resolving to object mapping server names to prompt arrays
1264
+ *
1265
+ * @example
1266
+ * ```typescript
1267
+ * const prompts = await mcp.prompts.list();
1268
+ * console.log(prompts.weatherServer); // Array of prompts
1269
+ * ```
1270
+ */
855
1271
  list: async () => {
856
1272
  const allPrompts = {};
857
1273
  for (const serverName of Object.keys(this.serverConfigs)) {
@@ -876,6 +1292,28 @@ To fix this you have three different options:
876
1292
  }
877
1293
  return allPrompts;
878
1294
  },
1295
+ /**
1296
+ * Retrieves a specific prompt with its messages from a server.
1297
+ *
1298
+ * @param params - Parameters for the prompt request
1299
+ * @param params.serverName - Name of the server to retrieve from
1300
+ * @param params.name - Name of the prompt to retrieve
1301
+ * @param params.args - Optional arguments to populate the prompt template
1302
+ * @param params.version - Optional specific version of the prompt
1303
+ * @returns Promise resolving to the prompt result with messages
1304
+ * @throws {MastraError} If fetching the prompt fails
1305
+ *
1306
+ * @example
1307
+ * ```typescript
1308
+ * const prompt = await mcp.prompts.get({
1309
+ * serverName: 'weatherServer',
1310
+ * name: 'forecast',
1311
+ * args: { city: 'London' },
1312
+ * version: '1.0'
1313
+ * });
1314
+ * console.log(prompt.messages);
1315
+ * ```
1316
+ */
879
1317
  get: async ({
880
1318
  serverName,
881
1319
  name,
@@ -900,6 +1338,22 @@ To fix this you have three different options:
900
1338
  );
901
1339
  }
902
1340
  },
1341
+ /**
1342
+ * Sets a notification handler for when the prompt list changes on a server.
1343
+ *
1344
+ * @param serverName - Name of the server to monitor
1345
+ * @param handler - Callback function invoked when prompts are added/removed/modified
1346
+ * @returns Promise resolving when handler is registered
1347
+ * @throws {MastraError} If setting up the handler fails
1348
+ *
1349
+ * @example
1350
+ * ```typescript
1351
+ * await mcp.prompts.onListChanged('weatherServer', async () => {
1352
+ * console.log('Prompt list changed, re-fetching...');
1353
+ * const prompts = await mcp.prompts.list();
1354
+ * });
1355
+ * ```
1356
+ */
903
1357
  onListChanged: async (serverName, handler) => {
904
1358
  try {
905
1359
  const internalClient = await this.getConnectedClientForServer(serverName);
@@ -930,6 +1384,21 @@ To fix this you have three different options:
930
1384
  const idNamespace = v5(`MCPClient`, v5.DNS);
931
1385
  return v5(text, idNamespace);
932
1386
  }
1387
+ /**
1388
+ * Disconnects from all MCP servers and cleans up resources.
1389
+ *
1390
+ * This method gracefully closes all server connections and clears internal caches.
1391
+ * Safe to call multiple times - subsequent calls will wait for the first disconnect to complete.
1392
+ *
1393
+ * @example
1394
+ * ```typescript
1395
+ * // Cleanup on application shutdown
1396
+ * process.on('SIGTERM', async () => {
1397
+ * await mcp.disconnect();
1398
+ * process.exit(0);
1399
+ * });
1400
+ * ```
1401
+ */
933
1402
  async disconnect() {
934
1403
  if (this.disconnectPromise) {
935
1404
  return this.disconnectPromise;
@@ -945,6 +1414,25 @@ To fix this you have three different options:
945
1414
  })();
946
1415
  return this.disconnectPromise;
947
1416
  }
1417
+ /**
1418
+ * Retrieves all tools from all configured servers with namespaced names.
1419
+ *
1420
+ * Tool names are namespaced as `serverName_toolName` to prevent conflicts between servers.
1421
+ * This method is intended to be passed directly to an Agent definition.
1422
+ *
1423
+ * @returns Object mapping namespaced tool names to tool implementations
1424
+ * @throws {MastraError} If retrieving tools fails
1425
+ *
1426
+ * @example
1427
+ * ```typescript
1428
+ * const agent = new Agent({
1429
+ * name: 'Multi-tool Agent',
1430
+ * instructions: 'You have access to weather and stock tools.',
1431
+ * model: openai('gpt-4'),
1432
+ * tools: await mcp.getTools(), // weather_getWeather, stockPrice_getPrice
1433
+ * });
1434
+ * ```
1435
+ */
948
1436
  async getTools() {
949
1437
  this.addToInstanceCache();
950
1438
  const connectedTools = {};
@@ -966,6 +1454,28 @@ To fix this you have three different options:
966
1454
  }
967
1455
  return connectedTools;
968
1456
  }
1457
+ /**
1458
+ * Returns toolsets organized by server name for dynamic tool injection.
1459
+ *
1460
+ * Unlike getTools(), this returns tools grouped by server without namespacing.
1461
+ * This is intended to be passed dynamically to the generate() or stream() method.
1462
+ *
1463
+ * @returns Object mapping server names to their tool collections
1464
+ * @throws {MastraError} If retrieving toolsets fails
1465
+ *
1466
+ * @example
1467
+ * ```typescript
1468
+ * const agent = new Agent({
1469
+ * name: 'Dynamic Agent',
1470
+ * instructions: 'You can use tools dynamically.',
1471
+ * model: openai('gpt-4'),
1472
+ * });
1473
+ *
1474
+ * const response = await agent.stream(prompt, {
1475
+ * toolsets: await mcp.getToolsets(), // { weather: {...}, stockPrice: {...} }
1476
+ * });
1477
+ * ```
1478
+ */
969
1479
  async getToolsets() {
970
1480
  this.addToInstanceCache();
971
1481
  const connectedToolsets = {};
@@ -994,8 +1504,19 @@ To fix this you have three different options:
994
1504
  return this.resources.list();
995
1505
  }
996
1506
  /**
997
- * Get the current session IDs for all connected MCP clients using the Streamable HTTP transport.
998
- * Returns an object mapping server names to their session IDs.
1507
+ * Gets current session IDs for all connected MCP clients using Streamable HTTP transport.
1508
+ *
1509
+ * Returns an object mapping server names to their session IDs. Only includes servers
1510
+ * that are currently connected via Streamable HTTP transport.
1511
+ *
1512
+ * @returns Object mapping server names to session IDs
1513
+ *
1514
+ * @example
1515
+ * ```typescript
1516
+ * const sessions = mcp.sessionIds;
1517
+ * console.log(sessions);
1518
+ * // { weatherServer: 'abc-123', stockServer: 'def-456' }
1519
+ * ```
999
1520
  */
1000
1521
  get sessionIds() {
1001
1522
  const sessionIds = {};
@@ -1069,6 +1590,9 @@ To fix this you have three different options:
1069
1590
  }
1070
1591
  };
1071
1592
  var MCPConfiguration = class extends MCPClient {
1593
+ /**
1594
+ * @deprecated Use MCPClient constructor instead
1595
+ */
1072
1596
  constructor(args) {
1073
1597
  super(args);
1074
1598
  this.logger.warn(
@@ -1327,14 +1851,27 @@ var ServerPromptActions = class {
1327
1851
  getLogger;
1328
1852
  getSdkServer;
1329
1853
  clearDefinedPrompts;
1854
+ /**
1855
+ * @internal
1856
+ */
1330
1857
  constructor(dependencies) {
1331
1858
  this.getLogger = dependencies.getLogger;
1332
1859
  this.getSdkServer = dependencies.getSdkServer;
1333
1860
  this.clearDefinedPrompts = dependencies.clearDefinedPrompts;
1334
1861
  }
1335
1862
  /**
1336
- * Notifies the server that the overall list of available prompts has changed.
1337
- * This will clear the internal cache of defined prompts and send a list_changed notification to clients.
1863
+ * Notifies clients that the overall list of available prompts has changed.
1864
+ *
1865
+ * This clears the internal prompt cache and sends a `notifications/prompts/list_changed`
1866
+ * message to all clients, prompting them to re-fetch the prompt list.
1867
+ *
1868
+ * @throws {MastraError} If sending the notification fails
1869
+ *
1870
+ * @example
1871
+ * ```typescript
1872
+ * // After adding or modifying prompts
1873
+ * await server.prompts.notifyListChanged();
1874
+ * ```
1338
1875
  */
1339
1876
  async notifyListChanged() {
1340
1877
  this.getLogger().info("Prompt list change externally notified. Clearing definedPrompts and sending notification.");
@@ -1365,6 +1902,9 @@ var ServerResourceActions = class {
1365
1902
  getSdkServer;
1366
1903
  clearDefinedResources;
1367
1904
  clearDefinedResourceTemplates;
1905
+ /**
1906
+ * @internal
1907
+ */
1368
1908
  constructor(dependencies) {
1369
1909
  this.getSubscriptions = dependencies.getSubscriptions;
1370
1910
  this.getLogger = dependencies.getLogger;
@@ -1373,8 +1913,20 @@ var ServerResourceActions = class {
1373
1913
  this.clearDefinedResourceTemplates = dependencies.clearDefinedResourceTemplates;
1374
1914
  }
1375
1915
  /**
1376
- * Checks if any resources have been updated.
1377
- * If the resource is subscribed to by clients, an update notification will be sent.
1916
+ * Notifies subscribed clients that a specific resource has been updated.
1917
+ *
1918
+ * If clients are subscribed to the resource URI, they will receive a
1919
+ * `notifications/resources/updated` message to re-fetch the resource content.
1920
+ *
1921
+ * @param params - Notification parameters
1922
+ * @param params.uri - URI of the resource that was updated
1923
+ * @throws {MastraError} If sending the notification fails
1924
+ *
1925
+ * @example
1926
+ * ```typescript
1927
+ * // After updating a file resource
1928
+ * await server.resources.notifyUpdated({ uri: 'file://data.txt' });
1929
+ * ```
1378
1930
  */
1379
1931
  async notifyUpdated({ uri }) {
1380
1932
  if (this.getSubscriptions().has(uri)) {
@@ -1405,8 +1957,18 @@ var ServerResourceActions = class {
1405
1957
  }
1406
1958
  }
1407
1959
  /**
1408
- * Notifies the server that the overall list of available resources has changed.
1409
- * This will clear the internal cache of defined resources and send a list_changed notification to clients.
1960
+ * Notifies clients that the overall list of available resources has changed.
1961
+ *
1962
+ * This clears the internal resource cache and sends a `notifications/resources/list_changed`
1963
+ * message to all clients, prompting them to re-fetch the resource list.
1964
+ *
1965
+ * @throws {MastraError} If sending the notification fails
1966
+ *
1967
+ * @example
1968
+ * ```typescript
1969
+ * // After adding a new resource to your resource handler
1970
+ * await server.resources.notifyListChanged();
1971
+ * ```
1410
1972
  */
1411
1973
  async notifyListChanged() {
1412
1974
  this.getLogger().info(
@@ -1451,36 +2013,134 @@ var MCPServer = class extends MCPServerBase {
1451
2013
  promptOptions;
1452
2014
  subscriptions = /* @__PURE__ */ new Set();
1453
2015
  currentLoggingLevel;
2016
+ /**
2017
+ * Provides methods to notify clients about resource changes.
2018
+ *
2019
+ * @example
2020
+ * ```typescript
2021
+ * // Notify that a specific resource was updated
2022
+ * await server.resources.notifyUpdated({ uri: 'file://data.txt' });
2023
+ *
2024
+ * // Notify that the resource list changed
2025
+ * await server.resources.notifyListChanged();
2026
+ * ```
2027
+ */
1454
2028
  resources;
2029
+ /**
2030
+ * Provides methods to notify clients about prompt changes.
2031
+ *
2032
+ * @example
2033
+ * ```typescript
2034
+ * // Notify that the prompt list changed
2035
+ * await server.prompts.notifyListChanged();
2036
+ * ```
2037
+ */
1455
2038
  prompts;
2039
+ /**
2040
+ * Provides methods for interactive user input collection during tool execution.
2041
+ *
2042
+ * @example
2043
+ * ```typescript
2044
+ * // Within a tool's execute function
2045
+ * const result = await options.elicitation.sendRequest({
2046
+ * message: 'Please provide your email address',
2047
+ * requestedSchema: {
2048
+ * type: 'object',
2049
+ * properties: {
2050
+ * email: { type: 'string', format: 'email' }
2051
+ * },
2052
+ * required: ['email']
2053
+ * }
2054
+ * });
2055
+ * ```
2056
+ */
1456
2057
  elicitation;
1457
2058
  /**
1458
- * Get the current stdio transport.
2059
+ * Gets the stdio transport instance if the server was started using stdio.
2060
+ *
2061
+ * This is primarily for internal checks or testing purposes.
2062
+ *
2063
+ * @returns The stdio transport instance, or undefined if not using stdio transport
1459
2064
  */
1460
2065
  getStdioTransport() {
1461
2066
  return this.stdioTransport;
1462
2067
  }
1463
2068
  /**
1464
- * Get the current SSE transport.
2069
+ * Gets the SSE transport instance if the server was started using SSE.
2070
+ *
2071
+ * This is primarily for internal checks or testing purposes.
2072
+ *
2073
+ * @returns The SSE transport instance, or undefined if not using SSE transport
1465
2074
  */
1466
2075
  getSseTransport() {
1467
2076
  return this.sseTransport;
1468
2077
  }
1469
2078
  /**
1470
- * Get the current SSE Hono transport.
2079
+ * Gets the Hono SSE transport instance for a specific session.
2080
+ *
2081
+ * This is primarily for internal checks or testing purposes.
2082
+ *
2083
+ * @param sessionId - The session identifier
2084
+ * @returns The Hono SSE transport instance, or undefined if session not found
1471
2085
  */
1472
2086
  getSseHonoTransport(sessionId) {
1473
2087
  return this.sseHonoTransports.get(sessionId);
1474
2088
  }
1475
2089
  /**
1476
- * Get the current server instance.
2090
+ * Gets the underlying MCP SDK Server instance.
2091
+ *
2092
+ * This provides access to the low-level server instance for advanced use cases.
2093
+ *
2094
+ * @returns The Server instance from @modelcontextprotocol/sdk
1477
2095
  */
1478
2096
  getServer() {
1479
2097
  return this.server;
1480
2098
  }
1481
2099
  /**
1482
- * Construct a new MCPServer instance.
1483
- * @param opts - Configuration options for the server, including registry metadata.
2100
+ * Creates a new MCPServer instance.
2101
+ *
2102
+ * The server exposes tools, agents, and workflows to MCP clients. Agents are automatically
2103
+ * converted to tools named `ask_<agentKey>`, and workflows become tools named `run_<workflowKey>`.
2104
+ *
2105
+ * @param opts - Configuration options for the server
2106
+ * @param opts.name - Descriptive name for the server (e.g., 'My Weather Server')
2107
+ * @param opts.version - Semantic version of the server (e.g., '1.0.0')
2108
+ * @param opts.tools - Object mapping tool names to tool definitions
2109
+ * @param opts.agents - Optional object mapping agent identifiers to Agent instances
2110
+ * @param opts.workflows - Optional object mapping workflow identifiers to Workflow instances
2111
+ * @param opts.resources - Optional resource configuration for exposing data and content
2112
+ * @param opts.prompts - Optional prompt configuration for exposing reusable templates
2113
+ * @param opts.id - Optional unique identifier (generated if not provided)
2114
+ * @param opts.description - Optional description of what the server does
2115
+ *
2116
+ * @example
2117
+ * ```typescript
2118
+ * import { MCPServer } from '@mastra/mcp';
2119
+ * import { Agent } from '@mastra/core/agent';
2120
+ * import { createTool } from '@mastra/core/tools';
2121
+ * import { z } from 'zod';
2122
+ *
2123
+ * const myAgent = new Agent({
2124
+ * name: 'Helper',
2125
+ * description: 'A helpful assistant',
2126
+ * instructions: 'You are helpful.',
2127
+ * model: openai('gpt-4o-mini'),
2128
+ * });
2129
+ *
2130
+ * const server = new MCPServer({
2131
+ * name: 'My Server',
2132
+ * version: '1.0.0',
2133
+ * tools: {
2134
+ * weatherTool: createTool({
2135
+ * id: 'getWeather',
2136
+ * description: 'Gets weather',
2137
+ * inputSchema: z.object({ location: z.string() }),
2138
+ * execute: async ({ context }) => `Sunny in ${context.location}`,
2139
+ * })
2140
+ * },
2141
+ * agents: { myAgent },
2142
+ * });
2143
+ * ```
1484
2144
  */
1485
2145
  constructor(opts) {
1486
2146
  super(opts);
@@ -2084,7 +2744,23 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2084
2744
  return allConvertedTools;
2085
2745
  }
2086
2746
  /**
2087
- * Start the MCP server using stdio transport (for Windsurf integration).
2747
+ * Starts the MCP server using standard input/output (stdio) transport.
2748
+ *
2749
+ * This is typically used when running the server as a command-line program that MCP clients
2750
+ * spawn as a subprocess (e.g., integration with Windsurf, Cursor, or Claude Desktop).
2751
+ *
2752
+ * @throws {MastraError} If the stdio connection fails
2753
+ *
2754
+ * @example
2755
+ * ```typescript
2756
+ * const server = new MCPServer({
2757
+ * name: 'My Server',
2758
+ * version: '1.0.0',
2759
+ * tools: { weatherTool },
2760
+ * });
2761
+ *
2762
+ * await server.startStdio();
2763
+ * ```
2088
2764
  */
2089
2765
  async startStdio() {
2090
2766
  this.stdioTransport = new StdioServerTransport();
@@ -2108,14 +2784,38 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2108
2784
  this.logger.info("Started MCP Server (stdio)");
2109
2785
  }
2110
2786
  /**
2111
- * Handles MCP-over-SSE protocol for user-provided HTTP servers.
2112
- * Call this from your HTTP server for both the SSE and message endpoints.
2787
+ * Integrates the MCP server with an existing HTTP server using Server-Sent Events (SSE).
2113
2788
  *
2114
- * @param url Parsed URL of the incoming request
2115
- * @param ssePath Path for establishing the SSE connection (e.g. '/sse')
2116
- * @param messagePath Path for POSTing client messages (e.g. '/message')
2117
- * @param req Incoming HTTP request
2118
- * @param res HTTP response (must support .write/.end)
2789
+ * Call this method from your web server's request handler for both the SSE and message paths.
2790
+ * This enables web-based MCP clients to connect to your server.
2791
+ *
2792
+ * @param options - Configuration for SSE integration
2793
+ * @param options.url - Parsed URL of the incoming request
2794
+ * @param options.ssePath - Path for establishing SSE connection (e.g., '/sse')
2795
+ * @param options.messagePath - Path for POSTing client messages (e.g., '/message')
2796
+ * @param options.req - Incoming HTTP request object
2797
+ * @param options.res - HTTP response object (must support .write/.end)
2798
+ *
2799
+ * @throws {MastraError} If SSE connection setup fails
2800
+ *
2801
+ * @example
2802
+ * ```typescript
2803
+ * import http from 'http';
2804
+ *
2805
+ * const httpServer = http.createServer(async (req, res) => {
2806
+ * await server.startSSE({
2807
+ * url: new URL(req.url || '', `http://localhost:1234`),
2808
+ * ssePath: '/sse',
2809
+ * messagePath: '/message',
2810
+ * req,
2811
+ * res,
2812
+ * });
2813
+ * });
2814
+ *
2815
+ * httpServer.listen(1234, () => {
2816
+ * console.log('MCP server listening on http://localhost:1234/sse');
2817
+ * });
2818
+ * ```
2119
2819
  */
2120
2820
  async startSSE({ url, ssePath, messagePath, req, res }) {
2121
2821
  try {
@@ -2157,13 +2857,37 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2157
2857
  }
2158
2858
  }
2159
2859
  /**
2160
- * Handles MCP-over-SSE protocol for user-provided HTTP servers.
2161
- * Call this from your HTTP server for both the SSE and message endpoints.
2860
+ * Integrates the MCP server with a Hono web framework using Server-Sent Events (SSE).
2861
+ *
2862
+ * Call this method from your Hono server's request handler for both the SSE and message paths.
2863
+ * This enables Hono-based web applications to expose MCP servers.
2864
+ *
2865
+ * @param options - Configuration for Hono SSE integration
2866
+ * @param options.url - Parsed URL of the incoming request
2867
+ * @param options.ssePath - Path for establishing SSE connection (e.g., '/hono-sse')
2868
+ * @param options.messagePath - Path for POSTing client messages (e.g., '/message')
2869
+ * @param options.context - Hono context object
2870
+ *
2871
+ * @throws {MastraError} If Hono SSE connection setup fails
2872
+ *
2873
+ * @example
2874
+ * ```typescript
2875
+ * import { Hono } from 'hono';
2876
+ *
2877
+ * const app = new Hono();
2878
+ *
2879
+ * app.all('*', async (c) => {
2880
+ * const url = new URL(c.req.url);
2881
+ * return await server.startHonoSSE({
2882
+ * url,
2883
+ * ssePath: '/hono-sse',
2884
+ * messagePath: '/message',
2885
+ * context: c,
2886
+ * });
2887
+ * });
2162
2888
  *
2163
- * @param url Parsed URL of the incoming request
2164
- * @param ssePath Path for establishing the SSE connection (e.g. '/sse')
2165
- * @param messagePath Path for POSTing client messages (e.g. '/message')
2166
- * @param context Incoming Hono context
2889
+ * export default app;
2890
+ * ```
2167
2891
  */
2168
2892
  async startHonoSSE({ url, ssePath, messagePath, context }) {
2169
2893
  try {
@@ -2213,14 +2937,46 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2213
2937
  }
2214
2938
  }
2215
2939
  /**
2216
- * Handles MCP-over-StreamableHTTP protocol for user-provided HTTP servers.
2217
- * Call this from your HTTP server for the streamable HTTP endpoint.
2940
+ * Integrates the MCP server with an existing HTTP server using streamable HTTP transport.
2218
2941
  *
2219
- * @param url Parsed URL of the incoming request
2220
- * @param httpPath Path for establishing the streamable HTTP connection (e.g. '/mcp')
2221
- * @param req Incoming HTTP request
2222
- * @param res HTTP response (must support .write/.end)
2223
- * @param options Optional options to pass to the transport (e.g. sessionIdGenerator)
2942
+ * This is the recommended modern transport method, providing better session management and
2943
+ * reliability compared to SSE. Call this from your HTTP server's request handler.
2944
+ *
2945
+ * @param options - Configuration for HTTP integration
2946
+ * @param options.url - Parsed URL of the incoming request
2947
+ * @param options.httpPath - Path for the MCP endpoint (e.g., '/mcp')
2948
+ * @param options.req - Incoming HTTP request (http.IncomingMessage)
2949
+ * @param options.res - HTTP response object (http.ServerResponse)
2950
+ * @param options.options - Optional transport options
2951
+ * @param options.options.sessionIdGenerator - Function to generate unique session IDs (defaults to randomUUID)
2952
+ * @param options.options.onsessioninitialized - Callback when a new session is initialized
2953
+ * @param options.options.enableJsonResponse - If true, return JSON instead of SSE streaming
2954
+ * @param options.options.eventStore - Event store for message resumability
2955
+ *
2956
+ * @throws {MastraError} If HTTP connection setup fails
2957
+ *
2958
+ * @example
2959
+ * ```typescript
2960
+ * import http from 'http';
2961
+ * import { randomUUID } from 'crypto';
2962
+ *
2963
+ * const httpServer = http.createServer(async (req, res) => {
2964
+ * await server.startHTTP({
2965
+ * url: new URL(req.url || '', 'http://localhost:1234'),
2966
+ * httpPath: '/mcp',
2967
+ * req,
2968
+ * res,
2969
+ * options: {
2970
+ * sessionIdGenerator: () => randomUUID(),
2971
+ * onsessioninitialized: (sessionId) => {
2972
+ * console.log(`New MCP session: ${sessionId}`);
2973
+ * },
2974
+ * },
2975
+ * });
2976
+ * });
2977
+ *
2978
+ * httpServer.listen(1234);
2979
+ * ```
2224
2980
  */
2225
2981
  async startHTTP({
2226
2982
  url,
@@ -2371,6 +3127,27 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2371
3127
  }
2372
3128
  }
2373
3129
  }
3130
+ /**
3131
+ * Establishes the SSE connection for the MCP server.
3132
+ *
3133
+ * This is a lower-level method called internally by `startSSE()`. In most cases,
3134
+ * you should use `startSSE()` instead which handles both connection establishment
3135
+ * and message routing.
3136
+ *
3137
+ * @param params - Connection parameters
3138
+ * @param params.messagePath - Path for POST requests from the client
3139
+ * @param params.res - HTTP response object for the SSE stream
3140
+ * @throws {MastraError} If SSE connection establishment fails
3141
+ *
3142
+ * @example
3143
+ * ```typescript
3144
+ * // Usually called internally by startSSE()
3145
+ * await server.connectSSE({
3146
+ * messagePath: '/message',
3147
+ * res: response
3148
+ * });
3149
+ * ```
3150
+ */
2374
3151
  async connectSSE({
2375
3152
  messagePath,
2376
3153
  res
@@ -2403,6 +3180,27 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2403
3180
  throw mastraError;
2404
3181
  }
2405
3182
  }
3183
+ /**
3184
+ * Establishes the Hono SSE connection for the MCP server.
3185
+ *
3186
+ * This is a lower-level method called internally by `startHonoSSE()`. In most cases,
3187
+ * you should use `startHonoSSE()` instead which handles both connection establishment
3188
+ * and message routing.
3189
+ *
3190
+ * @param params - Connection parameters
3191
+ * @param params.messagePath - Path for POST requests from the client
3192
+ * @param params.stream - Hono SSE streaming API object
3193
+ * @throws {MastraError} If Hono SSE connection establishment fails
3194
+ *
3195
+ * @example
3196
+ * ```typescript
3197
+ * // Usually called internally by startHonoSSE()
3198
+ * await server.connectHonoSSE({
3199
+ * messagePath: '/message',
3200
+ * stream: sseStream
3201
+ * });
3202
+ * ```
3203
+ */
2406
3204
  async connectHonoSSE({ messagePath, stream: stream2 }) {
2407
3205
  this.logger.debug("Received SSE connection");
2408
3206
  const sseTransport = new SSETransport(messagePath, stream2);
@@ -2444,7 +3242,21 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2444
3242
  }
2445
3243
  }
2446
3244
  /**
2447
- * Close the MCP server and all its connections
3245
+ * Closes the MCP server and releases all resources.
3246
+ *
3247
+ * This method cleanly shuts down all active transports (stdio, SSE, HTTP) and their
3248
+ * associated connections. Call this when your application is shutting down.
3249
+ *
3250
+ * @throws {MastraError} If closing the server fails
3251
+ *
3252
+ * @example
3253
+ * ```typescript
3254
+ * // Graceful shutdown
3255
+ * process.on('SIGTERM', async () => {
3256
+ * await server.close();
3257
+ * process.exit(0);
3258
+ * });
3259
+ * ```
2448
3260
  */
2449
3261
  async close() {
2450
3262
  try {
@@ -2491,8 +3303,19 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2491
3303
  }
2492
3304
  }
2493
3305
  /**
2494
- * Gets the basic information about the server, conforming to the Server schema.
2495
- * @returns ServerInfo object.
3306
+ * Gets basic information about the server.
3307
+ *
3308
+ * Returns metadata including server ID, name, description, repository, and version details.
3309
+ * This information conforms to the MCP Server schema.
3310
+ *
3311
+ * @returns Server information object
3312
+ *
3313
+ * @example
3314
+ * ```typescript
3315
+ * const info = server.getServerInfo();
3316
+ * console.log(`${info.name} v${info.version_detail.version}`);
3317
+ * // Output: My Weather Server v1.0.0
3318
+ * ```
2496
3319
  */
2497
3320
  getServerInfo() {
2498
3321
  return {
@@ -2508,8 +3331,19 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2508
3331
  };
2509
3332
  }
2510
3333
  /**
2511
- * Gets detailed information about the server, conforming to the ServerDetail schema.
2512
- * @returns ServerDetailInfo object.
3334
+ * Gets detailed information about the server including packaging and deployment metadata.
3335
+ *
3336
+ * Returns extended server information with package details, remotes, and deployment configurations.
3337
+ * This information conforms to the MCP ServerDetail schema.
3338
+ *
3339
+ * @returns Detailed server information object
3340
+ *
3341
+ * @example
3342
+ * ```typescript
3343
+ * const detail = server.getServerDetail();
3344
+ * console.log(detail.package_canonical); // 'npm'
3345
+ * console.log(detail.packages); // Package installation info
3346
+ * ```
2513
3347
  */
2514
3348
  getServerDetail() {
2515
3349
  return {
@@ -2520,9 +3354,21 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2520
3354
  };
2521
3355
  }
2522
3356
  /**
2523
- * Gets a list of tools provided by this MCP server, including their schemas.
2524
- * This leverages the same tool information used by the internal ListTools MCP request.
2525
- * @returns An object containing an array of tool information.
3357
+ * Gets a list of all tools provided by this MCP server with their schemas.
3358
+ *
3359
+ * Returns information about all registered tools including explicit tools, agent-derived tools,
3360
+ * and workflow-derived tools. Includes input/output schemas and tool types.
3361
+ *
3362
+ * @returns Object containing array of tool information
3363
+ *
3364
+ * @example
3365
+ * ```typescript
3366
+ * const toolList = server.getToolListInfo();
3367
+ * toolList.tools.forEach(tool => {
3368
+ * console.log(`${tool.name}: ${tool.description}`);
3369
+ * console.log(`Type: ${tool.toolType || 'tool'}`);
3370
+ * });
3371
+ * ```
2526
3372
  */
2527
3373
  getToolListInfo() {
2528
3374
  this.logger.debug(`Getting tool list information for MCPServer '${this.name}'`);
@@ -2539,8 +3385,21 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2539
3385
  }
2540
3386
  /**
2541
3387
  * Gets information for a specific tool provided by this MCP server.
2542
- * @param toolId The ID/name of the tool to retrieve.
2543
- * @returns Tool information (name, description, inputSchema) or undefined if not found.
3388
+ *
3389
+ * Returns detailed information about a single tool including its name, description, schemas, and type.
3390
+ * Returns undefined if the tool is not found.
3391
+ *
3392
+ * @param toolId - The ID/name of the tool to retrieve
3393
+ * @returns Tool information object or undefined if not found
3394
+ *
3395
+ * @example
3396
+ * ```typescript
3397
+ * const toolInfo = server.getToolInfo('getWeather');
3398
+ * if (toolInfo) {
3399
+ * console.log(toolInfo.description);
3400
+ * console.log(toolInfo.inputSchema);
3401
+ * }
3402
+ * ```
2544
3403
  */
2545
3404
  getToolInfo(toolId) {
2546
3405
  const tool = this.convertedTools[toolId];
@@ -2559,11 +3418,25 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2559
3418
  }
2560
3419
  /**
2561
3420
  * Executes a specific tool provided by this MCP server.
2562
- * @param toolId The ID/name of the tool to execute.
2563
- * @param args The arguments to pass to the tool's execute function.
2564
- * @param executionContext Optional context for the tool execution.
2565
- * @returns A promise that resolves to the result of the tool execution.
2566
- * @throws Error if the tool is not found, validation fails, or execution fails.
3421
+ *
3422
+ * This method validates the tool arguments against the input schema and executes the tool.
3423
+ * If validation fails, returns an error object instead of throwing.
3424
+ *
3425
+ * @param toolId - The ID/name of the tool to execute
3426
+ * @param args - The arguments to pass to the tool's execute function
3427
+ * @param executionContext - Optional context including messages and toolCallId
3428
+ * @returns Promise resolving to the tool execution result
3429
+ * @throws {MastraError} If the tool is not found or execution fails
3430
+ *
3431
+ * @example
3432
+ * ```typescript
3433
+ * const result = await server.executeTool(
3434
+ * 'getWeather',
3435
+ * { location: 'London' },
3436
+ * { toolCallId: 'call_123' }
3437
+ * );
3438
+ * console.log(result);
3439
+ * ```
2567
3440
  */
2568
3441
  async executeTool(toolId, args, executionContext) {
2569
3442
  const tool = this.convertedTools[toolId];