@mastra/mcp 2.0.0-alpha.4 → 2.0.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.
@@ -167,6 +167,17 @@ export declare class InternalMastraMCPClient extends MastraBase {
167
167
  * @internal
168
168
  */
169
169
  connect(): Promise<boolean>;
170
+ /**
171
+ * Installs the process-exit and signal handlers that tear this client down when the
172
+ * host process goes away. Idempotent, so repeated connects add at most one of each.
173
+ */
174
+ private registerProcessHooks;
175
+ /**
176
+ * Removes whatever {@link registerProcessHooks} installed. Keyed on the handlers this
177
+ * client actually registered rather than on connection state, so a client that never
178
+ * reached a transport still releases its process listeners.
179
+ */
180
+ private unregisterProcessHooks;
170
181
  /**
171
182
  * Gets the stderr stream of the child process, if using stdio transport with `stderr: 'pipe'`.
172
183
  *
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client/client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAI/C,OAAO,KAAK,EAAmB,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAShE,OAAO,KAAK,EAEV,eAAe,EACf,iBAAiB,EACjB,mBAAmB,EACnB,2BAA2B,EAG3B,kBAAkB,EAMnB,MAAM,8BAA8B,CAAC;AAMtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAG3D,OAAO,KAAK,EAGV,eAAe,EAEf,8BAA8B,EAG9B,6BAA6B,EAC9B,MAAM,SAAS,CAAC;AAIjB,YAAY,EACV,YAAY,EACZ,UAAU,EACV,UAAU,EACV,eAAe,EACf,eAAe,EACf,yBAAyB,EACzB,qBAAqB,EACrB,wBA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AAU,EAAE,6BAA6B,CAAA;KAAE,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CA2B1G;IAEK,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,CAgB/D;IAED;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAsN9B,OAAO,CAAC,mBAAmB;CAQ5B"}
@@ -3,7 +3,7 @@ name: mastra-mcp
3
3
  description: Documentation for @mastra/mcp. Use when working with @mastra/mcp APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/mcp"
6
- version: "2.0.0-alpha.4"
6
+ version: "2.0.0"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.0.0-alpha.4",
2
+ "version": "2.0.0",
3
3
  "package": "@mastra/mcp",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -959,6 +959,14 @@ execute: async ({ items }, context) => {
959
959
  }
960
960
  ```
961
961
 
962
+ ## Tracing
963
+
964
+ When the server is registered on a `Mastra` instance that has observability configured, every request it handles produces an `MCP_SERVER_REQUEST` root span: `tools/list`, `tools/call`, `resources/*`, and `prompts/*`. `executeTool()` produces the same span, so the Studio MCP server page is traced like an MCP client.
965
+
966
+ The span is named after the method and target (for example `tools/call lookupOrder`). It stores the request params as input and the response as output, and records the server name and version, the negotiated protocol version, and the client name and version when the client reported them. A `tools/call` that returns `isError: true` fails the span. Agents and workflows exposed as tools attach their `AGENT_RUN` and `WORKFLOW_RUN` spans under it. A served tool doesn't get its own `TOOL_CALL` span. Tools an agent calls inside the request still do.
967
+
968
+ A standalone `MCPServer` with no `mastra` instance produces no spans.
969
+
962
970
  ## Notification delivery
963
971
 
964
972
  Notification methods (`resources.notifyListChanged()`, `prompts.notifyListChanged()`, `toolActions.notifyListChanged()`, and `sendLoggingMessage()`) broadcast to every connected client across all transports: the stdio/SSE connection and each streamable HTTP session. `resources.notifyUpdated()` is the exception: it only notifies clients that subscribed to the resource URI via `resources/subscribe`. Subscriptions are tracked per session for streamable HTTP clients; legacy SSE clients share the main server instance and therefore share one subscription set. Clients using the stateless serverless mode can't receive notifications because each request uses a transient server instance.
package/dist/index.cjs CHANGED
@@ -23272,21 +23272,23 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
23272
23272
  }
23273
23273
  async connectStdio(command) {
23274
23274
  this.log("debug", `Using Stdio transport for command: ${command}`);
23275
+ const transport = new _modelcontextprotocol_client_stdio.StdioClientTransport({
23276
+ command,
23277
+ args: this.serverConfig.args,
23278
+ env: this.buildStdioEnv(),
23279
+ stderr: this.serverConfig.stderr,
23280
+ cwd: this.serverConfig.cwd
23281
+ });
23275
23282
  try {
23276
- this.transport = new _modelcontextprotocol_client_stdio.StdioClientTransport({
23277
- command,
23278
- args: this.serverConfig.args,
23279
- env: this.buildStdioEnv(),
23280
- stderr: this.serverConfig.stderr,
23281
- cwd: this.serverConfig.cwd
23282
- });
23283
- await this.client.connect(this.transport, {
23283
+ await this.client.connect(transport, {
23284
23284
  timeout: this.serverConfig.timeout ?? this.timeout,
23285
23285
  prior: this.priorDiscovery
23286
23286
  });
23287
+ this.transport = transport;
23287
23288
  this.log("debug", `Successfully connected to MCP server via Stdio`);
23288
23289
  } catch (e) {
23289
23290
  this.log("error", e instanceof Error ? e.stack || e.message : JSON.stringify(e));
23291
+ await transport.close().catch(() => {});
23290
23292
  throw e;
23291
23293
  }
23292
23294
  }
@@ -23469,11 +23471,20 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
23469
23471
  this.clientConnectionOnClose = connectionOnClose;
23470
23472
  this.client.onclose = connectionOnClose;
23471
23473
  } catch (e) {
23474
+ if (!this.transport) this.unregisterProcessHooks();
23472
23475
  this.isConnected = null;
23473
23476
  this.priorDiscovery = void 0;
23474
23477
  reject(e);
23475
23478
  }
23476
23479
  });
23480
+ this.registerProcessHooks();
23481
+ return this.isConnected;
23482
+ }
23483
+ /**
23484
+ * Installs the process-exit and signal handlers that tear this client down when the
23485
+ * host process goes away. Idempotent, so repeated connects add at most one of each.
23486
+ */
23487
+ registerProcessHooks() {
23477
23488
  if (!this.exitHookUnsubscribe) this.exitHookUnsubscribe = (0, exit_hook.asyncExitHook)(async () => {
23478
23489
  this.log("debug", `Disconnecting MCP server during exit`);
23479
23490
  await this.disconnect();
@@ -23486,7 +23497,25 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
23486
23497
  this.sigHupHandler = () => (0, exit_hook.gracefulExit)();
23487
23498
  process.on("SIGHUP", this.sigHupHandler);
23488
23499
  }
23489
- return this.isConnected;
23500
+ }
23501
+ /**
23502
+ * Removes whatever {@link registerProcessHooks} installed. Keyed on the handlers this
23503
+ * client actually registered rather than on connection state, so a client that never
23504
+ * reached a transport still releases its process listeners.
23505
+ */
23506
+ unregisterProcessHooks() {
23507
+ if (this.exitHookUnsubscribe) {
23508
+ this.exitHookUnsubscribe();
23509
+ this.exitHookUnsubscribe = void 0;
23510
+ }
23511
+ if (this.sigTermHandler) {
23512
+ process.off("SIGTERM", this.sigTermHandler);
23513
+ this.sigTermHandler = void 0;
23514
+ }
23515
+ if (this.sigHupHandler) {
23516
+ process.off("SIGHUP", this.sigHupHandler);
23517
+ this.sigHupHandler = void 0;
23518
+ }
23490
23519
  }
23491
23520
  /**
23492
23521
  * Gets the stderr stream of the child process, if using stdio transport with `stderr: 'pipe'`.
@@ -23531,6 +23560,7 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
23531
23560
  this.closePendingAuthTransport();
23532
23561
  if (!this.transport) {
23533
23562
  await this.detachStaleClientTransport();
23563
+ this.unregisterProcessHooks();
23534
23564
  this.log("debug", "Disconnect called but no transport was connected.");
23535
23565
  return;
23536
23566
  }
@@ -23548,18 +23578,7 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
23548
23578
  this.transport = void 0;
23549
23579
  this.isConnected = null;
23550
23580
  this.serverInstructions = void 0;
23551
- if (this.exitHookUnsubscribe) {
23552
- this.exitHookUnsubscribe();
23553
- this.exitHookUnsubscribe = void 0;
23554
- }
23555
- if (this.sigTermHandler) {
23556
- process.off("SIGTERM", this.sigTermHandler);
23557
- this.sigTermHandler = void 0;
23558
- }
23559
- if (this.sigHupHandler) {
23560
- process.off("SIGHUP", this.sigHupHandler);
23561
- this.sigHupHandler = void 0;
23562
- }
23581
+ this.unregisterProcessHooks();
23563
23582
  }
23564
23583
  }
23565
23584
  /**
@@ -26417,6 +26436,95 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26417
26436
  this.registerPromptHandlers(server);
26418
26437
  return server;
26419
26438
  }
26439
+ /**
26440
+ * Registers `method` under an `MCP_SERVER_REQUEST` span, so every request the
26441
+ * server answers is recorded — including the list and read methods that never
26442
+ * reach a tool, and requests that fail before any work is done.
26443
+ */
26444
+ setTracedHandler(server, method, handler) {
26445
+ server.setRequestHandler(method, async (request, ctx) => {
26446
+ const params = request.params;
26447
+ let requestContext;
26448
+ try {
26449
+ requestContext = await toRequestContext(ctx, this.mapAuthInfoToUser);
26450
+ } catch (error) {
26451
+ this.startRequestSpan(method, params, {
26452
+ server,
26453
+ ctx
26454
+ })?.error({ error });
26455
+ throw error;
26456
+ }
26457
+ const requestSpan = this.startRequestSpan(method, params, {
26458
+ server,
26459
+ ctx,
26460
+ requestContext
26461
+ });
26462
+ let reportedError;
26463
+ return this.traceRequest(requestSpan, () => handler(request, ctx, {
26464
+ requestSpan,
26465
+ requestContext,
26466
+ reportError: (error) => {
26467
+ reportedError = error;
26468
+ }
26469
+ }), () => reportedError);
26470
+ });
26471
+ }
26472
+ /**
26473
+ * Opens the span for one served request. `connection` is absent for
26474
+ * {@link executeTool}, which is called in-process and negotiates nothing.
26475
+ */
26476
+ startRequestSpan(method, params, connection) {
26477
+ const envelope = connection?.ctx?.mcpReq.envelope;
26478
+ const protocolVersion = envelope?.[_modelcontextprotocol_server.PROTOCOL_VERSION_META_KEY] ?? connection?.server?.getNegotiatedProtocolVersion();
26479
+ const client = envelope?.[_modelcontextprotocol_server.CLIENT_INFO_META_KEY] ?? connection?.server?.getClientVersion();
26480
+ const target = params?.name ?? params?.uri;
26481
+ const targetName = typeof target === "string" ? target : void 0;
26482
+ return (0, _mastra_core_observability.getOrCreateSpan)({
26483
+ type: _mastra_core_observability.SpanType.MCP_SERVER_REQUEST,
26484
+ name: targetName ? `${method} ${targetName}` : method,
26485
+ entityType: _mastra_core_observability.EntityType.MCP_SERVER,
26486
+ entityId: this.id,
26487
+ entityName: this.name,
26488
+ input: params,
26489
+ attributes: {
26490
+ mcpMethod: method,
26491
+ targetName,
26492
+ mcpServer: this.name,
26493
+ serverVersion: this.version,
26494
+ mcpProtocolVersion: typeof protocolVersion === "string" ? protocolVersion : void 0,
26495
+ clientName: client?.name,
26496
+ clientVersion: client?.version
26497
+ },
26498
+ tracingContext: {},
26499
+ requestContext: connection?.requestContext,
26500
+ mastra: this.mastra
26501
+ });
26502
+ }
26503
+ /**
26504
+ * Runs `fn` under a request span. Only the protocol's own `isError` marks a
26505
+ * failure; the rest of a result is opaque handler output that may legitimately
26506
+ * carry any field. A thrown error ends the whole span tree and is rethrown.
26507
+ */
26508
+ async traceRequest(requestSpan, fn, getReportedError) {
26509
+ try {
26510
+ const result = await fn();
26511
+ const errorResult = result;
26512
+ if (errorResult?.isError) requestSpan?.error({ error: getReportedError?.() ?? new _mastra_core_error.MastraError({
26513
+ id: "MCP_SERVER_REQUEST_FAILED",
26514
+ domain: _mastra_core_error.ErrorDomain.MCP,
26515
+ category: _mastra_core_error.ErrorCategory.USER,
26516
+ text: errorResult.content?.map((c) => c.text).filter(Boolean).join("\n")
26517
+ }) });
26518
+ else requestSpan?.end({ output: result });
26519
+ return result;
26520
+ } catch (error) {
26521
+ requestSpan?.error({
26522
+ error,
26523
+ endTree: true
26524
+ });
26525
+ throw error;
26526
+ }
26527
+ }
26420
26528
  /** Answers a suspended round: one keyed form derived from the handler's `resumeSchema`. */
26421
26529
  async inputRequired(ctx, requestContext, suspension) {
26422
26530
  const payload = suspension.suspendPayload;
@@ -26441,9 +26549,8 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26441
26549
  })
26442
26550
  });
