@dexto/core 1.13.5 → 1.14.1

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 (36) hide show
  1. package/dist/agent/DextoAgent.cjs +32 -0
  2. package/dist/agent/DextoAgent.d.ts +5 -1
  3. package/dist/agent/DextoAgent.d.ts.map +1 -1
  4. package/dist/agent/DextoAgent.js +32 -0
  5. package/dist/approval/index.d.ts +1 -1
  6. package/dist/approval/index.d.ts.map +1 -1
  7. package/dist/approval/manager.cjs +7 -0
  8. package/dist/approval/manager.d.ts +1 -0
  9. package/dist/approval/manager.d.ts.map +1 -1
  10. package/dist/approval/manager.js +7 -0
  11. package/dist/approval/types.d.ts +4 -0
  12. package/dist/approval/types.d.ts.map +1 -1
  13. package/dist/mcp/index.d.ts +1 -1
  14. package/dist/mcp/index.d.ts.map +1 -1
  15. package/dist/mcp/manager.cjs +224 -73
  16. package/dist/mcp/manager.d.ts +27 -3
  17. package/dist/mcp/manager.d.ts.map +1 -1
  18. package/dist/mcp/manager.js +224 -73
  19. package/dist/mcp/mcp-client.cjs +61 -65
  20. package/dist/mcp/mcp-client.d.ts +1 -1
  21. package/dist/mcp/mcp-client.d.ts.map +1 -1
  22. package/dist/mcp/mcp-client.js +61 -65
  23. package/dist/mcp/types.d.ts +19 -2
  24. package/dist/mcp/types.d.ts.map +1 -1
  25. package/dist/tools/approval/session-tool-policy.cjs +11 -0
  26. package/dist/tools/approval/session-tool-policy.d.ts +1 -0
  27. package/dist/tools/approval/session-tool-policy.d.ts.map +1 -1
  28. package/dist/tools/approval/session-tool-policy.js +11 -0
  29. package/dist/tools/tool-manager.cjs +14 -0
  30. package/dist/tools/tool-manager.d.ts +2 -0
  31. package/dist/tools/tool-manager.d.ts.map +1 -1
  32. package/dist/tools/tool-manager.js +14 -0
  33. package/dist/utils/redactor.cjs +39 -10
  34. package/dist/utils/redactor.d.ts.map +1 -1
  35. package/dist/utils/redactor.js +39 -10
  36. package/package.json +3 -3
@@ -1,7 +1,9 @@
1
1
  import "../chunk-C6A6W6XS.js";
2
2
  import { DextoMcpClient } from "./mcp-client.js";
3
3
  import { DextoLogComponent } from "../logger/v2/types.js";
4
+ import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
4
5
  import { MCPError } from "./errors.js";
6
+ import { MCPErrorCode } from "./error-codes.js";
5
7
  import { eventBus } from "../events/index.js";
6
8
  import { toolSchemaFingerprint } from "../tools/schema-fingerprint.js";
7
9
  import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker";
@@ -10,6 +12,10 @@ function isJsonSchemaObject(value) {
10
12
  }
