@mastra/mcp 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/client/actions/progress.d.ts +2 -3
  3. package/dist/client/actions/progress.d.ts.map +1 -1
  4. package/dist/client/actions/resource.d.ts +6 -2
  5. package/dist/client/actions/resource.d.ts.map +1 -1
  6. package/dist/client/client.d.ts +171 -175
  7. package/dist/client/client.d.ts.map +1 -1
  8. package/dist/client/configuration.d.ts +6 -2
  9. package/dist/client/configuration.d.ts.map +1 -1
  10. package/dist/client/types.d.ts +17 -0
  11. package/dist/client/types.d.ts.map +1 -1
  12. package/dist/docs/SKILL.md +3 -3
  13. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  14. package/dist/docs/references/docs-mcp-overview.md +1 -1
  15. package/dist/docs/references/docs-mcp-publishing-mcp-server.md +4 -4
  16. package/dist/docs/references/reference-tools-mcp-client.md +13 -13
  17. package/dist/docs/references/reference-tools-mcp-server.md +27 -27
  18. package/dist/index.cjs +62 -89
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.js +63 -90
  21. package/dist/index.js.map +1 -1
  22. package/dist/server/server.d.ts +1 -0
  23. package/dist/server/server.d.ts.map +1 -1
  24. package/package.json +10 -11
  25. package/dist/__fixtures__/fire-crawl-complex-schema.d.ts +0 -5
  26. package/dist/__fixtures__/fire-crawl-complex-schema.d.ts.map +0 -1
  27. package/dist/__fixtures__/server-weather.d.ts +0 -2
  28. package/dist/__fixtures__/server-weather.d.ts.map +0 -1
  29. package/dist/__fixtures__/stock-price.d.ts +0 -26
  30. package/dist/__fixtures__/stock-price.d.ts.map +0 -1
  31. package/dist/__fixtures__/tools.d.ts +0 -12
  32. package/dist/__fixtures__/tools.d.ts.map +0 -1
  33. package/dist/__fixtures__/weather.d.ts +0 -4
  34. package/dist/__fixtures__/weather.d.ts.map +0 -1
package/dist/index.cjs CHANGED
@@ -5,7 +5,6 @@ var $RefParser = require('@apidevtools/json-schema-ref-parser');
5
5
  var base = require('@mastra/core/base');
6
6
  var error = require('@mastra/core/error');
7
7
  var tools = require('@mastra/core/tools');
8
- var utils = require('@mastra/core/utils');
9
8
  var index_js = require('@modelcontextprotocol/sdk/client/index.js');
10
9
  var sse_js = require('@modelcontextprotocol/sdk/client/sse.js');
11
10
  var stdio_js = require('@modelcontextprotocol/sdk/client/stdio.js');