26443
26551
  }
26444
- async serverRequest(ctx, method, name, args, resumeSchema) {
26552
+ async serverRequest(ctx, requestContext, method, name, args, resumeSchema) {
26445
26553
  const argsHash = hashArguments(args);
26446
- const requestContext = await toRequestContext(ctx, this.mapAuthInfoToUser);
26447
26554
  const continuation = readContinuation(ctx, requestContext, {
26448
26555
  method,
26449
26556
  name,
@@ -26469,11 +26576,10 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26469
26576
  };
26470
26577
  }
26471
26578
  registerToolHandlers(server) {
26472
- server.setRequestHandler("tools/list", async (_request, ctx) => {
26473
- const requestContext = await toRequestContext(ctx, this.mapAuthInfoToUser);
26474
- return { tools: (await this.authorizedToolEntries(requestContext)).map(([name, tool]) => this.toMCPTool(name, tool)) };
26579
+ this.setTracedHandler(server, "tools/list", async (_request, _ctx, trace) => {
26580
+ return { tools: (await this.authorizedToolEntries(trace.requestContext)).map(([name, tool]) => this.toMCPTool(name, tool)) };
26475
26581
  });
26476
- server.setRequestHandler("tools/call", async (request, ctx) => {
26582
+ this.setTracedHandler(server, "tools/call", async (request, ctx, trace) => {
26477
26583
  const name = request.params.name;
26478
26584
  const tool = this.convertedTools[name];
26479
26585
  if (!tool) {
@@ -26482,43 +26588,25 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26482
26588
  }
26483
26589
  const args = request.params.arguments ?? {};
26484
26590
  const argsHash = hashArguments(args);
26485
- const requestContext = await toRequestContext(ctx, this.mapAuthInfoToUser);
26591
+ const requestContext = trace.requestContext;
26486
26592
  const continuation = readContinuation(ctx, requestContext, {
26487
26593
  method: "tools/call",
26488
26594
  name,
26489
26595
  argsHash
26490
26596
  });
26491
26597
  const mcp = toToolExecutionContext(ctx, this.name);
26492
- const span = (0, _mastra_core_observability.getOrCreateSpan)({
26493
- type: _mastra_core_observability.SpanType.TOOL_CALL,
26494
- name: `tool: '${name}'`,
26495
- input: args,
26496
- entityType: _mastra_core_observability.EntityType.TOOL,
26497
- entityId: name,
26498
- entityName: name,
26499
- attributes: {
26500
- toolType: "tool",
26501
- toolDescription: tool.description
26502
- },
26503
- requestContext,
26504
- mastra: this.mastra
26505
- });
26506
26598
  const startedAt = Date.now();
26507
26599
  try {
26508
26600
  await this.enforceToolExecutionFGA(name, requestContext);
26509
- if (continuation && continuation.outcome !== "accept") {
26510
- span?.end({ attributes: { success: false } });
26511
- return errorResult(`Tool '${name}' was ${continuation.outcome === "decline" ? "declined" : "cancelled"}`);
26512
- }
26601
+ if (continuation && continuation.outcome !== "accept") return errorResult(`Tool '${name}' was ${continuation.outcome === "decline" ? "declined" : "cancelled"}`);
26513
26602
  const execution = await this.runTool(name, tool, args, {
26514
26603
  requestContext,
26515
26604
  mcp,
26516
- tracingContext: { currentSpan: span },
26605
+ tracingContext: { currentSpan: trace.requestSpan },
26517
26606
  resumeData: continuation?.resumeData,
26518
26607
  suspendPayload: continuation?.suspendPayload
26519
26608
  });
26520
26609
  if (execution.status === "suspended") {
26521
- span?.end({ attributes: { success: true } });
26522
26610
  this.logger.debug(`Tool '${name}' requires client input.`);
26523
26611
  return this.inputRequired(ctx, requestContext, {
26524
26612
  method: "tools/call",
@@ -26530,17 +26618,9 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26530
26618
  });
26531
26619
  }
26532
26620
  const result = this.toCallToolResult(name, tool, execution.output);
26533
- span?.end({
26534
- output: execution.output,
26535
- attributes: { success: !result.isError }
26536
- });
26537
26621
  this.logger.info(`Tool '${name}' finished in ${Date.now() - startedAt}ms.`);
26538
26622
  return result;
26539
26623
  } catch (error) {
26540
- span?.error({
26541
- error,
26542
- attributes: { success: false }
26543
- });
26544
26624
  if (error instanceof _modelcontextprotocol_server.ProtocolError) throw error;
26545
26625
  this.logger.error("Tool execution failed", {
26546
26626
  tool: name,
@@ -26552,6 +26632,7 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26552
26632
  category: _mastra_core_error.ErrorCategory.USER,
26553
26633
  details: { toolName: name }
26554
26634
  }, error);
26635
+ trace.reportError(mastraError);
26555
26636
  return errorResult(JSON.stringify(mastraError.toJSON()));
26556
26637
  }
26557
26638
  });
@@ -26567,6 +26648,7 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26567
26648
  const output = await tool.execute(args, {
26568
26649
  toolCallId: "",
26569
26650
  messages: [],
26651
+ skipToolSpan: true,
26570
26652
  requestContext: options.requestContext,
26571
26653
  tracingContext: options.tracingContext,
26572
26654
  abortSignal: options.mcp?.extra.signal,
@@ -26620,19 +26702,19 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26620
26702
  const options = this.resourceOptions;
26621
26703
  const hasAppResources = this.appResourceList.length > 0;
26622
26704
  if (!options && !hasAppResources) return;
26623
- const listResources = async (ctx) => [...this.appResourceList, ...await options?.listResources({
26705
+ const listResources = async (ctx, requestContext) => [...this.appResourceList, ...await options?.listResources({
26624
26706
  extra: toToolExecutionContext(ctx, this.name).extra,
26625
- requestContext: await toRequestContext(ctx, this.mapAuthInfoToUser)
26707
+ requestContext
26626
26708
  }) ?? []];
26627
- server.setRequestHandler("resources/list", async (_request, ctx) => ({ resources: await listResources(ctx) }));
26628
- server.setRequestHandler("resources/read", async (request, ctx) => {
26709
+ this.setTracedHandler(server, "resources/list", async (_request, ctx, trace) => ({ resources: await listResources(ctx, trace.requestContext) }));
26710
+ this.setTracedHandler(server, "resources/read", async (request, ctx, trace) => {
26629
26711
  const uri = request.params.uri;
26630
- const resource = (await listResources(ctx)).find((r) => r.uri === uri);
26712
+ const resource = (await listResources(ctx, trace.requestContext)).find((r) => r.uri === uri);
26631
26713
  if (!resource) throw new _modelcontextprotocol_server.ProtocolError(_modelcontextprotocol_server.ProtocolErrorCode.InvalidParams, `Resource not found: ${uri}`);
26632
26714
  const html = this.appResourceHtml.get(uri);
26633
26715
  if (html !== void 0) return { contents: [this.resourceContents(resource, { text: html })] };
26634
26716
  if (!options) throw new _modelcontextprotocol_server.ProtocolError(_modelcontextprotocol_server.ProtocolErrorCode.InvalidParams, `Resource not found: ${uri}`);
26635
- const { request: serverRequest, continuation, suspended, argsHash } = await this.serverRequest(ctx, "resources/read", uri, {}, options.resumeSchema);
26717
+ const { request: serverRequest, continuation, suspended, argsHash } = await this.serverRequest(ctx, trace.requestContext, "resources/read", uri, {}, options.resumeSchema);
26636
26718
  if (continuation && continuation.outcome !== "accept") throw new _modelcontextprotocol_server.ProtocolError(_modelcontextprotocol_server.ProtocolErrorCode.InvalidParams, `Reading '${uri}' was ${continuation.outcome}ed`);
26637
26719
  const result = await options.getResourceContent({
26638
26720
  uri,
@@ -26650,9 +26732,9 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26650
26732
  if (result === void 0) throw new Error(`Resource '${uri}' returned no content`);
26651
26733
  return { contents: (Array.isArray(result) ? result : [result]).map((content) => this.resourceContents(resource, content)) };
26652
26734
  });
26653
- if (options?.resourceTemplates) server.setRequestHandler("resources/templates/list", async (_request, ctx) => ({ resourceTemplates: await options.resourceTemplates({
26735
+ if (options?.resourceTemplates) this.setTracedHandler(server, "resources/templates/list", async (_request, ctx, trace) => ({ resourceTemplates: await options.resourceTemplates({
26654
26736
  extra: toToolExecutionContext(ctx, this.name).extra,
26655
- requestContext: await toRequestContext(ctx, this.mapAuthInfoToUser)
26737
+ requestContext: trace.requestContext
26656
26738
  }) }));
26657
26739
  }
26658
26740
  resourceContents(resource, content) {
@@ -26674,22 +26756,22 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26674
26756
  registerPromptHandlers(server) {
26675
26757
  const options = this.promptOptions;
26676
26758
  if (!options) return;
26677
- const listPrompts = async (ctx) => {
26759
+ const listPrompts = async (ctx, requestContext) => {
26678
26760
  const prompts = await options.listPrompts({
26679
26761
  extra: toToolExecutionContext(ctx, this.name).extra,
26680
- requestContext: await toRequestContext(ctx, this.mapAuthInfoToUser)
26762
+ requestContext
26681
26763
  });
26682
26764
  for (const prompt of prompts) _modelcontextprotocol_core.PromptSchema.parse(prompt);
26683
26765
  return prompts;
26684
26766
  };
26685
- server.setRequestHandler("prompts/list", async (_request, ctx) => ({ prompts: await listPrompts(ctx) }));
26767
+ this.setTracedHandler(server, "prompts/list", async (_request, ctx, trace) => ({ prompts: await listPrompts(ctx, trace.requestContext) }));
26686
26768
  if (!options.getPromptMessages) return;
26687
- server.setRequestHandler("prompts/get", async (request, ctx) => {
26769
+ this.setTracedHandler(server, "prompts/get", async (request, ctx, trace) => {
26688
26770
  const { name, arguments: args } = request.params;
26689
- const prompt = (await listPrompts(ctx)).find((p) => p.name === name);
26771
+ const prompt = (await listPrompts(ctx, trace.requestContext)).find((p) => p.name === name);
26690
26772
  if (!prompt) throw new _modelcontextprotocol_server.ProtocolError(_modelcontextprotocol_server.ProtocolErrorCode.InvalidParams, `Prompt "${name}" not found`);
26691
26773
  for (const arg of prompt.arguments ?? []) if (arg.required && (args?.[arg.name] === void 0 || args?.[arg.name] === null)) throw new _modelcontextprotocol_server.ProtocolError(_modelcontextprotocol_server.ProtocolErrorCode.InvalidParams, `Missing required argument: ${arg.name}`);
26692
- const { request: serverRequest, continuation, suspended, argsHash } = await this.serverRequest(ctx, "prompts/get", name, args ?? {}, options.resumeSchema);
26774
+ const { request: serverRequest, continuation, suspended, argsHash } = await this.serverRequest(ctx, trace.requestContext, "prompts/get", name, args ?? {}, options.resumeSchema);
26693
26775
  if (continuation && continuation.outcome !== "accept") throw new _modelcontextprotocol_server.ProtocolError(_modelcontextprotocol_server.ProtocolErrorCode.InvalidParams, `Prompt "${name}" was ${continuation.outcome}ed`);
26694
26776
  const messages = await options.getPromptMessages({
26695
26777
  name,
@@ -26902,52 +26984,58 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
26902
26984
  * arguments with `resumeData` and `suspendPayload`.
26903
26985
  */
26904
26986
  async executeTool(toolId, args, executionContext = {}) {
26905
- const tool = this.convertedTools[toolId];
26906
- if (!tool) {
26907
- this.logger.warn("Unknown tool requested", {
26908
- tool: toolId,
26909
- server: this.name
26910
- });
26911
- throw new _mastra_core_error.MastraError({
26912
- id: "MCP_SERVER_TOOL_EXECUTE_PREPARATION_FAILED",
26913
- domain: _mastra_core_error.ErrorDomain.MCP,
26914
- category: _mastra_core_error.ErrorCategory.USER,
26915
- text: `Unknown tool: ${toolId}`,
26916
- details: { toolId }
26917
- });
26918
- }
26919
26987
  const requestContext = executionContext.requestContext ?? new _mastra_core_request_context.RequestContext();
26920
- await this.enforceToolExecutionFGA(toolId, requestContext);
26921
- try {
26922
- const execution = await this.runTool(toolId, tool, args, {
26923
- requestContext,
26924
- tracingContext: { currentSpan: void 0 },
26925
- resumeData: executionContext.resumeData,
26926
- suspendPayload: executionContext.suspendPayload
26927
- });
26928
- if (execution.status === "completed" && (0, _mastra_core_tools.isValidationError)(execution.output)) throw new _mastra_core_error.MastraError({
26929
- id: "MCP_SERVER_TOOL_INVALID_INPUT",
26930
- domain: _mastra_core_error.ErrorDomain.MCP,
26931
- category: _mastra_core_error.ErrorCategory.USER,
26932
- text: execution.output.message,
26933
- details: { toolId }
26934
- });
26935
- this.logger.info("Tool executed successfully", { tool: toolId });
26936
- return execution;
26937
- } catch (error) {
26938
- if (error instanceof _mastra_core_error.MastraError && error.id === "MCP_SERVER_TOOL_INVALID_INPUT") throw error;
26939
- const mastraError = new _mastra_core_error.MastraError({
26940
- id: "MCP_SERVER_TOOL_EXECUTE_FAILED",
26941
- domain: _mastra_core_error.ErrorDomain.MCP,
26942
- category: _mastra_core_error.ErrorCategory.USER,
26943
- details: {
26944
- toolId,
26945
- args: JSON.stringify(args)
26946
- }
26947
- }, error);
26948
- this.logger.trackException(mastraError);
26949
- throw mastraError;
26950
- }
26988
+ const requestSpan = this.startRequestSpan("tools/call", {
26989
+ name: toolId,
26990
+ arguments: args
26991
+ }, { requestContext });
26992
+ return this.traceRequest(requestSpan, async () => {
26993
+ const tool = this.convertedTools[toolId];
26994
+ if (!tool) {
26995
+ this.logger.warn("Unknown tool requested", {
26996
+ tool: toolId,
26997
+ server: this.name
26998
+ });
26999
+ throw new _mastra_core_error.MastraError({
27000
+ id: "MCP_SERVER_TOOL_EXECUTE_PREPARATION_FAILED",
27001
+ domain: _mastra_core_error.ErrorDomain.MCP,
27002
+ category: _mastra_core_error.ErrorCategory.USER,
27003
+ text: `Unknown tool: ${toolId}`,
27004
+ details: { toolId }
27005
+ });
27006
+ }
27007
+ await this.enforceToolExecutionFGA(toolId, requestContext);
27008
+ try {
27009
+ const execution = await this.runTool(toolId, tool, args, {
27010
+ requestContext,
27011
+ tracingContext: { currentSpan: requestSpan },
27012
+ resumeData: executionContext.resumeData,
27013
+ suspendPayload: executionContext.suspendPayload
27014
+ });
27015
+ if (execution.status === "completed" && (0, _mastra_core_tools.isValidationError)(execution.output)) throw new _mastra_core_error.MastraError({
27016
+ id: "MCP_SERVER_TOOL_INVALID_INPUT",
27017
+ domain: _mastra_core_error.ErrorDomain.MCP,
27018
+ category: _mastra_core_error.ErrorCategory.USER,
27019
+ text: execution.output.message,
27020
+ details: { toolId }
27021
+ });
27022
+ this.logger.info("Tool executed successfully", { tool: toolId });
27023
+ return execution;
27024
+ } catch (error) {
27025
+ if (error instanceof _mastra_core_error.MastraError && error.id === "MCP_SERVER_TOOL_INVALID_INPUT") throw error;
27026
+ const mastraError = new _mastra_core_error.MastraError({
27027
+ id: "MCP_SERVER_TOOL_EXECUTE_FAILED",
27028
+ domain: _mastra_core_error.ErrorDomain.MCP,
27029
+ category: _mastra_core_error.ErrorCategory.USER,
27030
+ details: {
27031
+ toolId,
27032
+ args: JSON.stringify(args)
27033
+ }
27034
+ }, error);
27035
+ this.logger.trackException(mastraError);
27036
+ throw mastraError;
27037
+ }
27038
+ });
26951
27039
  }
26952
27040
  /** Reads an `ui://` app resource; application resources require a protocol request. */
26953
27041
  async readResource(uri) {