11
13
  class MCPManager {
12
14
  clients = /* @__PURE__ */ new Map();
15
+ retiredClients = /* @__PURE__ */ new Map();
16
+ desiredConfigurations = /* @__PURE__ */ new Map();
17
+ connectingOperations = /* @__PURE__ */ new Map();
18
+ pendingConnectionOperations = /* @__PURE__ */ new Set();
13
19
  connectionErrors = {};
14
20
  configCache = /* @__PURE__ */ new Map();
15
21
  // Store original configs for restart
@@ -104,6 +110,9 @@ class MCPManager {
104
110
  if (existingServerWithSameSanitizedName && existingServerWithSameSanitizedName !== name) {
105
111
  throw MCPError.duplicateName(name, existingServerWithSameSanitizedName);
106
112
  }
113
+ const previousClient = this.clients.get(name);
114
+ if (previousClient && previousClient !== client)
115
+ this.retiredClients.set(previousClient, name);
107
116
  this.clients.set(name, client);
108
117
  this.sanitizedNameToServerMap.set(sanitizedName, name);
109
118
  this.setupClientNotifications(name, client);
@@ -259,10 +268,10 @@ class MCPManager {
259
268
  this.logger.debug(
260
269
  `\u2705 Successfully cached ${Object.keys(tools).length} tools for client: ${clientName}`
261
270
  );
262
- } catch (error) {
263
- this.logger.error(
264
- `\u274C Error retrieving tools for client ${clientName}: ${error instanceof Error ? error.message : String(error)}`
265
- );
271
+ } catch {
272
+ this.logger.error(`\u274C Error retrieving tools for client ${clientName}`, {
273
+ code: MCPErrorCode.PROTOCOL_ERROR
274
+ });
266
275
  return;
267
276
  }
268
277
  try {
@@ -281,8 +290,10 @@ class MCPManager {
281
290
  });
282
291
  }
283
292
  this.logger.debug(`Cached ${prompts.length} prompts for client: ${clientName}`);
284
- } catch (error) {
285
- this.logger.debug(`Skipping prompts for client ${clientName}: ${error}`);
293
+ } catch {
294
+ this.logger.debug(`Skipping prompts for client ${clientName}`, {
295
+ code: MCPErrorCode.PROTOCOL_ERROR
296
+ });
286
297
  }
287
298
  try {
288
299
  this.removeServerResources(clientName);
@@ -296,8 +307,10 @@ class MCPManager {
296
307
  });
297
308
  });
298
309
  this.logger.debug(`Cached resources for client: ${clientName}`);
299
- } catch (error) {
300
- this.logger.debug(`Skipping resources for client ${clientName}: ${error}`);
310
+ } catch {
311
+ this.logger.debug(`Skipping resources for client ${clientName}`, {
312
+ code: MCPErrorCode.PROTOCOL_ERROR
313
+ });
301
314
  }
302
315
  }