@@ -13,14 +12,13 @@ var streamableHttp_js = require('@modelcontextprotocol/sdk/client/streamableHttp
13
12
  var protocol_js = require('@modelcontextprotocol/sdk/shared/protocol.js');
14
13
  var types_js = require('@modelcontextprotocol/sdk/types.js');
15
14
  var exitHook = require('exit-hook');
16
- var zod = require('zod');
17
- var zodFromJsonSchema = require('zod-from-json-schema');
18
- var zodFromJsonSchemaV3 = require('zod-from-json-schema-v3');
19
15
  var equal = require('fast-deep-equal');
20
16
  var uuid = require('uuid');
21
17
  var crypto$1 = require('crypto');
22
18
  var mcp = require('@mastra/core/mcp');
23
19
  var requestContext = require('@mastra/core/request-context');
20
+ var schema = require('@mastra/core/schema');
21
+ var utils = require('@mastra/core/utils');
24
22
  var index_js$1 = require('@modelcontextprotocol/sdk/server/index.js');
25
23
  var sse_js$1 = require('@modelcontextprotocol/sdk/server/sse.js');
26
24
  var stdio_js$1 = require('@modelcontextprotocol/sdk/server/stdio.js');
@@ -499,18 +497,10 @@ var InternalMastraMCPClient = class extends base.MastraBase {
499
497
  }
500
498
  setupLogging() {
501
499
  if (this.enableServerLogs) {
502
- this.client.setNotificationHandler(
503
- zod.z.object({
504
- method: zod.z.literal("notifications/message"),
505
- params: zod.z.object({
506
- level: zod.z.string()
507
- }).passthrough()
508
- }),
509
- (notification) => {
510
- const { level, ...params } = notification.params;
511
- this.log(level, "[MCP SERVER LOG]", params);
512
- }
513
- );
500
+ this.client.setNotificationHandler(types_js.LoggingMessageNotificationSchema, (notification) => {
501
+ const { level, ...params } = notification.params;
502
+ this.log(level, "[MCP SERVER LOG]", params);
503
+ });
514
504
  }
515
505
  }
516
506
  /**
@@ -576,7 +566,9 @@ var InternalMastraMCPClient = class extends base.MastraBase {
576
566
  this.transport = new stdio_js.StdioClientTransport({
577
567
  command,
578
568
  args: this.serverConfig.args,
579
- env: { ...stdio_js.getDefaultEnvironment(), ...this.serverConfig.env || {} }
569
+ env: { ...stdio_js.getDefaultEnvironment(), ...this.serverConfig.env || {} },
570
+ stderr: this.serverConfig.stderr,
571
+ cwd: this.serverConfig.cwd
580
572
  });
581
573
  await this.client.connect(this.transport, { timeout: this.serverConfig.timeout ?? this.timeout });
582
574
  this.log("debug", `Successfully connected to MCP server via Stdio`);
@@ -795,13 +787,13 @@ var InternalMastraMCPClient = class extends base.MastraBase {
795
787
  }
796
788
  async subscribeResource(uri) {
797
789
  this.log("debug", `Subscribing to resource on MCP server: ${uri}`);
798
- return await this.client.request({ method: "resources/subscribe", params: { uri } }, zod.z.object({}), {
790
+ return await this.client.request({ method: "resources/subscribe", params: { uri } }, types_js.EmptyResultSchema, {
799
791
  timeout: this.timeout
800
792
  });
801
793
  }
802
794
  async unsubscribeResource(uri) {
803
795
  this.log("debug", `Unsubscribing from resource on MCP server: ${uri}`);
804
- return await this.client.request({ method: "resources/unsubscribe", params: { uri } }, zod.z.object({}), {
796
+ return await this.client.request({ method: "resources/unsubscribe", params: { uri } }, types_js.EmptyResultSchema, {
805
797
  timeout: this.timeout
806
798
  });
807
799
  }
@@ -874,17 +866,9 @@ var InternalMastraMCPClient = class extends base.MastraBase {
874
866
  });
875
867
  }
876
868
  async convertInputSchema(inputSchema) {
877
- if (utils.isZodType(inputSchema)) {
878
- return inputSchema;
879
- }
880
869
  try {
881
870
  await $RefParser__default.default.dereference(inputSchema);
882
- const jsonSchemaToConvert = "jsonSchema" in inputSchema ? inputSchema.jsonSchema : inputSchema;
883
- if ("toJSONSchema" in zod.z) {
884
- return zodFromJsonSchema.convertJsonSchemaToZod(jsonSchemaToConvert);
885
- } else {
886
- return zodFromJsonSchemaV3.convertJsonSchemaToZod(jsonSchemaToConvert);
887
- }
871
+ return "jsonSchema" in inputSchema ? inputSchema.jsonSchema : inputSchema;
888
872
  } catch (error$1) {
889
873
  let errorDetails;
890
874
  if (error$1 instanceof Error) {
@@ -896,7 +880,7 @@ var InternalMastraMCPClient = class extends base.MastraBase {
896
880
  errorDetails = String(error$1);
897
881
  }
898
882
  }
899
- this.log("error", "Failed to convert JSON schema to Zod schema using zodFromJsonSchema", {
883
+ this.log("error", "Failed to dereference JSON schema", {
900
884
  error: errorDetails,
901
885
  originalJsonSchema: inputSchema
902
886
  });
@@ -908,46 +892,11 @@ var InternalMastraMCPClient = class extends base.MastraBase {
908
892
  });
909
893
  }
910
894
  }
911
- /**
912
- * Recursively applies `.passthrough()` to all ZodObject schemas so that
913
- * unknown keys returned by an MCP server are preserved instead of being
914
- * silently stripped by Zod's default "strip" mode.
915
- */
916
- applyPassthrough(schema) {
917
- if (schema instanceof zod.z.ZodObject) {
918
- const shape = schema.shape;
919
- const newShape = {};
920
- for (const key of Object.keys(shape)) {
921
- newShape[key] = this.applyPassthrough(shape[key]);
922
- }
923
- return zod.z.object(newShape).passthrough();
924
- }
925
- if (schema instanceof zod.z.ZodArray) {
926
- return zod.z.array(this.applyPassthrough(schema.element));
927
- }
928
- if (schema instanceof zod.z.ZodOptional) {
929
- return this.applyPassthrough(schema.unwrap()).optional();
930
- }
931
- if (schema instanceof zod.z.ZodNullable) {
932
- return this.applyPassthrough(schema.unwrap()).nullable();
933
- }
934
- return schema;
935
- }
936
895
  async convertOutputSchema(outputSchema) {
937
896
  if (!outputSchema) return;
938
- if (utils.isZodType(outputSchema)) {
939
- return outputSchema;
940
- }
941
897
  try {
942
898
  await $RefParser__default.default.dereference(outputSchema);
943
- const jsonSchemaToConvert = "jsonSchema" in outputSchema ? outputSchema.jsonSchema : outputSchema;
944
- let zodSchema;
945
- if ("toJSONSchema" in zod.z) {
946
- zodSchema = zodFromJsonSchema.convertJsonSchemaToZod(jsonSchemaToConvert);
947
- } else {
948
- zodSchema = zodFromJsonSchemaV3.convertJsonSchemaToZod(jsonSchemaToConvert);
949
- }
950
- return this.applyPassthrough(zodSchema);
899
+ return "jsonSchema" in outputSchema ? outputSchema.jsonSchema : outputSchema;
951
900
  } catch (error$1) {
952
901
  let errorDetails;
953
902
  if (error$1 instanceof Error) {
@@ -959,7 +908,7 @@ var InternalMastraMCPClient = class extends base.MastraBase {
959
908
  errorDetails = String(error$1);
960
909
  }
961
910
  }
962
- this.log("error", "Failed to convert JSON schema to Zod schema using zodFromJsonSchema", {
911
+ this.log("error", "Failed to dereference JSON schema", {
963
912
  error: errorDetails,
964
913
  originalJsonSchema: outputSchema
965
914
  });
@@ -983,6 +932,10 @@ var InternalMastraMCPClient = class extends base.MastraBase {
983
932
  description: tool.description || "",
984
933
  inputSchema: await this.convertInputSchema(tool.inputSchema),
985
934
  outputSchema: await this.convertOutputSchema(tool.outputSchema),
935
+ mcpMetadata: {
936
+ serverName: this.name,
937
+ serverVersion: this.client.getServerVersion()?.version
938
+ },
986
939
  execute: async (input, context) => {
987
940
  const operationContext = context?.requestContext ?? null;
988
941
  return this.operationContextStore.run(operationContext, async () => {
@@ -997,7 +950,8 @@ var InternalMastraMCPClient = class extends base.MastraBase {
997
950
  },
998
951
  types_js.CallToolResultSchema,
999
952
  {
1000
- timeout: this.timeout
953
+ timeout: this.timeout,
954
+ signal: context?.abortSignal
1001
955
  }
1002
956
  );
1003
957
  this.log("debug", `Tool executed successfully: ${tool.name}`);
@@ -2747,10 +2701,10 @@ var MCPServer = class extends mcp.MCPServerBase {
2747
2701
  const toolSpec = {
2748
2702
  name: tool.id || "unknown",
2749
2703
  description: tool.description,
2750
- inputSchema: tool.parameters.jsonSchema
2704
+ inputSchema: this.convertSchema(tool.parameters)
2751
2705
  };
2752
2706
  if (tool.outputSchema) {
2753
- toolSpec.outputSchema = tool.outputSchema.jsonSchema;
2707
+ toolSpec.outputSchema = this.convertSchema(tool.outputSchema);
2754
2708
  }
2755
2709
  if (tool.mcp?.annotations) {
2756
2710
  toolSpec.annotations = tool.mcp.annotations;
@@ -2862,17 +2816,18 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
2862
2816
  return response;
2863
2817
  } catch (error$1) {
2864
2818
  const duration = Date.now() - startTime;
2865
- if (error$1 instanceof zod.z.ZodError) {
2819
+ if (error$1 instanceof Error && "issues" in error$1 && Array.isArray(error$1.issues)) {
2820
+ const issues = error$1.issues;
2866
2821
  this.logger.warn("Invalid tool arguments", {
2867
2822
  tool: request.params.name,
2868
- errors: error$1.errors,
2823
+ errors: issues,
2869
2824
  duration: `${duration}ms`
2870
2825
  });
2871
2826
  return {
2872
2827
  content: [
2873
2828
  {
2874
2829
  type: "text",
2875
- text: `Invalid arguments: ${error$1.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ")}`
2830
+ text: `Invalid arguments: ${issues.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ")}`
2876
2831
  }
2877
2832
  ],
2878
2833
  isError: true
@@ -3105,12 +3060,18 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
3105
3060
  const agentToolDefinition = tools.createTool({
3106
3061
  id: agentToolName,
3107
3062
  description: `Ask agent '${agent.name}' a question. Agent description: ${agentDescription}`,
3108
- inputSchema: zod.z.object({
3109
- message: zod.z.string().describe("The question or input for the agent.")
3110
- }),
3063
+ inputSchema: {
3064
+ type: "object",
3065
+ properties: {
3066
+ message: { type: "string", description: "The question or input for the agent." }
3067
+ },
3068
+ required: ["message"],
3069
+ additionalProperties: false
3070
+ },
3111
3071
  execute: async (inputData, context) => {
3072
+ const { message } = inputData;
3112
3073
  this.logger.debug(
3113
- `Executing agent tool '${agentToolName}' for agent '${agent.name}' with message: "${inputData.message}"`
3074
+ `Executing agent tool '${agentToolName}' for agent '${agent.name}' with message: "${message}"`
3114
3075
  );
3115
3076
  try {
3116
3077
  const proxiedContext = context?.requestContext || new requestContext.RequestContext();
@@ -3119,7 +3080,7 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
3119
3080
  proxiedContext.set(key, value);
3120
3081
  });
3121
3082
  }
3122
- const response = await agent.generate(inputData.message, {
3083
+ const response = await agent.generate(message, {
3123
3084
  ...context ?? {},
3124
3085
  requestContext: proxiedContext
3125
3086
  });
@@ -3972,6 +3933,12 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
3972
3933
  remotes: this.remotes
3973
3934
  };
3974
3935
  }
3936
+ convertSchema(schema$1) {
3937
+ if (schema.isStandardSchemaWithJSON(schema$1)) {
3938
+ return schema.standardSchemaToJSONSchema(schema$1);
3939
+ }
3940
+ return schema$1?.jsonSchema || schema$1;
3941
+ }
3975
3942
  /**
3976
3943
  * Gets a list of all tools provided by this MCP server with their schemas.
3977
3944
  *
@@ -3996,8 +3963,8 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
3996
3963
  id: toolId,
3997
3964
  name: tool.id || toolId,
3998
3965
  description: tool.description,
3999
- inputSchema: tool.parameters?.jsonSchema || tool.parameters,
4000
- outputSchema: tool.outputSchema?.jsonSchema || tool.outputSchema,
3966
+ inputSchema: this.convertSchema(tool.parameters),
3967
+ outputSchema: this.convertSchema(tool.parameters),
4001
3968
  toolType: tool.mcp?.toolType
4002
3969
  }))
4003
3970
  };
@@ -4030,8 +3997,8 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
4030
3997
  return {
4031
3998
  name: tool.id || toolId,
4032
3999
  description: tool.description,
4033
- inputSchema: tool.parameters?.jsonSchema || tool.parameters,
4034
- outputSchema: tool.outputSchema?.jsonSchema || tool.outputSchema,
4000
+ inputSchema: this.convertSchema(tool.parameters),
4001
+ outputSchema: this.convertSchema(tool.outputSchema),
4035
4002
  toolType: tool.mcp?.toolType
4036
4003
  };
4037
4004
  }
@@ -4066,23 +4033,29 @@ Provided arguments: ${JSON.stringify(request.params.arguments, null, 2)}`
4066
4033
  throw new Error(`Unknown tool: ${toolId}`);
4067
4034
  }
4068
4035
  this.logger.debug(`ExecuteTool: Invoking '${toolId}' with arguments:`, args);
4069
- if (tool.parameters instanceof zod.z.ZodType && typeof tool.parameters.safeParse === "function") {
4070
- const validation = tool.parameters.safeParse(args ?? {});
4071
- if (!validation.success) {
4072
- const errorMessages = validation.error.errors.map((e) => `- ${e.path?.join(".") || "root"}: ${e.message}`).join("\n");
4036
+ const paramsSchema = tool.parameters;
4037
+ const validation = typeof paramsSchema?.validate === "function" ? paramsSchema.validate(args ?? {}) : typeof paramsSchema?.safeParse === "function" ? paramsSchema.safeParse(args ?? {}) : null;
4038
+ if (validation) {
4039
+ const success = typeof validation.success === "boolean" ? validation.success : !validation.issues?.length;
4040
+ if (!success) {
4041
+ const issues = validation.error?.issues ?? validation.error?.errors ?? validation.issues ?? [];
4042
+ const errorMessages = issues.map(
4043
+ (e) => `- ${e.path?.join(".") || "root"}: ${e.message}`
4044
+ ).join("\n");
4045
+ const validationErrors = validation.error?.format?.() ?? validation.error ?? validation.issues;
4073
4046
  this.logger.warn(`ExecuteTool: Invalid tool arguments for '${toolId}': ${errorMessages}`, {
4074
- errors: validation.error.format()
4047
+ errors: validationErrors
4075
4048
  });
4076
4049
  return {
4077
4050
  error: true,
4078
4051
  message: `Tool validation failed. Please fix the following errors and try again:
4079
- ${errorMessages}
4052
+ ${errorMessages || "Validation failed"}
4080
4053
 
4081
4054
  Provided arguments: ${JSON.stringify(args, null, 2)}`,
4082
- validationErrors: validation.error.format()
4055
+ validationErrors
4083
4056
  };
4084
4057
  }
4085
- validatedArgs = validation.data;
4058
+ validatedArgs = validation.data ?? validation.value ?? args;
4086
4059
  } else {
4087
4060
  this.logger.debug(
4088
4061
  `ExecuteTool: Tool '${toolId}' parameters is not a Zod schema with safeParse or is undefined. Skipping validation.`