@ai-sdk/mcp 2.0.58 → 2.0.61

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
@@ -520,17 +520,25 @@ var MCPClientOAuthError = class extends (_b2 = AISDKError2, _a2 = symbol2, _b2)
520
520
  }
521
521
  };
522
522
  var ServerError = class extends MCPClientOAuthError {
523
+ static {
524
+ this.errorCode = "server_error";
525
+ }
523
526
  };
524
- ServerError.errorCode = "server_error";
525
527
  var InvalidClientError = class extends MCPClientOAuthError {
528
+ static {
529
+ this.errorCode = "invalid_client";
530
+ }
526
531
  };
527
- InvalidClientError.errorCode = "invalid_client";
528
532
  var InvalidGrantError = class extends MCPClientOAuthError {
533
+ static {
534
+ this.errorCode = "invalid_grant";
535
+ }
529
536
  };
530
- InvalidGrantError.errorCode = "invalid_grant";
531
537
  var UnauthorizedClientError = class extends MCPClientOAuthError {
538
+ static {
539
+ this.errorCode = "unauthorized_client";
540
+ }
532
541
  };
533
- UnauthorizedClientError.errorCode = "unauthorized_client";
534
542
  var OAUTH_ERRORS = {
535
543
  [ServerError.errorCode]: ServerError,
536
544
  [InvalidClientError.errorCode]: InvalidClientError,
@@ -571,7 +579,7 @@ function checkResourceAllowed({
571
579
  // src/tool/oauth.ts
572
580
  import {
573
581
  fetchWithValidatedEndpoint,
574
- fetchWithValidatedRedirects,
582
+ fetchUntrustedUrl,
575
583
  parseJSON as parseJSON2,
576
584
  validateDownloadUrl
577
585
  } from "@ai-sdk/provider-utils";
@@ -616,12 +624,11 @@ function validateAuthorizationResponseIssuer({
616
624
  }
617
625
  }
618
626
  function createAuthorizationServerInformation(authorizationServerUrl, metadata) {
619
- var _a3;
620
627
  return {
621
- issuer: (_a3 = metadata == null ? void 0 : metadata.issuer) != null ? _a3 : String(authorizationServerUrl),
628
+ issuer: metadata?.issuer ?? String(authorizationServerUrl),
622
629
  authorizationServerUrl: normalizeUrl(authorizationServerUrl),
623
630
  tokenEndpoint: normalizeUrl(
624
- (metadata == null ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl)
631
+ metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl)
625
632
  )
626
633
  };
627
634
  }
@@ -642,7 +649,7 @@ function addAuthorizationServerInformationToClientInformation(clientInformation,
642
649
  };
643
650
  }
644
651
  function getAuthorizationServerInformationFromCredentials(credentials) {
645
- if (!(credentials == null ? void 0 : credentials.authorization_server) || !credentials.token_endpoint) {
652
+ if (!credentials?.authorization_server || !credentials.token_endpoint) {
646
653
  return void 0;
647
654
  }
648
655
  return {
@@ -656,12 +663,11 @@ async function getStoredAuthorizationServerInformation({
656
663
  clientInformation,
657
664
  tokens
658
665
  }) {
659
- var _a3;
660
666
  const tokenAuthorizationServerInformation = getAuthorizationServerInformationFromCredentials(tokens);
661
667
  if (tokenAuthorizationServerInformation) {
662
668
  return tokenAuthorizationServerInformation;
663
669
  }
664
- const providerAuthorizationServerInformation = await ((_a3 = provider.authorizationServerInformation) == null ? void 0 : _a3.call(provider));
670
+ const providerAuthorizationServerInformation = await provider.authorizationServerInformation?.();
665
671
  if (providerAuthorizationServerInformation) {
666
672
  return {
667
673
  issuer: providerAuthorizationServerInformation.issuer,
@@ -719,8 +725,7 @@ function assertAuthorizationServerInformationMatches({
719
725
  }
720
726
  }
721
727
  function extractWWWAuthenticateParams(response) {
722
- var _a3, _b3;
723
- const header = (_a3 = response.headers.get("www-authenticate")) != null ? _a3 : response.headers.get("WWW-Authenticate");
728
+ const header = response.headers.get("www-authenticate") ?? response.headers.get("WWW-Authenticate");
724
729
  if (!header) {
725
730
  return {};
726
731
  }
@@ -731,11 +736,11 @@ function extractWWWAuthenticateParams(response) {
731
736
  const resourceMetadataMatch = header.match(
732
737
  /(?:^|[,\s])resource_metadata="([^"]*)"/i
733
738
  );
734
- const scope = (_b3 = header.match(/(?:^|[,\s])scope="([^"]*)"/i)) == null ? void 0 : _b3[1];
739
+ const scope = header.match(/(?:^|[,\s])scope="([^"]*)"/i)?.[1];
735
740
  let resourceMetadataUrl;
736
741
  try {
737
742
  resourceMetadataUrl = resourceMetadataMatch ? new URL(resourceMetadataMatch[1]) : void 0;
738
- } catch (e) {
743
+ } catch {
739
744
  }
740
745
  return { resourceMetadataUrl, scope };
741
746
  }
@@ -744,11 +749,10 @@ function selectScope({
744
749
  resourceMetadata,
745
750
  clientMetadata
746
751
  }) {
747
- var _a3;
748
752
  if (scope) {
749
753
  return scope;
750
754
  }
751
- const resourceScopes = (_a3 = resourceMetadata == null ? void 0 : resourceMetadata.scopes_supported) == null ? void 0 : _a3.join(" ");
755
+ const resourceScopes = resourceMetadata?.scopes_supported?.join(" ");
752
756
  if (resourceScopes) {
753
757
  return resourceScopes;
754
758
  }
@@ -762,20 +766,21 @@ function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
762
766
  }
763
767
  async function fetchWithCorsRetry(url, headers, fetchFn = fetch, trustedOrigin) {
764
768
  try {
765
- return await fetchWithValidatedRedirects({
769
+ return await fetchUntrustedUrl({
766
770
  url: url.href,
767
771
  fetch: async (input, init) => fetchWithValidatedEndpoint({
768
772
  url: input,
769
773
  init: {
770
774
  ...init,
771
- headers: new Headers(init == null ? void 0 : init.headers).has("MCP-Protocol-Version") ? headers : void 0
775
+ headers: new Headers(init?.headers).has("MCP-Protocol-Version") ? headers : void 0
772
776
  },
773
777
  fetch: fetchFn,
774
778
  trustedOrigin,
775
779
  redirect: "manual"
776
780
  }),
777
781
  headers,
778
- trustedOrigin
782
+ trustedOrigin,
783
+ untrustedFirstHopHeaders: ["mcp-protocol-version"]
779
784
  });
780
785
  } catch (error) {
781
786
  if (error instanceof TypeError) {
@@ -798,30 +803,29 @@ function shouldAttemptFallback(response, pathname) {
798
803
  return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
799
804
  }
800
805
  async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
801
- var _a3, _b3;
802
806
  const issuer = new URL(serverUrl);
803
- const protocolVersion = (_a3 = opts == null ? void 0 : opts.protocolVersion) != null ? _a3 : LATEST_PROTOCOL_VERSION;
807
+ const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;
804
808
  let url;
805
- if (opts == null ? void 0 : opts.metadataUrl) {
809
+ if (opts?.metadataUrl) {
806
810
  url = new URL(opts.metadataUrl);
807
811
  } else {
808
812
  const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
809
- url = new URL(wellKnownPath, (_b3 = opts == null ? void 0 : opts.metadataServerUrl) != null ? _b3 : issuer);
813
+ url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
810
814
  url.search = issuer.search;
811
815
  }
812
816
  let response = await tryMetadataDiscovery(
813
817
  url,
814
818
  protocolVersion,
815
819
  fetchFn,
816
- opts == null ? void 0 : opts.trustedOrigin
820
+ opts?.trustedOrigin
817
821
  );
818
- if (!(opts == null ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) {
822
+ if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
819
823
  const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
820
824
  response = await tryMetadataDiscovery(
821
825
  rootUrl,
822
826
  protocolVersion,
823
827
  fetchFn,
824
- opts == null ? void 0 : opts.trustedOrigin
828
+ opts?.trustedOrigin
825
829
  );
826
830
  }
827
831
  return response;
@@ -832,8 +836,8 @@ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn =
832
836
  "oauth-protected-resource",
833
837
  fetchFn,
834
838
  {
835
- protocolVersion: opts == null ? void 0 : opts.protocolVersion,
836
- metadataUrl: opts == null ? void 0 : opts.resourceMetadataUrl,
839
+ protocolVersion: opts?.protocolVersion,
840
+ metadataUrl: opts?.resourceMetadataUrl,
837
841
  // The configured MCP server is trusted as a request target. Redirects
838
842
  // crossing its origin are still validated before they are followed.
839
843
  trustedOrigin: new URL(serverUrl).origin
@@ -912,7 +916,6 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, {
912
916
  protocolVersion = LATEST_PROTOCOL_VERSION,
913
917
  trustedOrigin
914
918
  } = {}) {
915
- var _a3;
916
919
  const headers = { "MCP-Protocol-Version": protocolVersion };
917
920
  const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
918
921
  for (const { url: endpointUrl, type, expectedIssuer } of urlsToTry) {
@@ -942,7 +945,7 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, {
942
945
  await response.json()
943
946
  );
944
947
  assertMetadataIssuerMatches(metadata, expectedIssuer);
945
- if (!((_a3 = metadata.code_challenge_methods_supported) == null ? void 0 : _a3.includes("S256"))) {
948
+ if (!metadata.code_challenge_methods_supported?.includes("S256")) {
946
949
  throw new Error(
947
950
  `Incompatible OIDC provider at ${endpointUrl}: does not support S256 code challenge method required by MCP specification`
948
951
  );
@@ -994,7 +997,7 @@ async function startAuthorization(authorizationServerUrl, {
994
997
  if (scope) {
995
998
  authorizationUrl.searchParams.set("scope", scope);
996
999
  }
997
- if (scope == null ? void 0 : scope.includes("offline_access")) {
1000
+ if (scope?.includes("offline_access")) {
998
1001
  authorizationUrl.searchParams.append("prompt", "consent");
999
1002
  }
1000
1003
  if (resource) {
@@ -1083,14 +1086,13 @@ async function exchangeAuthorization(authorizationServerUrl, {
1083
1086
  addClientAuthentication,
1084
1087
  fetchFn
1085
1088
  }) {
1086
- var _a3;
1087
1089
  const grantType = "authorization_code";
1088
- const tokenUrl = (metadata == null ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
1090
+ const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
1089
1091
  const trustedOrigin = getTrustedLoopbackOrigin(authorizationServerUrl);
1090
1092
  assertSafeOAuthEndpoint(tokenUrl, {
1091
1093
  allowLoopback: tokenUrl.origin === trustedOrigin
1092
1094
  });
1093
- if ((metadata == null ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) {
1095
+ if (metadata?.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) {
1094
1096
  throw new Error(
1095
1097
  `Incompatible auth server: does not support grant type ${grantType}`
1096
1098
  );
@@ -1113,7 +1115,7 @@ async function exchangeAuthorization(authorizationServerUrl, {
1113
1115
  metadata
1114
1116
  );
1115
1117
  } else {
1116
- const supportedMethods = (_a3 = metadata == null ? void 0 : metadata.token_endpoint_auth_methods_supported) != null ? _a3 : [];
1118
+ const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
1117
1119
  const authMethod = selectClientAuthMethod(
1118
1120
  clientInformation,
1119
1121
  supportedMethods
@@ -1146,7 +1148,6 @@ async function refreshAuthorization(authorizationServerUrl, {
1146
1148
  addClientAuthentication,
1147
1149
  fetchFn
1148
1150
  }) {
1149
- var _a3;
1150
1151
  const grantType = "refresh_token";
1151
1152
  let tokenUrl;
1152
1153
  if (metadata) {
@@ -1179,7 +1180,7 @@ async function refreshAuthorization(authorizationServerUrl, {
1179
1180
  metadata
1180
1181
  );
1181
1182
  } else {
1182
- const supportedMethods = (_a3 = metadata == null ? void 0 : metadata.token_endpoint_auth_methods_supported) != null ? _a3 : [];
1183
+ const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
1183
1184
  const authMethod = selectClientAuthMethod(
1184
1185
  clientInformation,
1185
1186
  supportedMethods
@@ -1212,7 +1213,6 @@ async function registerClient(authorizationServerUrl, {
1212
1213
  clientMetadata,
1213
1214
  fetchFn
1214
1215
  }) {
1215
- var _a3;
1216
1216
  let registrationUrl;
1217
1217
  if (metadata) {
1218
1218
  if (!metadata.registration_endpoint) {
@@ -1228,7 +1228,7 @@ async function registerClient(authorizationServerUrl, {
1228
1228
  assertSafeOAuthEndpoint(registrationUrl, {
1229
1229
  allowLoopback: registrationUrl.origin === trustedOrigin
1230
1230
  });
1231
- const applicationType = (_a3 = clientMetadata.application_type) != null ? _a3 : inferOAuthApplicationType(clientMetadata.redirect_uris);
1231
+ const applicationType = clientMetadata.application_type ?? inferOAuthApplicationType(clientMetadata.redirect_uris);
1232
1232
  const response = await fetchWithValidatedEndpoint({
1233
1233
  url: registrationUrl,
1234
1234
  init: {
@@ -1257,18 +1257,17 @@ function inferOAuthApplicationType(redirectUris) {
1257
1257
  return redirectUris.every(isNativeRedirectUri) ? "native" : "web";
1258
1258
  }
1259
1259
  async function auth(provider, options) {
1260
- var _a3, _b3, _c;
1261
1260
  try {
1262
1261
  return await authInternal(provider, options);
1263
1262
  } catch (error) {
1264
1263
  if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
1265
- if (options.authorizationCode !== void 0 || !await ((_a3 = provider.isClientInformationDynamicallyRegistered) == null ? void 0 : _a3.call(provider))) {
1264
+ if (options.authorizationCode !== void 0 || !await provider.isClientInformationDynamicallyRegistered?.()) {
1266
1265
  throw error;
1267
1266
  }
1268
- await ((_b3 = provider.invalidateCredentials) == null ? void 0 : _b3.call(provider, "all"));
1267
+ await provider.invalidateCredentials?.("all");
1269
1268
  return await authInternal(provider, options);
1270
1269
  } else if (error instanceof InvalidGrantError) {
1271
- await ((_c = provider.invalidateCredentials) == null ? void 0 : _c.call(provider, "tokens"));
1270
+ await provider.invalidateCredentials?.("tokens");
1272
1271
  return await authInternal(provider, options);
1273
1272
  }
1274
1273
  throw error;
@@ -1279,7 +1278,7 @@ async function selectResourceURL(serverUrl, provider, resourceMetadata) {
1279
1278
  if (provider.validateResourceURL) {
1280
1279
  return await provider.validateResourceURL(
1281
1280
  defaultResource,
1282
- resourceMetadata == null ? void 0 : resourceMetadata.resource
1281
+ resourceMetadata?.resource
1283
1282
  );
1284
1283
  }
1285
1284
  if (!resourceMetadata) {
@@ -1304,7 +1303,6 @@ async function authInternal(provider, {
1304
1303
  resourceMetadataUrl,
1305
1304
  fetchFn
1306
1305
  }) {
1307
- var _a3, _b3, _c, _d, _e;
1308
1306
  let resourceMetadata;
1309
1307
  let authorizationServerUrl;
1310
1308
  let clientInformation;
@@ -1319,7 +1317,7 @@ async function authInternal(provider, {
1319
1317
  if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
1320
1318
  authorizationServerUrl = resourceMetadata.authorization_servers[0];
1321
1319
  }
1322
- } catch (e) {
1320
+ } catch {
1323
1321
  }
1324
1322
  if (authorizationCode !== void 0) {
1325
1323
  clientInformation = await Promise.resolve(provider.clientInformation());
@@ -1331,7 +1329,7 @@ async function authInternal(provider, {
1331
1329
  }
1332
1330
  }
1333
1331
  if (!authorizationServerUrl) {
1334
- authorizationServerUrl = (_a3 = callbackAuthorizationServerInformation == null ? void 0 : callbackAuthorizationServerInformation.authorizationServerUrl) != null ? _a3 : serverUrl;
1332
+ authorizationServerUrl = callbackAuthorizationServerInformation?.authorizationServerUrl ?? serverUrl;
1335
1333
  }
1336
1334
  const parsedServerUrl = new URL(serverUrl);
1337
1335
  const parsedAuthorizationServerUrl = new URL(authorizationServerUrl);
@@ -1346,11 +1344,10 @@ async function authInternal(provider, {
1346
1344
  provider,
1347
1345
  resourceMetadata
1348
1346
  );
1349
- await ((_b3 = provider.validateAuthorizationServerURL) == null ? void 0 : _b3.call(
1350
- provider,
1347
+ await provider.validateAuthorizationServerURL?.(
1351
1348
  serverUrl,
1352
1349
  authorizationServerUrl
1353
- ));
1350
+ );
1354
1351
  const metadata = await discoverAuthorizationServerMetadata(
1355
1352
  authorizationServerUrl,
1356
1353
  {
@@ -1368,8 +1365,8 @@ async function authInternal(provider, {
1368
1365
  if (authorizationCode === void 0) {
1369
1366
  clientInformation = await Promise.resolve(provider.clientInformation());
1370
1367
  }
1371
- if ((clientInformation == null ? void 0 : clientInformation.issuer) != null) {
1372
- const storedAuthorizationServerInformation = callbackAuthorizationServerInformation != null ? callbackAuthorizationServerInformation : await getStoredAuthorizationServerInformation({
1368
+ if (clientInformation?.issuer != null) {
1369
+ const storedAuthorizationServerInformation = callbackAuthorizationServerInformation ?? await getStoredAuthorizationServerInformation({
1373
1370
  provider,
1374
1371
  clientInformation
1375
1372
  });
@@ -1414,7 +1411,7 @@ async function authInternal(provider, {
1414
1411
  );
1415
1412
  }
1416
1413
  }
1417
- const storedAuthorizationServerInformation = callbackAuthorizationServerInformation != null ? callbackAuthorizationServerInformation : await getStoredAuthorizationServerInformation({
1414
+ const storedAuthorizationServerInformation = callbackAuthorizationServerInformation ?? await getStoredAuthorizationServerInformation({
1418
1415
  provider,
1419
1416
  clientInformation
1420
1417
  });
@@ -1425,7 +1422,7 @@ async function authInternal(provider, {
1425
1422
  }
1426
1423
  validateAuthorizationResponseIssuer({
1427
1424
  callbackIssuer,
1428
- expectedIssuer: (_d = (_c = storedAuthorizationServerInformation.issuer) != null ? _c : metadata == null ? void 0 : metadata.issuer) != null ? _d : String(authorizationServerUrl)
1425
+ expectedIssuer: storedAuthorizationServerInformation.issuer ?? metadata?.issuer ?? String(authorizationServerUrl)
1429
1426
  });
1430
1427
  assertAuthorizationServerInformationMatches({
1431
1428
  storedAuthorizationServerInformation,
@@ -1451,7 +1448,7 @@ async function authInternal(provider, {
1451
1448
  return "AUTHORIZED";
1452
1449
  }
1453
1450
  const tokens = await provider.tokens();
1454
- if (tokens == null ? void 0 : tokens.refresh_token) {
1451
+ if (tokens?.refresh_token) {
1455
1452
  const storedAuthorizationServerInformation = await getStoredAuthorizationServerInformation({
1456
1453
  provider,
1457
1454
  clientInformation,
@@ -1463,7 +1460,7 @@ async function authInternal(provider, {
1463
1460
  currentAuthorizationServerInformation
1464
1461
  });
1465
1462
  } else {
1466
- await ((_e = provider.invalidateCredentials) == null ? void 0 : _e.call(provider, "tokens"));
1463
+ await provider.invalidateCredentials?.("tokens");
1467
1464
  }
1468
1465
  try {
1469
1466
  if (storedAuthorizationServerInformation) {
@@ -1540,21 +1537,20 @@ var SseMCPTransport = class {
1540
1537
  this.headers = headers;
1541
1538
  this.authProvider = authProvider;
1542
1539
  this.redirectMode = redirect;
1543
- this.fetchFn = fetchFn != null ? fetchFn : globalThis.fetch;
1540
+ this.fetchFn = fetchFn ?? globalThis.fetch;
1544
1541
  }
1545
1542
  setProtocolVersion(version) {
1546
1543
  this.protocolVersion = version;
1547
1544
  }
1548
1545
  async commonHeaders(base) {
1549
- var _a3;
1550
1546
  const headers = {
1551
1547
  ...this.headers,
1552
1548
  ...base,
1553
- "mcp-protocol-version": (_a3 = this.protocolVersion) != null ? _a3 : LATEST_LEGACY_PROTOCOL_VERSION
1549
+ "mcp-protocol-version": this.protocolVersion ?? LATEST_LEGACY_PROTOCOL_VERSION
1554
1550
  };
1555
1551
  if (this.authProvider) {
1556
1552
  const tokens = await this.authProvider.tokens();
1557
- if (tokens == null ? void 0 : tokens.access_token) {
1553
+ if (tokens?.access_token) {
1558
1554
  headers["Authorization"] = `Bearer ${tokens.access_token}`;
1559
1555
  }
1560
1556
  }
@@ -1584,8 +1580,7 @@ var SseMCPTransport = class {
1584
1580
  return this.authPromise;
1585
1581
  }
1586
1582
  async accessTokenChanged(requestAuthorization) {
1587
- var _a3, _b3;
1588
- const accessToken = (_b3 = await ((_a3 = this.authProvider) == null ? void 0 : _a3.tokens())) == null ? void 0 : _b3.access_token;
1583
+ const accessToken = (await this.authProvider?.tokens())?.access_token;
1589
1584
  return accessToken != null && requestAuthorization !== `Bearer ${accessToken}`;
1590
1585
  }
1591
1586
  async start() {
@@ -1595,14 +1590,13 @@ var SseMCPTransport = class {
1595
1590
  }
1596
1591
  this.abortController = new AbortController();
1597
1592
  const establishConnection = async (triedAuth = false) => {
1598
- var _a3, _b3, _c, _d, _e;
1599
1593
  try {
1600
1594
  const headers = await this.commonHeaders({
1601
1595
  Accept: "text/event-stream"
1602
1596
  });
1603
1597
  const response = await this.fetchFn(this.url.href, {
1604
1598
  headers,
1605
- signal: (_a3 = this.abortController) == null ? void 0 : _a3.signal,
1599
+ signal: this.abortController?.signal,
1606
1600
  redirect: this.redirectMode
1607
1601
  });
1608
1602
  if (response.status === 401 && this.authProvider && !triedAuth) {
@@ -1615,11 +1609,11 @@ var SseMCPTransport = class {
1615
1609
  );
1616
1610
  if (result !== "AUTHORIZED") {
1617
1611
  const error = new UnauthorizedError();
1618
- (_b3 = this.onerror) == null ? void 0 : _b3.call(this, error);
1612
+ this.onerror?.(error);
1619
1613
  return reject(error);
1620
1614
  }
1621
1615
  } catch (error) {
1622
- (_c = this.onerror) == null ? void 0 : _c.call(this, error);
1616
+ this.onerror?.(error);
1623
1617
  return reject(error);
1624
1618
  }
1625
1619
  return establishConnection(true);
@@ -1632,13 +1626,12 @@ var SseMCPTransport = class {
1632
1626
  const error = new MCPClientError({
1633
1627
  message: errorMessage
1634
1628
  });
1635
- (_d = this.onerror) == null ? void 0 : _d.call(this, error);
1629
+ this.onerror?.(error);
1636
1630
  return reject(error);
1637
1631
  }
1638
1632
  const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream());
1639
1633
  const reader = stream.getReader();
1640
1634
  const processEvents = async () => {
1641
- var _a4, _b4, _c2, _d2, _e2;
1642
1635
  try {
1643
1636
  while (true) {
1644
1637
  const { done, value } = await reader.read();
@@ -1660,8 +1653,8 @@ var SseMCPTransport = class {
1660
1653
  if (endpoint.origin !== this.url.origin) {
1661
1654
  this.connected = false;
1662
1655
  this.endpoint = void 0;
1663
- (_a4 = this.sseConnection) == null ? void 0 : _a4.close();
1664
- (_b4 = this.abortController) == null ? void 0 : _b4.abort();
1656
+ this.sseConnection?.close();
1657
+ this.abortController?.abort();
1665
1658
  throw new MCPClientError({
1666
1659
  message: `MCP SSE Transport Error: Endpoint origin does not match connection origin: ${endpoint.origin}`
1667
1660
  });
@@ -1672,13 +1665,13 @@ var SseMCPTransport = class {
1672
1665
  } else if (isMessageEvent(event)) {
1673
1666
  try {
1674
1667
  const message = await parseJSONRPCMessage(data);
1675
- (_c2 = this.onmessage) == null ? void 0 : _c2.call(this, message);
1668
+ this.onmessage?.(message);
1676
1669
  } catch (error) {
1677
1670
  const e = new MCPClientError({
1678
1671
  message: "MCP SSE Transport Error: Failed to parse message",
1679
1672
  cause: error
1680
1673
  });
1681
- (_d2 = this.onerror) == null ? void 0 : _d2.call(this, e);
1674
+ this.onerror?.(e);
1682
1675
  }
1683
1676
  }
1684
1677
  }
@@ -1686,7 +1679,7 @@ var SseMCPTransport = class {
1686
1679
  if (error instanceof Error && error.name === "AbortError") {
1687
1680
  return;
1688
1681
  }
1689
- (_e2 = this.onerror) == null ? void 0 : _e2.call(this, error);
1682
+ this.onerror?.(error);
1690
1683
  reject(error);
1691
1684
  }
1692
1685
  };
@@ -1698,7 +1691,7 @@ var SseMCPTransport = class {
1698
1691
  if (error instanceof Error && error.name === "AbortError") {
1699
1692
  return;
1700
1693
  }
1701
- (_e = this.onerror) == null ? void 0 : _e.call(this, error);
1694
+ this.onerror?.(error);
1702
1695
  reject(error);
1703
1696
  }
1704
1697
  };
@@ -1706,26 +1699,23 @@ var SseMCPTransport = class {
1706
1699
  });
1707
1700
  }
1708
1701
  async close() {
1709
- var _a3, _b3, _c;
1710
1702
  this.connected = false;
1711
1703
  this.endpoint = void 0;
1712
- (_a3 = this.sseConnection) == null ? void 0 : _a3.close();
1713
- (_b3 = this.abortController) == null ? void 0 : _b3.abort();
1714
- (_c = this.onclose) == null ? void 0 : _c.call(this);
1704
+ this.sseConnection?.close();
1705
+ this.abortController?.abort();
1706
+ this.onclose?.();
1715
1707
  }
1716
1708
  async send(message, options) {
1717
- var _a3, _b3;
1718
- (_a3 = options == null ? void 0 : options.signal) == null ? void 0 : _a3.throwIfAborted();
1709
+ options?.signal?.throwIfAborted();
1719
1710
  if (!this.endpoint || !this.connected) {
1720
1711
  throw new MCPClientError({
1721
1712
  message: "MCP SSE Transport Error: Not connected"
1722
1713
  });
1723
1714
  }
1724
1715
  const endpoint = this.endpoint;
1725
- const transportSignal = (_b3 = this.abortController) == null ? void 0 : _b3.signal;
1726
- const requestSignal = (options == null ? void 0 : options.signal) == null ? transportSignal : transportSignal == null ? options.signal : AbortSignal.any([transportSignal, options.signal]);
1716
+ const transportSignal = this.abortController?.signal;
1717
+ const requestSignal = options?.signal == null ? transportSignal : transportSignal == null ? options.signal : AbortSignal.any([transportSignal, options.signal]);
1727
1718
  const attempt = async (triedAuth = false) => {
1728
- var _a4, _b4, _c;
1729
1719
  try {
1730
1720
  const headers = await this.commonHeaders({
1731
1721
  "Content-Type": "application/json"
@@ -1740,7 +1730,7 @@ var SseMCPTransport = class {
1740
1730
  const response = await this.fetchFn(endpoint.href, init);
1741
1731
  if (response.status === 401 && this.authProvider && !triedAuth) {
1742
1732
  if (await this.accessTokenChanged(
1743
- (_a4 = new Headers(headers).get("authorization")) != null ? _a4 : void 0
1733
+ new Headers(headers).get("authorization") ?? void 0
1744
1734
  )) {
1745
1735
  return attempt(true);
1746
1736
  }
@@ -1761,15 +1751,15 @@ var SseMCPTransport = class {
1761
1751
  message: `MCP SSE Transport Error: POSTing to endpoint (HTTP ${response.status}): ${text}`,
1762
1752
  statusCode: response.status,
1763
1753
  url: endpoint.href,
1764
- responseBody: text != null ? text : void 0
1754
+ responseBody: text ?? void 0
1765
1755
  });
1766
1756
  throw error;
1767
1757
  }
1768
1758
  } catch (error) {
1769
- if ((_b4 = options == null ? void 0 : options.signal) == null ? void 0 : _b4.aborted) {
1759
+ if (options?.signal?.aborted) {
1770
1760
  throw error;
1771
1761
  }
1772
- (_c = this.onerror) == null ? void 0 : _c.call(this, error);
1762
+ this.onerror?.(error);
1773
1763
  throw error;
1774
1764
  }
1775
1765
  };
@@ -1914,20 +1904,19 @@ var HttpMCPTransport = class {
1914
1904
  this.authProvider = authProvider;
1915
1905
  this.redirectMode = redirect;
1916
1906
  this.sessionId = initialSessionId;
1917
- this.protocolVersion = initialProtocolVersion != null ? initialProtocolVersion : LATEST_LEGACY_PROTOCOL_VERSION;
1907
+ this.protocolVersion = initialProtocolVersion ?? LATEST_LEGACY_PROTOCOL_VERSION;
1918
1908
  this.onSessionIdChange = onSessionIdChange;
1919
1909
  this.onSessionExpired = onSessionExpired;
1920
1910
  this.terminateSessionOnClose = terminateSessionOnClose;
1921
- this.fetchFn = fetchFn != null ? fetchFn : globalThis.fetch;
1911
+ this.fetchFn = fetchFn ?? globalThis.fetch;
1922
1912
  }
1923
1913
  setProtocolVersion(version) {
1924
- var _a3;
1925
1914
  this.protocolVersion = version;
1926
1915
  if (!this.abortController) {
1927
1916
  return;
1928
1917
  }
1929
1918
  if (this.isModernProtocol()) {
1930
- (_a3 = this.inboundSseConnection) == null ? void 0 : _a3.close();
1919
+ this.inboundSseConnection?.close();
1931
1920
  this.inboundSseConnection = void 0;
1932
1921
  return;
1933
1922
  }
@@ -1936,25 +1925,23 @@ var HttpMCPTransport = class {
1936
1925
  }
1937
1926
  }
1938
1927
  isModernProtocol() {
1939
- var _a3;
1940
- return ((_a3 = this.protocolVersion) != null ? _a3 : LATEST_PROTOCOL_VERSION) === LATEST_PROTOCOL_VERSION;
1928
+ return (this.protocolVersion ?? LATEST_PROTOCOL_VERSION) === LATEST_PROTOCOL_VERSION;
1941
1929
  }
1942
1930
  async commonHeaders({
1943
1931
  base,
1944
1932
  includeSessionId = true
1945
1933
  }) {
1946
- var _a3;
1947
1934
  const headers = {
1948
1935
  ...this.headers,
1949
1936
  ...base,
1950
- "mcp-protocol-version": (_a3 = this.protocolVersion) != null ? _a3 : LATEST_LEGACY_PROTOCOL_VERSION
1937
+ "mcp-protocol-version": this.protocolVersion ?? LATEST_LEGACY_PROTOCOL_VERSION
1951
1938
  };
1952
1939
  if (!this.isModernProtocol() && includeSessionId && this.sessionId) {
1953
1940
  headers["mcp-session-id"] = this.sessionId;
1954
1941
  }
1955
1942
  if (this.authProvider) {
1956
1943
  const tokens = await this.authProvider.tokens();
1957
- if (tokens == null ? void 0 : tokens.access_token) {
1944
+ if (tokens?.access_token) {
1958
1945
  headers["Authorization"] = `Bearer ${tokens.access_token}`;
1959
1946
  }
1960
1947
  }
@@ -1965,12 +1952,11 @@ var HttpMCPTransport = class {
1965
1952
  );
1966
1953
  }
1967
1954
  setSessionId(sessionId) {
1968
- var _a3;
1969
1955
  if (this.sessionId === sessionId) {
1970
1956
  return;
1971
1957
  }
1972
1958
  this.sessionId = sessionId;
1973
- (_a3 = this.onSessionIdChange) == null ? void 0 : _a3.call(this, sessionId);
1959
+ this.onSessionIdChange?.(sessionId);
1974
1960
  }
1975
1961
  applySessionIdFromResponse(response) {
1976
1962
  if (this.isModernProtocol()) {
@@ -1982,11 +1968,10 @@ var HttpMCPTransport = class {
1982
1968
  }
1983
1969
  }
1984
1970
  expireSessionId(sessionId) {
1985
- var _a3;
1986
1971
  if (this.sessionId === sessionId) {
1987
1972
  this.setSessionId(void 0);
1988
1973
  }
1989
- (_a3 = this.onSessionExpired) == null ? void 0 : _a3.call(this, sessionId);
1974
+ this.onSessionExpired?.(sessionId);
1990
1975
  }
1991
1976
  /**
1992
1977
  * Runs a single OAuth recovery flow for concurrent 401 responses.
@@ -2019,32 +2004,29 @@ var HttpMCPTransport = class {
2019
2004
  }
2020
2005
  }
2021
2006
  async close(options) {
2022
- var _a3, _b3, _c, _d, _e;
2023
- (_a3 = this.inboundSseConnection) == null ? void 0 : _a3.close();
2024
- (_b3 = this.abortController) == null ? void 0 : _b3.abort();
2007
+ this.inboundSseConnection?.close();
2008
+ this.abortController?.abort();
2025
2009
  try {
2026
2010
  if (!this.isModernProtocol() && this.sessionId && this.terminateSessionOnClose && this.abortController) {
2027
- (_c = options == null ? void 0 : options.signal) == null ? void 0 : _c.throwIfAborted();
2011
+ options?.signal?.throwIfAborted();
2028
2012
  const headers = await this.commonHeaders({ base: {} });
2029
- (_d = options == null ? void 0 : options.signal) == null ? void 0 : _d.throwIfAborted();
2013
+ options?.signal?.throwIfAborted();
2030
2014
  await this.fetchFn(this.url.href, {
2031
2015
  method: "DELETE",
2032
2016
  headers,
2033
- signal: options == null ? void 0 : options.signal,
2017
+ signal: options?.signal,
2034
2018
  redirect: this.redirectMode
2035
2019
  }).catch(() => void 0);
2036
2020
  }
2037
- } catch (e) {
2021
+ } catch {
2038
2022
  }
2039
- (_e = this.onclose) == null ? void 0 : _e.call(this);
2023
+ this.onclose?.();
2040
2024
  }
2041
2025
  async send(message, options) {
2042
- var _a3, _b3;
2043
- (_a3 = options == null ? void 0 : options.signal) == null ? void 0 : _a3.throwIfAborted();
2044
- const transportSignal = (_b3 = this.abortController) == null ? void 0 : _b3.signal;
2045
- const requestSignal = (options == null ? void 0 : options.signal) == null ? transportSignal : transportSignal == null ? options.signal : AbortSignal.any([transportSignal, options.signal]);
2026
+ options?.signal?.throwIfAborted();
2027
+ const transportSignal = this.abortController?.signal;
2028
+ const requestSignal = options?.signal == null ? transportSignal : transportSignal == null ? options.signal : AbortSignal.any([transportSignal, options.signal]);
2046
2029
  const attempt = async (triedAuth = false) => {
2047
- var _a4, _b4, _c, _d, _e, _f, _g, _h;
2048
2030
  try {
2049
2031
  const isInitializeRequest = "method" in message && message.method === "initialize";
2050
2032
  const sessionIdForRequest = isInitializeRequest ? void 0 : this.sessionId;
@@ -2052,7 +2034,7 @@ var HttpMCPTransport = class {
2052
2034
  base: {
2053
2035
  "Content-Type": "application/json",
2054
2036
  Accept: "application/json, text/event-stream",
2055
- ...this.isModernProtocol() ? options == null ? void 0 : options.headers : {},
2037
+ ...this.isModernProtocol() ? options?.headers : {},
2056
2038
  ...this.isModernProtocol() && "method" in message && "id" in message ? this.getStandardRequestHeaders(message) : {}
2057
2039
  },
2058
2040
  includeSessionId: !isInitializeRequest
@@ -2079,7 +2061,7 @@ var HttpMCPTransport = class {
2079
2061
  throw error2;
2080
2062
  }
2081
2063
  } catch (error2) {
2082
- (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error2);
2064
+ this.onerror?.(error2);
2083
2065
  throw error2;
2084
2066
  }
2085
2067
  return attempt(true);
@@ -2097,8 +2079,7 @@ var HttpMCPTransport = class {
2097
2079
  () => void 0
2098
2080
  );
2099
2081
  if (jsonRpcMessage != null && "error" in jsonRpcMessage) {
2100
- (_b4 = this.onmessage) == null ? void 0 : _b4.call(
2101
- this,
2082
+ this.onmessage?.(
2102
2083
  jsonRpcMessage.id == null ? { ...jsonRpcMessage, id: message.id } : jsonRpcMessage
2103
2084
  );
2104
2085
  return;
@@ -2117,9 +2098,9 @@ var HttpMCPTransport = class {
2117
2098
  message: errorMessage,
2118
2099
  statusCode: response.status,
2119
2100
  url: this.url.href,
2120
- responseBody: text != null ? text : void 0
2101
+ responseBody: text ?? void 0
2121
2102
  });
2122
- (_c = this.onerror) == null ? void 0 : _c.call(this, error2);
2103
+ this.onerror?.(error2);
2123
2104
  throw error2;
2124
2105
  }
2125
2106
  const isNotification = !("id" in message);
@@ -2131,7 +2112,7 @@ var HttpMCPTransport = class {
2131
2112
  const data = await response.json();
2132
2113
  const messages = Array.isArray(data) ? data.map((message2) => validateJSONRPCMessage(message2)) : [validateJSONRPCMessage(data)];
2133
2114
  for (const jsonRpcMessage of messages) {
2134
- (_d = this.onmessage) == null ? void 0 : _d.call(this, jsonRpcMessage);
2115
+ this.onmessage?.(jsonRpcMessage);
2135
2116
  }
2136
2117
  return;
2137
2118
  }
@@ -2142,13 +2123,12 @@ var HttpMCPTransport = class {
2142
2123
  statusCode: response.status,
2143
2124
  url: this.url.href
2144
2125
  });
2145
- (_e = this.onerror) == null ? void 0 : _e.call(this, error2);
2126
+ this.onerror?.(error2);
2146
2127
  throw error2;
2147
2128
  }
2148
2129
  const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream2());
2149
2130
  const reader = stream.getReader();
2150
2131
  const processEvents = async () => {
2151
- var _a5, _b5, _c2, _d2;
2152
2132
  try {
2153
2133
  while (true) {
2154
2134
  const { done, value } = await reader.read();
@@ -2157,29 +2137,28 @@ var HttpMCPTransport = class {
2157
2137
  if (isMessageEvent2(event)) {
2158
2138
  try {
2159
2139
  const jsonRpcMessage = await parseJSONRPCMessage(data);
2160
- (_a5 = this.onmessage) == null ? void 0 : _a5.call(this, jsonRpcMessage);
2140
+ this.onmessage?.(jsonRpcMessage);
2161
2141
  } catch (error2) {
2162
2142
  const e = new MCPClientError({
2163
2143
  message: "MCP HTTP Transport Error: Failed to parse message",
2164
2144
  cause: error2
2165
2145
  });
2166
- (_b5 = this.onerror) == null ? void 0 : _b5.call(this, e);
2146
+ this.onerror?.(e);
2167
2147
  }
2168
2148
  }
2169
2149
  }
2170
2150
  } catch (error2) {
2171
- if (((_c2 = options == null ? void 0 : options.signal) == null ? void 0 : _c2.aborted) || error2 instanceof Error && error2.name === "AbortError") {
2151
+ if (options?.signal?.aborted || error2 instanceof Error && error2.name === "AbortError") {
2172
2152
  return;
2173
2153
  }
2174
- (_d2 = this.onerror) == null ? void 0 : _d2.call(this, error2);
2154
+ this.onerror?.(error2);
2175
2155
  }
2176
2156
  };
2177
2157
  void processEvents().catch((error2) => {
2178
- var _a5, _b5;
2179
- if (((_a5 = options == null ? void 0 : options.signal) == null ? void 0 : _a5.aborted) || error2 instanceof Error && error2.name === "AbortError") {
2158
+ if (options?.signal?.aborted || error2 instanceof Error && error2.name === "AbortError") {
2180
2159
  return;
2181
2160
  }
2182
- (_b5 = this.onerror) == null ? void 0 : _b5.call(this, error2);
2161
+ this.onerror?.(error2);
2183
2162
  });
2184
2163
  return;
2185
2164
  }
@@ -2188,13 +2167,13 @@ var HttpMCPTransport = class {
2188
2167
  statusCode: response.status,
2189
2168
  url: this.url.href
2190
2169
  });
2191
- (_f = this.onerror) == null ? void 0 : _f.call(this, error);
2170
+ this.onerror?.(error);
2192
2171
  throw error;
2193
2172
  } catch (error) {
2194
- if ((_g = options == null ? void 0 : options.signal) == null ? void 0 : _g.aborted) {
2173
+ if (options?.signal?.aborted) {
2195
2174
  throw error;
2196
2175
  }
2197
- (_h = this.onerror) == null ? void 0 : _h.call(this, error);
2176
+ this.onerror?.(error);
2198
2177
  throw error;
2199
2178
  }
2200
2179
  };
@@ -2205,7 +2184,7 @@ var HttpMCPTransport = class {
2205
2184
  "Mcp-Method": message.method
2206
2185
  };
2207
2186
  const params = message.params;
2208
- const name3 = message.method === "resources/read" ? params == null ? void 0 : params.uri : message.method === "tools/call" || message.method === "prompts/get" ? params == null ? void 0 : params.name : void 0;
2187
+ const name3 = message.method === "resources/read" ? params?.uri : message.method === "tools/call" || message.method === "prompts/get" ? params?.name : void 0;
2209
2188
  if (typeof name3 === "string") {
2210
2189
  headers["Mcp-Name"] = encodeMCPHeaderValue(name3);
2211
2190
  }
@@ -2223,11 +2202,9 @@ var HttpMCPTransport = class {
2223
2202
  );
2224
2203
  }
2225
2204
  scheduleInboundSseReconnection() {
2226
- var _a3;
2227
2205
  const { maxRetries } = this.reconnectionOptions;
2228
2206
  if (maxRetries > 0 && this.inboundReconnectAttempts >= maxRetries) {
2229
- (_a3 = this.onerror) == null ? void 0 : _a3.call(
2230
- this,
2207
+ this.onerror?.(
2231
2208
  new MCPClientError({
2232
2209
  message: `MCP HTTP Transport Error: Maximum reconnection attempts (${maxRetries}) exceeded.`
2233
2210
  })
@@ -2237,8 +2214,7 @@ var HttpMCPTransport = class {
2237
2214
  const delay = this.getNextReconnectionDelay(this.inboundReconnectAttempts);
2238
2215
  this.inboundReconnectAttempts += 1;
2239
2216
  setTimeout(() => {
2240
- var _a4;
2241
- if ((_a4 = this.abortController) == null ? void 0 : _a4.signal.aborted) return;
2217
+ if (this.abortController?.signal.aborted) return;
2242
2218
  this.startInboundSse(false, this.lastInboundEventId);
2243
2219
  }, delay);
2244
2220
  }
@@ -2247,16 +2223,14 @@ var HttpMCPTransport = class {
2247
2223
  return;
2248
2224
  }
2249
2225
  void this.openInboundSse(triedAuth, resumeToken).catch((error) => {
2250
- var _a3;
2251
2226
  if (error instanceof Error && error.name === "AbortError") {
2252
2227
  return;
2253
2228
  }
2254
- (_a3 = this.onerror) == null ? void 0 : _a3.call(this, error);
2229
+ this.onerror?.(error);
2255
2230
  });
2256
2231
  }
2257
2232
  // Open optional inbound SSE stream; best-effort and resumable
2258
2233
  async openInboundSse(triedAuth = false, resumeToken) {
2259
- var _a3, _b3, _c, _d, _e, _f;
2260
2234
  if (this.isModernProtocol()) {
2261
2235
  return;
2262
2236
  }
@@ -2273,7 +2247,7 @@ var HttpMCPTransport = class {
2273
2247
  const response = await this.fetchFn(this.url.href, {
2274
2248
  method: "GET",
2275
2249
  headers,
2276
- signal: (_a3 = this.abortController) == null ? void 0 : _a3.signal,
2250
+ signal: this.abortController?.signal,
2277
2251
  redirect: this.redirectMode
2278
2252
  });
2279
2253
  this.applySessionIdFromResponse(response);
@@ -2287,11 +2261,11 @@ var HttpMCPTransport = class {
2287
2261
  );
2288
2262
  if (result !== "AUTHORIZED") {
2289
2263
  const error = new UnauthorizedError();
2290
- (_b3 = this.onerror) == null ? void 0 : _b3.call(this, error);
2264
+ this.onerror?.(error);
2291
2265
  return;
2292
2266
  }
2293
2267
  } catch (error) {
2294
- (_c = this.onerror) == null ? void 0 : _c.call(this, error);
2268
+ this.onerror?.(error);
2295
2269
  return;
2296
2270
  }
2297
2271
  return this.openInboundSse(true, resumeToken);
@@ -2308,13 +2282,12 @@ var HttpMCPTransport = class {
2308
2282
  statusCode: response.status,
2309
2283
  url: this.url.href
2310
2284
  });
2311
- (_d = this.onerror) == null ? void 0 : _d.call(this, error);
2285
+ this.onerror?.(error);
2312
2286
  return;
2313
2287
  }
2314
2288
  const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream2());
2315
2289
  const reader = stream.getReader();
2316
2290
  const processEvents = async () => {
2317
- var _a4, _b4, _c2, _d2;
2318
2291
  try {
2319
2292
  while (true) {
2320
2293
  const { done, value } = await reader.read();
@@ -2326,13 +2299,13 @@ var HttpMCPTransport = class {
2326
2299
  if (isMessageEvent2(event)) {
2327
2300
  try {
2328
2301
  const jsonRpcMessage = await parseJSONRPCMessage(data);
2329
- (_a4 = this.onmessage) == null ? void 0 : _a4.call(this, jsonRpcMessage);
2302
+ this.onmessage?.(jsonRpcMessage);
2330
2303
  } catch (error) {
2331
2304
  const e = new MCPClientError({
2332
2305
  message: "MCP HTTP Transport Error: Failed to parse message",
2333
2306
  cause: error
2334
2307
  });
2335
- (_b4 = this.onerror) == null ? void 0 : _b4.call(this, e);
2308
+ this.onerror?.(e);
2336
2309
  }
2337
2310
  }
2338
2311
  }
@@ -2340,8 +2313,8 @@ var HttpMCPTransport = class {
2340
2313
  if (error instanceof Error && error.name === "AbortError") {
2341
2314
  return;
2342
2315
  }
2343
- (_c2 = this.onerror) == null ? void 0 : _c2.call(this, error);
2344
- if (!((_d2 = this.abortController) == null ? void 0 : _d2.signal.aborted)) {
2316
+ this.onerror?.(error);
2317
+ if (!this.abortController?.signal.aborted) {
2345
2318
  this.scheduleInboundSseReconnection();
2346
2319
  }
2347
2320
  }
@@ -2349,22 +2322,20 @@ var HttpMCPTransport = class {
2349
2322
  this.inboundSseConnection = {
2350
2323
  close: () => {
2351
2324
  void reader.cancel().catch((error) => {
2352
- var _a4;
2353
2325
  if (error instanceof Error && error.name === "AbortError") {
2354
2326
  return;
2355
2327
  }
2356
- (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error);
2328
+ this.onerror?.(error);
2357
2329
  });
2358
2330
  }
2359
2331
  };
2360
2332
  this.inboundReconnectAttempts = 0;
2361
2333
  void processEvents().catch((error) => {
2362
- var _a4, _b4;
2363
2334
  if (error instanceof Error && error.name === "AbortError") {
2364
2335
  return;
2365
2336
  }
2366
- (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error);
2367
- if (!((_b4 = this.abortController) == null ? void 0 : _b4.signal.aborted)) {
2337
+ this.onerror?.(error);
2338
+ if (!this.abortController?.signal.aborted) {
2368
2339
  this.scheduleInboundSseReconnection();
2369
2340
  }
2370
2341
  });
@@ -2372,8 +2343,8 @@ var HttpMCPTransport = class {
2372
2343
  if (error instanceof Error && error.name === "AbortError") {
2373
2344
  return;
2374
2345
  }
2375
- (_e = this.onerror) == null ? void 0 : _e.call(this, error);
2376
- if (!((_f = this.abortController) == null ? void 0 : _f.signal.aborted)) {
2346
+ this.onerror?.(error);
2347
+ if (!this.abortController?.signal.aborted) {
2377
2348
  this.scheduleInboundSseReconnection();
2378
2349
  }
2379
2350
  }
@@ -2382,14 +2353,13 @@ var HttpMCPTransport = class {
2382
2353
 
2383
2354
  // src/tool/mcp-transport.ts
2384
2355
  function createMcpTransport(config) {
2385
- var _a3;
2386
2356
  switch (config.type) {
2387
2357
  case "sse":
2388
2358
  return new SseMCPTransport(config);
2389
2359
  case "http":
2390
2360
  return new HttpMCPTransport({
2391
2361
  ...config,
2392
- initialProtocolVersion: (_a3 = config.initialProtocolVersion) != null ? _a3 : LATEST_PROTOCOL_VERSION
2362
+ initialProtocolVersion: config.initialProtocolVersion ?? LATEST_PROTOCOL_VERSION
2393
2363
  });
2394
2364
  default:
2395
2365
  throw new MCPClientError({
@@ -2416,7 +2386,7 @@ var mcpAppClientCapabilities = {
2416
2386
  }
2417
2387
  };
2418
2388
  function getToolUiMeta(meta) {
2419
- const uiMeta = meta == null ? void 0 : meta.ui;
2389
+ const uiMeta = meta?.ui;
2420
2390
  return isJSONObject(uiMeta) ? uiMeta : void 0;
2421
2391
  }
2422
2392
  var optionalStringArray = z4.array(z4.unknown()).transform((items) => items.filter((v) => typeof v === "string")).optional().catch(void 0);
@@ -2432,7 +2402,7 @@ var MCPAppResourceMetaSchema = z4.looseObject({
2432
2402
  });
2433
2403
  function getResourceUiMeta(meta) {
2434
2404
  const resourceMeta = isJSONObject(meta) ? meta : void 0;
2435
- const rawUiMeta = resourceMeta == null ? void 0 : resourceMeta.ui;
2405
+ const rawUiMeta = resourceMeta?.ui;
2436
2406
  if (!isJSONObject(rawUiMeta)) {
2437
2407
  return void 0;
2438
2408
  }
@@ -2445,10 +2415,9 @@ function parseVisibility(value) {
2445
2415
  ) : void 0;
2446
2416
  }
2447
2417
  function getMCPAppToolMeta(tool2) {
2448
- var _a3, _b3;
2449
2418
  const uiMeta = getToolUiMeta(tool2._meta);
2450
- const resourceUri = (_b3 = uiMeta == null ? void 0 : uiMeta.resourceUri) != null ? _b3 : (_a3 = tool2._meta) == null ? void 0 : _a3[MCP_APP_LEGACY_RESOURCE_URI_META_KEY];
2451
- const visibility = parseVisibility(uiMeta == null ? void 0 : uiMeta.visibility);
2419
+ const resourceUri = uiMeta?.resourceUri ?? tool2._meta?.[MCP_APP_LEGACY_RESOURCE_URI_META_KEY];
2420
+ const visibility = parseVisibility(uiMeta?.visibility);
2452
2421
  if (resourceUri !== void 0) {
2453
2422
  if (typeof resourceUri !== "string" || !resourceUri.startsWith("ui://")) {
2454
2423
  throw new Error(
@@ -2465,15 +2434,14 @@ function getMCPAppToolMeta(tool2) {
2465
2434
  };
2466
2435
  }
2467
2436
  function splitMCPAppTools(definitions) {
2468
- var _a3;
2469
2437
  const modelVisibleTools = [];
2470
2438
  const appVisibleTools = [];
2471
2439
  for (const tool2 of definitions.tools) {
2472
- const visibility = (_a3 = getMCPAppToolMeta(tool2)) == null ? void 0 : _a3.visibility;
2440
+ const visibility = getMCPAppToolMeta(tool2)?.visibility;
2473
2441
  if (visibility == null || visibility.includes("model")) {
2474
2442
  modelVisibleTools.push(tool2);
2475
2443
  }
2476
- if ((visibility == null ? void 0 : visibility.includes("app")) === true) {
2444
+ if (visibility?.includes("app") === true) {
2477
2445
  appVisibleTools.push(tool2);
2478
2446
  }
2479
2447
  }
@@ -2644,7 +2612,7 @@ var DefaultMCPClient = class {
2644
2612
  constructor({
2645
2613
  transport: transportConfig,
2646
2614
  name: name3,
2647
- clientName = name3 != null ? name3 : "ai-sdk-mcp-client",
2615
+ clientName = name3 ?? "ai-sdk-mcp-client",
2648
2616
  version = CLIENT_VERSION,
2649
2617
  onUncaughtError,
2650
2618
  maxRetries,
@@ -2668,7 +2636,7 @@ var DefaultMCPClient = class {
2668
2636
  this.isClosed = true;
2669
2637
  this.onUncaughtError = onUncaughtError;
2670
2638
  this.maxRetries = prepareMaxRetries(maxRetries);
2671
- this.clientCapabilities = capabilities != null ? capabilities : {};
2639
+ this.clientCapabilities = capabilities ?? {};
2672
2640
  this.initialInitializeResult = initialInitializeResult;
2673
2641
  this.initializationOptions = initializationOptions;
2674
2642
  this.protocolVersionDiscovery = protocolVersionDiscovery;
@@ -2709,11 +2677,10 @@ var DefaultMCPClient = class {
2709
2677
  return this._serverInstructions;
2710
2678
  }
2711
2679
  async init() {
2712
- var _a3;
2713
- const externalSignal = (_a3 = this.initializationOptions) == null ? void 0 : _a3.signal;
2680
+ const externalSignal = this.initializationOptions?.signal;
2714
2681
  const timeout = this.initializationOptions ? getEffectiveTimeout(this.initializationOptions) : void 0;
2715
2682
  const timeoutController = timeout == null ? void 0 : new AbortController();
2716
- const signal = externalSignal == null ? timeoutController == null ? void 0 : timeoutController.signal : timeoutController == null ? externalSignal : AbortSignal.any([externalSignal, timeoutController.signal]);
2683
+ const signal = externalSignal == null ? timeoutController?.signal : timeoutController == null ? externalSignal : AbortSignal.any([externalSignal, timeoutController.signal]);
2717
2684
  let timeoutId;
2718
2685
  let timeoutError;
2719
2686
  if (timeout != null) {
@@ -2721,12 +2688,12 @@ var DefaultMCPClient = class {
2721
2688
  timeoutError = new MCPClientError({
2722
2689
  message: `MCP client initialization timed out after ${timeout}ms`
2723
2690
  });
2724
- timeoutController == null ? void 0 : timeoutController.abort(timeoutError);
2691
+ timeoutController?.abort(timeoutError);
2725
2692
  }, timeout);
2726
2693
  }
2727
2694
  try {
2728
2695
  this.isClosed = false;
2729
- signal == null ? void 0 : signal.throwIfAborted();
2696
+ signal?.throwIfAborted();
2730
2697
  await waitForAbort(this.transport.start(), signal);
2731
2698
  if (this.initialInitializeResult) {
2732
2699
  const result2 = InitializeResultSchema.parse(
@@ -2772,13 +2739,13 @@ var DefaultMCPClient = class {
2772
2739
  } catch (error) {
2773
2740
  try {
2774
2741
  await waitForAbort(this.transport.close({ signal }), signal);
2775
- } catch (e) {
2742
+ } catch {
2776
2743
  }
2777
2744
  this.onClose();
2778
2745
  if (timeoutError != null) {
2779
2746
  throw timeoutError;
2780
2747
  }
2781
- if (externalSignal == null ? void 0 : externalSignal.aborted) {
2748
+ if (externalSignal?.aborted) {
2782
2749
  throw new MCPClientError({
2783
2750
  message: "MCP client initialization was aborted",
2784
2751
  cause: externalSignal.reason
@@ -2814,13 +2781,12 @@ var DefaultMCPClient = class {
2814
2781
  }
2815
2782
  }
2816
2783
  applyDiscoverResult(result) {
2817
- var _a3;
2818
2784
  if (!result.supportedVersions.includes(this.protocolVersion)) {
2819
2785
  throw new MCPClientError({
2820
2786
  message: `Server does not support the requested protocol version: ${this.protocolVersion}`
2821
2787
  });
2822
2788
  }
2823
- const serverInfo = (_a3 = result._meta) == null ? void 0 : _a3["io.modelcontextprotocol/serverInfo"];
2789
+ const serverInfo = result._meta?.["io.modelcontextprotocol/serverInfo"];
2824
2790
  if (serverInfo != null && typeof serverInfo === "object" && "name" in serverInfo && typeof serverInfo.name === "string" && "version" in serverInfo && typeof serverInfo.version === "string") {
2825
2791
  this._serverInfo = serverInfo;
2826
2792
  }
@@ -2855,9 +2821,8 @@ var DefaultMCPClient = class {
2855
2821
  this._serverInstructions = result.instructions;
2856
2822
  }
2857
2823
  async close() {
2858
- var _a3;
2859
2824
  if (this.isClosed) return;
2860
- await ((_a3 = this.transport) == null ? void 0 : _a3.close());
2825
+ await this.transport?.close();
2861
2826
  this.onClose();
2862
2827
  }
2863
2828
  send(message, options) {
@@ -2912,7 +2877,6 @@ var DefaultMCPClient = class {
2912
2877
  options
2913
2878
  }) {
2914
2879
  return new Promise((resolve, reject) => {
2915
- var _a3;
2916
2880
  if (this.isClosed) {
2917
2881
  return reject(
2918
2882
  new MCPClientError({
@@ -2921,11 +2885,11 @@ var DefaultMCPClient = class {
2921
2885
  );
2922
2886
  }
2923
2887
  this.assertCapability(request.method);
2924
- const signal = options == null ? void 0 : options.signal;
2925
- signal == null ? void 0 : signal.throwIfAborted();
2888
+ const signal = options?.signal;
2889
+ signal?.throwIfAborted();
2926
2890
  const timeout = options == null ? void 0 : getEffectiveTimeout(options);
2927
2891
  const timeoutController = timeout == null ? void 0 : new AbortController();
2928
- const transportSignal = signal == null ? timeoutController == null ? void 0 : timeoutController.signal : timeoutController == null ? signal : AbortSignal.any([signal, timeoutController.signal]);
2892
+ const transportSignal = signal == null ? timeoutController?.signal : timeoutController == null ? signal : AbortSignal.any([signal, timeoutController.signal]);
2929
2893
  let timeoutId;
2930
2894
  const messageId = this.requestMessageId++;
2931
2895
  const preparedRequest = this.protocolEra === "modern" ? {
@@ -2933,7 +2897,7 @@ var DefaultMCPClient = class {
2933
2897
  params: {
2934
2898
  ...request.params,
2935
2899
  _meta: {
2936
- ...(_a3 = request.params) == null ? void 0 : _a3._meta,
2900
+ ...request.params?._meta,
2937
2901
  "io.modelcontextprotocol/protocolVersion": this.protocolVersion,
2938
2902
  "io.modelcontextprotocol/clientCapabilities": this.clientCapabilities,
2939
2903
  "io.modelcontextprotocol/clientInfo": this.clientInfo
@@ -2950,13 +2914,13 @@ var DefaultMCPClient = class {
2950
2914
  reject(
2951
2915
  new MCPClientError({
2952
2916
  message: "Request was aborted",
2953
- cause: signal == null ? void 0 : signal.reason
2917
+ cause: signal?.reason
2954
2918
  })
2955
2919
  );
2956
2920
  };
2957
2921
  const cleanup = () => {
2958
2922
  this.responseHandlers.delete(messageId);
2959
- signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
2923
+ signal?.removeEventListener("abort", onAbort);
2960
2924
  if (timeoutId != null) {
2961
2925
  clearTimeout(timeoutId);
2962
2926
  }
@@ -2973,11 +2937,11 @@ var DefaultMCPClient = class {
2973
2937
  const error = new MCPClientError({
2974
2938
  message: `Request timed out after ${timeout}ms`
2975
2939
  });
2976
- timeoutController == null ? void 0 : timeoutController.abort(error);
2940
+ timeoutController?.abort(error);
2977
2941
  rejectAndCleanup(error);
2978
2942
  };
2979
2943
  this.responseHandlers.set(messageId, (response) => {
2980
- if (signal == null ? void 0 : signal.aborted) {
2944
+ if (signal?.aborted) {
2981
2945
  cleanup();
2982
2946
  return rejectWithAbortError();
2983
2947
  }
@@ -3006,7 +2970,7 @@ var DefaultMCPClient = class {
3006
2970
  rejectAndCleanup(parseError);
3007
2971
  }
3008
2972
  });
3009
- signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
2973
+ signal?.addEventListener("abort", onAbort, { once: true });
3010
2974
  if (timeout != null) {
3011
2975
  timeoutId = setTimeout(onTimeout, timeout);
3012
2976
  }
@@ -3029,7 +2993,7 @@ var DefaultMCPClient = class {
3029
2993
  resultSchema: ListToolsResultSchema,
3030
2994
  options
3031
2995
  });
3032
- return this.prepareToolDefinitions(result, (params == null ? void 0 : params.cursor) == null);
2996
+ return this.prepareToolDefinitions(result, params?.cursor == null);
3033
2997
  }
3034
2998
  prepareToolDefinitions(definitions, resetHeaderBindings = false) {
3035
2999
  if (this.protocolEra !== "modern" || !this.transport.supportsMcpToolParameterHeaders) {
@@ -3054,8 +3018,7 @@ var DefaultMCPClient = class {
3054
3018
  return { ...definitions, tools };
3055
3019
  }
3056
3020
  getToolRequestHeaders(request) {
3057
- var _a3;
3058
- if (this.protocolEra !== "modern" || request.method !== "tools/call" || typeof ((_a3 = request.params) == null ? void 0 : _a3.name) !== "string") {
3021
+ if (this.protocolEra !== "modern" || request.method !== "tools/call" || typeof request.params?.name !== "string") {
3059
3022
  return void 0;
3060
3023
  }
3061
3024
  const bindings = this.toolHeaderBindings.get(request.params.name);
@@ -3087,7 +3050,7 @@ var DefaultMCPClient = class {
3087
3050
  }
3088
3051
  return retryWithExponentialBackoff({
3089
3052
  maxRetries: this.maxRetries,
3090
- abortSignal: options == null ? void 0 : options.signal,
3053
+ abortSignal: options?.signal,
3091
3054
  shouldRetry: isRetryableMCPToolCallError,
3092
3055
  createRetryError: ({ message, errors }) => new MCPClientError({
3093
3056
  message,
@@ -3180,9 +3143,9 @@ var DefaultMCPClient = class {
3180
3143
  await waitForAbort(
3181
3144
  this.send(
3182
3145
  jsonrpcNotification,
3183
- (options == null ? void 0 : options.signal) == null ? void 0 : { signal: options.signal }
3146
+ options?.signal == null ? void 0 : { signal: options.signal }
3184
3147
  ),
3185
- options == null ? void 0 : options.signal
3148
+ options?.signal
3186
3149
  );
3187
3150
  }
3188
3151
  /**
@@ -3209,7 +3172,6 @@ var DefaultMCPClient = class {
3209
3172
  * Creates AI SDK tools from tool definitions without fetching from the server.
3210
3173
  */
3211
3174
  toolsFromDefinitions(definitions, { schemas = "automatic" } = {}) {
3212
- var _a3, _b3;
3213
3175
  definitions = this.prepareToolDefinitions(definitions);
3214
3176
  const tools = {};
3215
3177
  for (const {
@@ -3220,12 +3182,12 @@ var DefaultMCPClient = class {
3220
3182
  annotations,
3221
3183
  _meta
3222
3184
  } of definitions.tools) {
3223
- const resolvedTitle = title != null ? title : annotations == null ? void 0 : annotations.title;
3185
+ const resolvedTitle = title ?? annotations?.title;
3224
3186
  if (schemas !== "automatic" && !Object.prototype.hasOwnProperty.call(schemas, name3)) {
3225
3187
  continue;
3226
3188
  }
3227
3189
  const self = this;
3228
- const outputSchema = schemas !== "automatic" ? (_a3 = schemas[name3]) == null ? void 0 : _a3.outputSchema : void 0;
3190
+ const outputSchema = schemas !== "automatic" ? schemas[name3]?.outputSchema : void 0;
3229
3191
  const appMeta = getMCPAppToolMeta({ _meta });
3230
3192
  const metadata = {
3231
3193
  clientName: this.clientInfo.name,
@@ -3240,7 +3202,7 @@ var DefaultMCPClient = class {
3240
3202
  ...annotations.openWorldHint != null ? { openWorldHint: annotations.openWorldHint } : {}
3241
3203
  }
3242
3204
  } : {},
3243
- ...(appMeta == null ? void 0 : appMeta.resourceUri) != null ? {
3205
+ ...appMeta?.resourceUri != null ? {
3244
3206
  app: {
3245
3207
  ...appMeta,
3246
3208
  mimeType: MCP_APP_MIME_TYPE
@@ -3248,12 +3210,11 @@ var DefaultMCPClient = class {
3248
3210
  } : {}
3249
3211
  };
3250
3212
  const execute = async (args, options) => {
3251
- var _a4;
3252
- (_a4 = options == null ? void 0 : options.abortSignal) == null ? void 0 : _a4.throwIfAborted();
3213
+ options?.abortSignal?.throwIfAborted();
3253
3214
  const result = await self.callTool({
3254
3215
  name: name3,
3255
3216
  arguments: args,
3256
- options: { signal: options == null ? void 0 : options.abortSignal }
3217
+ options: { signal: options?.abortSignal }
3257
3218
  });
3258
3219
  if (result.isError) {
3259
3220
  return result;
@@ -3269,7 +3230,7 @@ var DefaultMCPClient = class {
3269
3230
  metadata,
3270
3231
  inputSchema: jsonSchema({
3271
3232
  ...inputSchema,
3272
- properties: (_b3 = inputSchema.properties) != null ? _b3 : {},
3233
+ properties: inputSchema.properties ?? {},
3273
3234
  additionalProperties: false
3274
3235
  }),
3275
3236
  execute,
@@ -3491,7 +3452,7 @@ import { convertUint8ArrayToBase64 as convertUint8ArrayToBase642 } from "@ai-sdk
3491
3452
  var encoder = new TextEncoder();
3492
3453
  function canonicalJSON(value) {
3493
3454
  if (value == null || typeof value !== "object") {
3494
- return JSON.stringify(value != null ? value : null);
3455
+ return JSON.stringify(value ?? null);
3495
3456
  }
3496
3457
  if (Array.isArray(value)) {
3497
3458
  return `[${value.map(canonicalJSON).join(",")}]`;
@@ -3504,14 +3465,13 @@ function toBase64url(bytes) {
3504
3465
  return convertUint8ArrayToBase642(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
3505
3466
  }
3506
3467
  async function fingerprintMCPAppResource(resource) {
3507
- var _a3, _b3, _c, _d;
3508
3468
  const digest = await crypto.subtle.digest(
3509
3469
  "SHA-256",
3510
3470
  encoder.encode(
3511
3471
  canonicalJSON({
3512
3472
  html: resource.html,
3513
- csp: (_b3 = (_a3 = resource.meta) == null ? void 0 : _a3.csp) != null ? _b3 : null,
3514
- permissions: (_d = (_c = resource.meta) == null ? void 0 : _c.permissions) != null ? _d : null
3473
+ csp: resource.meta?.csp ?? null,
3474
+ permissions: resource.meta?.permissions ?? null
3515
3475
  })
3516
3476
  )
3517
3477
  );