303
316
  /**
@@ -331,7 +344,6 @@ class MCPManager {
331
344
  this.logger.debug(` - ${toolName}`);
332
345
  }
333
346
  });
334
- this.logger.silly(`MCP tools: ${JSON.stringify(allTools, null, 2)}`);
335
347
  return allTools;
336
348
  }
337
349
  /**
@@ -434,6 +446,26 @@ class MCPManager {
434
446
  getToolClient(toolName) {
435
447
  return this.toolCache.get(toolName)?.client;
436
448
  }
449
+ /** Call a literal upstream identity and retain its complete MCP protocol result. */
450
+ async callToolDirect(request) {
451
+ const { connectionId, toolName } = request.identity;
452
+ if (this.connectingOperations.has(connectionId)) {
453
+ throw MCPError.clientNotConnected("connection operation in progress");
454
+ }
455
+ const client = this.clients.get(connectionId);
456
+ if (!client) throw MCPError.serverNotFound(connectionId);
457
+ const timeout = this.configCache.get(connectionId)?.timeout;
458
+ const connected = await client.getConnectedClient();
459
+ const result = await connected.callTool(
460
+ { name: toolName, arguments: request.arguments },
461
+ CallToolResultSchema,
462
+ {
463
+ ...timeout !== void 0 ? { timeout } : {},
464
+ ...request.signal !== void 0 ? { signal: request.signal } : {}
465
+ }
466
+ );
467
+ return CallToolResultSchema.parse(result);
468
+ }
437
469
  /**
438
470
  * Execute a specific MCP tool with the given arguments.
439
471
  * @param toolName Name of the MCP tool to execute (may include server prefix)
@@ -558,6 +590,63 @@ class MCPManager {
558
590
  }
559
591
  return await entry.client.readResource(entry.summary.uri);
560
592
  }
593
+ /** Register desired configuration without connecting or changing legacy restart configuration. */
594
+ configureServer(name, config) {
595
+ if (name === "__proto__")
596
+ throw MCPError.connectionFailed(
597
+ name,
598
+ "Server name is reserved by legacy error storage"
599
+ );
600
+ this.assertConfigurationMutable(name);
601
+ this.desiredConfigurations.set(name, structuredClone(config));
602
+ }
603
+ /** Forget an explicit desired registration; disconnecting alone retains it. */
604
+ forgetServerConfiguration(name) {
605
+ this.assertConfigurationMutable(name);
606
+ this.desiredConfigurations.delete(name);
607
+ }
608
+ /** Connect an explicitly registered, enabled configuration using the existing engine. */
609
+ async connectConfiguredServer(name) {
610
+ const config = this.desiredConfigurations.get(name);
611
+ if (config === void 0)
612
+ throw MCPError.serverNotFound(name, "Desired configuration not found");
613
+ if (!config.enabled) throw MCPError.connectionFailed(name, "Configured server is disabled");
614
+ this.assertConfigurationMutable(name);
615
+ await this.connectServer(name, structuredClone(config));
616
+ }
617
+ /** List only explicitly registered desired configurations, never raw configs or diagnostics. */
618
+ getConfiguredServerStatuses() {
619
+ return Array.from(
620
+ this.desiredConfigurations,
621
+ ([name, config]) => {
622
+ const metadata = { name, configuredTransport: config.type };
623
+ if (this.connectingOperations.has(name))
624
+ return { ...metadata, status: "connecting" };
625
+ if (this.clients.has(name)) return { ...metadata, status: "connected" };
626
+ if (!config.enabled) return { ...metadata, status: "disabled" };
627
+ const error = Object.hasOwn(this.connectionErrors, name) ? this.connectionErrors[name] : void 0;
628
+ if (error !== void 0) {
629
+ const errorCode = Object.values(MCPErrorCode).find((code) => code === error.code) ?? MCPErrorCode.CONNECTION_FAILED;
630
+ return { ...metadata, status: "failed", errorCode };
631
+ }
632
+ return { ...metadata, status: "configured" };
633
+ }
634
+ );
635
+ }
636
+ assertConfigurationMutable(name) {
637
+ if (this.clients.has(name) || this.connectingOperations.has(name)) {
638
+ throw MCPError.connectionFailed(
639
+ name,
640
+ "Server has an active connection operation or registered client"
641
+ );
642
+ }
643
+ }
644
+ finishConnectionAttempt(name) {
645
+ const count = this.connectingOperations.get(name);
646
+ if (count === void 0) throw MCPError.protocolError("Missing MCP connection operation");
647
+ if (count === 1) this.connectingOperations.delete(name);
648
+ else this.connectingOperations.set(name, count - 1);
649
+ }
561
650
  /**
562
651
  * Initialize clients from server configurations
563
652
  * @param serverConfigs Server configurations with individual connection modes
@@ -595,7 +684,8 @@ class MCPManager {
595
684
  };
596
685
  }
597
686
  this.logger.debug(
598
- `Handled connection error for '${name}' during initialization: ${error instanceof Error ? error.message : String(error)}`
687
+ `Handled connection error for '${name}' during initialization`,
688
+ { code: MCPErrorCode.CONNECTION_FAILED }
599
689
  );
600
690
  });
601
691
  connectionPromises.push(connectPromise);
@@ -618,13 +708,25 @@ class MCPManager {
618
708
  * @returns Promise resolving when the connection attempt is complete.
619
709
  * @throws Error if the connection fails.
620
710
  */
621
- async connectServer(name, config) {
711
+ connectServer(name, config) {
712
+ return this.trackConnectionOperation(this.connectServerAndCache(name, config));
713
+ }
714
+ async trackConnectionOperation(operation) {
715
+ this.pendingConnectionOperations.add(operation);
716
+ try {
717
+ await operation;
718
+ } finally {
719
+ this.pendingConnectionOperations.delete(operation);
720
+ }
721
+ }
722
+ async connectServerAndCache(name, config) {
622
723
  if (this.clients.has(name)) {
623
724
  this.logger.warn(`Client '${name}' is already connected or registered.`);
624
725
  return;
625
726
  }
626
727
  const client = new DextoMcpClient(this.logger);
627
728
  client.setAuthProviderFactory(this.authProviderFactory);
729
+ this.connectingOperations.set(name, (this.connectingOperations.get(name) ?? 0) + 1);
628
730
  try {
629
731
  this.logger.info(`Attempting to connect to new server '${name}'...`);
630
732
  await client.connect(config, name);
@@ -642,9 +744,24 @@ class MCPManager {
642
744
  message: errorMsg,
643
745
  ...errorCode ? { code: errorCode } : {}
644
746
  };
645
- this.logger.error(`Failed to connect to new server '${name}': ${errorMsg}`);
646
- this.clients.delete(name);
747
+ this.logger.error(`Failed to connect to new server '${name}'`, {
748
+ code: MCPErrorCode.CONNECTION_FAILED
749
+ });
750
+ await this.discardFailedClient(name, client);
647
751
  throw MCPError.connectionFailed(name, errorMsg);
752
+ } finally {
753
+ this.finishConnectionAttempt(name);
754
+ }
755
+ }
756
+ async discardFailedClient(name, client) {
757
+ if (this.clients.get(name) === client) {
758
+ this.clearClientCache(name);
759
+ this.clients.delete(name);
760
+ }
761
+ try {
762
+ await client.disconnect();
763
+ } catch {
764
+ this.logger.warn(`Failed to disconnect rejected MCP client '${name}'`);
648
765
  }
649
766
  }
650
767
  /**
@@ -703,10 +820,10 @@ class MCPManager {
703
820
  try {
704
821
  await client.disconnect();
705
822
  this.logger.info(`Successfully disconnected client: ${name}`);
706
- } catch (error) {
707
- this.logger.error(
708
- `Error disconnecting client '${name}': ${error instanceof Error ? error.message : String(error)}`
709
- );
823
+ } catch {
824
+ this.logger.error(`Error disconnecting client '${name}'`, {
825
+ code: MCPErrorCode.DISCONNECTION_FAILED
826
+ });
710
827
  }
711
828
  this.clearClientCache(name);
712
829
  this.clients.delete(name);
@@ -723,7 +840,10 @@ class MCPManager {
723
840
  * @param name The name of the server to restart.
724
841
  * @throws Error if server doesn't exist or config is not cached.
725
842
  */
726
- async restartServer(name) {
843
+ restartServer(name) {
844
+ return this.trackConnectionOperation(this.restartServerAndCache(name));
845
+ }
846
+ async restartServerAndCache(name) {
727
847
  const config = this.configCache.get(name);
728
848
  if (!config) {
729
849
  throw MCPError.serverNotFound(
@@ -731,61 +851,80 @@ class MCPManager {
731
851
  "Server config not found - cannot restart dynamically added servers without stored config"
732
852
  );
733
853
  }
734
- const client = this.clients.get(name);
735
- this.logger.info(`Restarting MCP server '${name}'...`);
736
- if (client) {
737
- try {
738
- await client.disconnect();
739
- this.logger.info(`Disconnected server '${name}' for restart`);
740
- } catch (error) {
741
- this.logger.warn(
742
- `Error disconnecting server '${name}' during restart (continuing): ${error instanceof Error ? error.message : String(error)}`
854
+ this.connectingOperations.set(name, (this.connectingOperations.get(name) ?? 0) + 1);
855
+ try {
856
+ const client = this.clients.get(name);
857
+ this.logger.info(`Restarting MCP server '${name}'...`);
858
+ if (client) {
859
+ try {
860
+ await client.disconnect();
861
+ this.logger.info(`Disconnected server '${name}' for restart`);
862
+ } catch {
863
+ this.logger.warn(
864
+ `Error disconnecting server '${name}' during restart (continuing)`,
865
+ { code: MCPErrorCode.DISCONNECTION_FAILED }
866
+ );
867
+ }
868
+ } else {
869
+ this.logger.info(
870
+ `No active client found for '${name}' during restart; attempting fresh connection`
743
871
  );
744
872
  }
745
- } else {
746
- this.logger.info(
747
- `No active client found for '${name}' during restart; attempting fresh connection`
748
- );
749
- }
750
- this.clearClientCache(name);
751
- this.clients.delete(name);
752
- delete this.connectionErrors[name];
753
- try {
873
+ this.clearClientCache(name);
874
+ this.clients.delete(name);
875
+ delete this.connectionErrors[name];
754
876
  const newClient = new DextoMcpClient(this.logger);
755
877
  newClient.setAuthProviderFactory(this.authProviderFactory);
756
- await newClient.connect(config, name);
757
- if (this.approvalManager) {
758
- newClient.setApprovalManager(this.approvalManager);
878
+ try {
879
+ await newClient.connect(config, name);
880
+ if (this.approvalManager) {
881
+ newClient.setApprovalManager(this.approvalManager);
882
+ }
883
+ this.registerClient(name, newClient);
884
+ await this.updateClientCache(name, newClient);
885
+ this.logger.info(`Successfully restarted server '${name}'`);
886
+ this.eventBus.emit("mcp:server-restarted", { serverName: name });
887
+ } catch (error) {
888
+ const errorMsg = error instanceof Error ? error.message : String(error);
889
+ const errorCode = error && typeof error === "object" && "code" in error ? String(error.code) : void 0;
890
+ this.connectionErrors[name] = {
891
+ message: errorMsg,
892
+ ...errorCode ? { code: errorCode } : {}
893
+ };
894
+ this.logger.error(`Failed to restart server '${name}'`, {
895
+ code: MCPErrorCode.CONNECTION_FAILED
896
+ });
897
+ await this.discardFailedClient(name, newClient);
898
+ throw MCPError.connectionFailed(name, errorMsg);
759
899
  }
760
- this.registerClient(name, newClient);
761
- await this.updateClientCache(name, newClient);
762
- this.logger.info(`Successfully restarted server '${name}'`);
763
- this.eventBus.emit("mcp:server-restarted", { serverName: name });
764
- } catch (error) {
765
- const errorMsg = error instanceof Error ? error.message : String(error);
766
- const errorCode = error && typeof error === "object" && "code" in error ? String(error.code) : void 0;
767
- this.connectionErrors[name] = {
768
- message: errorMsg,
769
- ...errorCode ? { code: errorCode } : {}
770
- };
771
- this.logger.error(`Failed to restart server '${name}': ${errorMsg}`);
772
- throw MCPError.connectionFailed(name, errorMsg);
900
+ } finally {
901
+ this.finishConnectionAttempt(name);
773
902
  }
774
903
  }
775
904
  /**
776
- * Disconnect all clients and clear caches
905
+ * Drain already-started connection/restart operations, including discovery, then
906
+ * disconnect registered clients and clear caches. Desired registrations remain reusable.
907
+ * Callers must stop starting new connection/restart operations before teardown.
908
+ * Draining waits for existing protocol/authentication completion; it does not cancel
909
+ * startup or introduce an additional deadline.
777
910
  */
778
911
  async disconnectAll() {
912
+ await Promise.allSettled([...this.pendingConnectionOperations]);
779
913
  const disconnectPromises = [];
780
- for (const [name, client] of Array.from(this.clients.entries())) {
914
+ const ownedClients = new Map(this.retiredClients);
915
+ for (const [name, client] of this.clients) ownedClients.set(client, name);
916
+ for (const [client, name] of ownedClients) {
781
917
  disconnectPromises.push(
782
918
  client.disconnect().then(() => this.logger.info(`Disconnected client: ${name}`)).catch(
783
- (error) => this.logger.error(`Failed to disconnect client '${name}': ${error}`)
919
+ () => this.logger.error(`Failed to disconnect client '${name}'`, {
920
+ code: MCPErrorCode.DISCONNECTION_FAILED
921
+ })
784
922
  )
785
923
  );
786
924
  }
787
925
  await Promise.all(disconnectPromises);
788
926
  this.clients.clear();
927
+ this.retiredClients.clear();
789
928
  this.connectionErrors = {};
790
929
  this.configCache.clear();
791
930
  this.toolCache.clear();
@@ -802,9 +941,7 @@ class MCPManager {
802
941
  setupClientNotifications(clientName, client) {
803
942
  try {
804
943
  client.on("resourceUpdated", async (params) => {
805
- this.logger.debug(
806
- `Received resource update notification from ${clientName}: ${params.uri}`
807
- );
944
+ this.logger.debug(`Received resource update notification from ${clientName}`);
808
945
  await this.handleResourceUpdated(clientName, params);
809
946
  });
810
947
  client.on("promptsListChanged", async () => {
@@ -816,8 +953,10 @@ class MCPManager {
816
953
  await this.handleToolsListChanged(clientName, client);
817
954
  });
818
955
  this.logger.debug(`Set up notification listeners for client: ${clientName}`);
819
- } catch (error) {
820
- this.logger.warn(`Failed to set up notification listeners for ${clientName}: ${error}`);
956
+ } catch {
957
+ this.logger.warn(`Failed to set up notification listeners for ${clientName}`, {
958
+ code: MCPErrorCode.PROTOCOL_ERROR
959
+ });
821
960
  }
822
961
  }
823
962
  /**
@@ -837,18 +976,22 @@ class MCPManager {
837
976
  client,
838
977
  summary: updatedResource
839
978
  });
840
- this.logger.debug(`Updated resource cache for: ${params.uri}`);
979
+ this.logger.debug(`Updated resource cache for server: ${serverName}`);
841
980
  }
842
- } catch (error) {
843
- this.logger.warn(`Failed to refresh resource ${params.uri}: ${error}`);
981
+ } catch {
982
+ this.logger.warn(`Failed to refresh resource for server ${serverName}`, {
983
+ code: MCPErrorCode.PROTOCOL_ERROR
984
+ });
844
985
  }
845
986
  }
846
987
  this.eventBus.emit("mcp:resource-updated", {
847
988
  serverName,
848
989
  resourceUri: params.uri
849
990
  });
850
- } catch (error) {
851
- this.logger.error(`Error handling resource update: ${error}`);
991
+ } catch {
992
+ this.logger.error("Error handling resource update", {
993
+ code: MCPErrorCode.PROTOCOL_ERROR
994
+ });
852
995
  }
853
996
  }
854
997
  /**
@@ -883,11 +1026,15 @@ class MCPManager {
883
1026
  serverName,
884
1027
  prompts: promptNames
885
1028
  });
886
- } catch (error) {
887
- this.logger.warn(`Failed to refresh prompts for ${serverName}: ${error}`);
1029
+ } catch {
1030
+ this.logger.warn(`Failed to refresh prompts for ${serverName}`, {
1031
+ code: MCPErrorCode.PROTOCOL_ERROR
1032
+ });
888
1033
  }
889
- } catch (error) {
890
- this.logger.error(`Error handling prompts list change: ${error}`);
1034
+ } catch {
1035
+ this.logger.error("Error handling prompts list change", {
1036
+ code: MCPErrorCode.PROTOCOL_ERROR
1037
+ });
891
1038
  }
892
1039
  }
893
1040
  /**
@@ -985,11 +1132,15 @@ class MCPManager {
985
1132
  serverName,
986
1133
  tools: toolNames
987
1134
  });
988
- } catch (error) {
989
- this.logger.warn(`Failed to refresh tools for ${serverName}: ${error}`);
1135
+ } catch {
1136
+ this.logger.warn(`Failed to refresh tools for ${serverName}`, {
1137
+ code: MCPErrorCode.PROTOCOL_ERROR
1138
+ });
990
1139
  }
991
- } catch (error) {
992
- this.logger.error(`Error handling tools list change: ${error}`);
1140
+ } catch {
1141
+ this.logger.error("Error handling tools list change", {
1142
+ code: MCPErrorCode.PROTOCOL_ERROR
1143
+ });
993
1144
  }
994
1145
  }
995
1146
  }