fastmcp 4.21.2 → 4.22.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.
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
- var _chunkGTPK7A57cjs = require('./chunk-GTPK7A57.cjs');
3
+ var _chunkYOBCXNFPcjs = require('./chunk-YOBCXNFP.cjs');
4
4
 
5
5
 
6
6
  var _chunkO22SYZMCcjs = require('./chunk-O22SYZMC.cjs');
@@ -134,7 +134,7 @@ var DiscoveryDocumentCache = class {
134
134
  throw error;
135
135
  }
136
136
  if (!res.ok) {
137
- await _chunkGTPK7A57cjs.cancelResponseBody.call(void 0, res);
137
+ await _chunkYOBCXNFPcjs.cancelResponseBody.call(void 0, res);
138
138
  throw new Error(
139
139
  `Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`
140
140
  );
@@ -230,7 +230,7 @@ var imageContent = async (input) => {
230
230
  signal: AbortSignal.timeout(timeoutMs)
231
231
  });
232
232
  if (!response.ok) {
233
- await _chunkGTPK7A57cjs.cancelResponseBody.call(void 0, response);
233
+ await _chunkYOBCXNFPcjs.cancelResponseBody.call(void 0, response);
234
234
  throw new Error(
235
235
  `Server responded with status: ${response.status} - ${response.statusText}`
236
236
  );
@@ -292,7 +292,7 @@ var audioContent = async (input) => {
292
292
  signal: AbortSignal.timeout(timeoutMs)
293
293
  });
294
294
  if (!response.ok) {
295
- await _chunkGTPK7A57cjs.cancelResponseBody.call(void 0, response);
295
+ await _chunkYOBCXNFPcjs.cancelResponseBody.call(void 0, response);
296
296
  throw new Error(
297
297
  `Server responded with status: ${response.status} - ${response.statusText}`
298
298
  );
@@ -464,6 +464,17 @@ var capCompletionValues = (completion) => {
464
464
  values: completion.values.slice(0, COMPLETION_VALUES_LIMIT)
465
465
  };
466
466
  };
467
+ var DEFAULT_LOGGING_LEVEL = "info";
468
+ var LOGGING_LEVEL_SEVERITY = {
469
+ alert: 6,
470
+ critical: 5,
471
+ debug: 0,
472
+ emergency: 7,
473
+ error: 4,
474
+ info: 1,
475
+ notice: 2,
476
+ warning: 3
477
+ };
467
478
  var FastMCPSessionEventEmitterBase = _events.EventEmitter;
468
479
  var ServerState = /* @__PURE__ */ ((ServerState2) => {
469
480
  ServerState2["Error"] = "error";
@@ -481,7 +492,7 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
481
492
  return this.#connectionState === "ready";
482
493
  }
483
494
  get loggingLevel() {
484
- return this.#loggingLevel;
495
+ return _nullishCoalesce(this.#loggingLevel, () => ( DEFAULT_LOGGING_LEVEL));
485
496
  }
486
497
  get roots() {
487
498
  return this.#roots;
@@ -530,7 +541,11 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
530
541
  #clientCapabilities;
531
542
  #connectionState = "connecting";
532
543
  #logger;
533
- #loggingLevel = "info";
544
+ /**
545
+ * The minimum level the client asked for with `logging/setLevel`, or
546
+ * `undefined` while it has not asked. See {@link DEFAULT_LOGGING_LEVEL}.
547
+ */
548
+ #loggingLevel;
534
549
  #needsEventLoopFlush = false;
535
550
  #onToolCall;
536
551
  #pingConfig;
@@ -561,6 +576,12 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
561
576
  */
562
577
  #subscriptions = /* @__PURE__ */ new Set();
563
578
  #transportType;
579
+ /**
580
+ * Capabilities this session has already warned about in `#canRefresh`, so a
581
+ * server that registers a hundred resources at runtime logs one line rather
582
+ * than a hundred.
583
+ */
584
+ #unnegotiatedWarnings = /* @__PURE__ */ new Set();
564
585
  #utils;
565
586
  constructor({
566
587
  auth,
@@ -600,7 +621,7 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
600
621
  this.#needsEventLoopFlush = transportType === "httpStream";
601
622
  const supportsTools = _nullishCoalesce(hasTools, () => ( tools.length > 0));
602
623
  if (supportsTools) {
603
- this.#capabilities.tools = {};
624
+ this.#capabilities.tools = { listChanged: true };
604
625
  }
605
626
  if (resources.length || resourcesTemplates.length) {
606
627
  this.#capabilities.resources = { listChanged: true, subscribe: true };
@@ -744,6 +765,9 @@ ${e instanceof Error ? e.stack : JSON.stringify(e)}`
744
765
  }
745
766
  }
746
767
  promptsListChanged(prompts) {
768
+ if (!this.#canRefresh("prompts")) {
769
+ return;
770
+ }
747
771
  this.#prompts.clear();
748
772
  for (const prompt of prompts) {
749
773
  this.addPrompt(prompt);
@@ -758,6 +782,9 @@ ${e instanceof Error ? e.stack : JSON.stringify(e)}`
758
782
  return this.#server.createMessage(message, options);
759
783
  }
760
784
  resourcesListChanged(resources) {
785
+ if (!this.#canRefresh("resources")) {
786
+ return;
787
+ }
761
788
  this.#resources.clear();
762
789
  for (const resource of resources) {
763
790
  this.addResource(resource);
@@ -766,6 +793,9 @@ ${e instanceof Error ? e.stack : JSON.stringify(e)}`
766
793
  this.triggerListChangedNotification("notifications/resources/list_changed");
767
794
  }
768
795
  resourceTemplatesListChanged(resourceTemplates) {
796
+ if (!this.#canRefresh("resources")) {
797
+ return;
798
+ }
769
799
  this.#resourceTemplates.clear();
770
800
  for (const resourceTemplate of resourceTemplates) {
771
801
  this.addResourceTemplate(resourceTemplate);
@@ -795,6 +825,9 @@ ${error instanceof Error ? error.stack : JSON.stringify(error)}`
795
825
  }
796
826
  }
797
827
  toolsListChanged(tools) {
828
+ if (!this.#canRefresh("tools")) {
829
+ return;
830
+ }
798
831
  this.setupToolHandlers(
799
832
  toolsVisibleTo(tools, this.#auth, this.#authRequired)
800
833
  );
@@ -857,6 +890,30 @@ ${error instanceof Error ? error.stack : JSON.stringify(error)}`
857
890
  this.#abortController.abort(new SessionError("Session closed"));
858
891
  }
859
892
  }
893
+ /**
894
+ * Whether this session can be told about a primitive added at runtime.
895
+ *
896
+ * A session that connected before the server had any tool, resource or prompt
897
+ * of its own never advertised that capability, and MCP fixes capabilities
898
+ * during `initialize` for the life of the session. Registering the handler
899
+ * anyway makes the SDK throw `Server does not support <capability>` — out of
900
+ * `addTool()`, `addResource()`, `addResourceTemplate()` or `addPrompt()`,
901
+ * which are the public builder methods, and out of the middle of the loop
902
+ * over sessions, so the sessions after this one never heard about the change
903
+ * either. Warn once instead and let the rest of the loop run.
904
+ */
905
+ #canRefresh(capability) {
906
+ if (this.#capabilities[capability]) {
907
+ return true;
908
+ }
909
+ if (!this.#unnegotiatedWarnings.has(capability)) {
910
+ this.#unnegotiatedWarnings.add(capability);
911
+ this.#logger.warn(
912
+ `[FastMCP warning] This session advertised no '${capability}' capability, because the server had none when the client connected, so it cannot be shown the ones registered since. Register one before start(), or reconnect the client; sessions that connect from now on do see them.`
913
+ );
914
+ }
915
+ return false;
916
+ }
860
917
  /**
861
918
  * Builds the context object passed as the third argument to
862
919
  * `resource.load` / `resourceTemplate.load` / `prompt.load`.
@@ -917,6 +974,9 @@ ${error instanceof Error ? error.stack : JSON.stringify(error)}`
917
974
  * disconnects mid-tool takes the server process down with it.
918
975
  */
919
976
  #sendLog(level, message, context) {
977
+ if (this.#loggingLevel && LOGGING_LEVEL_SEVERITY[level] < LOGGING_LEVEL_SEVERITY[this.#loggingLevel]) {
978
+ return;
979
+ }
920
980
  this.#server.sendLoggingMessage({
921
981
  data: {
922
982
  context,
@@ -940,6 +1000,12 @@ ${error instanceof Error ? error.stack : JSON.stringify(error)}`
940
1000
  * request's own stream, which is the only server-to-client route that exists
941
1001
  * when running stateless.
942
1002
  *
1003
+ * It is deliberately not filtered against the level the client set with
1004
+ * `logging/setLevel`, unlike the `log` object a tool is handed: its job is to
1005
+ * put bytes on the stream, and a client that asked for `error` only would
1006
+ * otherwise switch off a feature the server opted into. Raise
1007
+ * `streamKeepalive.logLevel` if the level it uses matters to you.
1008
+ *
943
1009
  * @returns a function that stops the keepalive.
944
1010
  */
945
1011
  #startStreamKeepalive(extra, toolName) {
@@ -1622,6 +1688,17 @@ function parseBasicAuthHeader(authHeader) {
1622
1688
  return null;
1623
1689
  }
1624
1690
  }
1691
+ function protectedResourceMetadataUrl(resource) {
1692
+ let url;
1693
+ try {
1694
+ url = new URL(resource);
1695
+ } catch (e6) {
1696
+ return `${resource}/.well-known/oauth-protected-resource`;
1697
+ }
1698
+ const path = url.pathname === "/" ? "" : url.pathname;
1699
+ url.pathname = `/.well-known/oauth-protected-resource${path}`;
1700
+ return url.toString();
1701
+ }
1625
1702
  var OAUTH_PROXY_MAX_BODY_SIZE = 1024 * 1024;
1626
1703
  var OAUTH_CREDENTIAL_RESPONSE_HEADERS = {
1627
1704
  "Cache-Control": "no-store",
@@ -1664,10 +1741,9 @@ var FastMCP = class extends FastMCPEventEmitter {
1664
1741
  this.#authenticate = options.authenticate;
1665
1742
  }
1666
1743
  if (!options.oauth) {
1667
- this.#options = {
1668
- ...options,
1669
- oauth: options.auth.getOAuthConfig()
1670
- };
1744
+ const oauth = options.auth.getOAuthConfig();
1745
+ this.#providerResourceBase = oauth.protectedResource.resource;
1746
+ this.#options = { ...options, oauth };
1671
1747
  }
1672
1748
  } else {
1673
1749
  this.#authenticate = options.authenticate;
@@ -1685,6 +1761,8 @@ var FastMCP = class extends FastMCPEventEmitter {
1685
1761
  #logger;
1686
1762
  #options;
1687
1763
  #prompts = [];
1764
+ /** The auth provider's base URL, when it supplied the OAuth config. */
1765
+ #providerResourceBase;
1688
1766
  #resources = [];
1689
1767
  #resourcesTemplates = [];
1690
1768
  #serverState = "stopped" /* Stopped */;
@@ -2111,6 +2189,7 @@ var FastMCP = class extends FastMCPEventEmitter {
2111
2189
  httpConfig.basePath,
2112
2190
  httpConfig.endpoint
2113
2191
  );
2192
+ this.#useEndpointAsResource(httpConfig.endpoint);
2114
2193
  if (httpConfig.stateless) {
2115
2194
  this.#logger.info(
2116
2195
  `[FastMCP info] Starting server in stateless mode on HTTP Stream at ${protocol}://${httpConfig.host}:${httpConfig.port}${streamEndpoint}`
@@ -2279,7 +2358,7 @@ var FastMCP = class extends FastMCPEventEmitter {
2279
2358
  ];
2280
2359
  if (resource) {
2281
2360
  wwwAuthenticateParts.push(
2282
- `resource_metadata="${resource}/.well-known/oauth-protected-resource"`
2361
+ `resource_metadata="${protectedResourceMetadataUrl(resource)}"`
2283
2362
  );
2284
2363
  }
2285
2364
  return new Response(
@@ -2930,6 +3009,28 @@ var FastMCP = class extends FastMCPEventEmitter {
2930
3009
  session.toolsListChanged(tools);
2931
3010
  }
2932
3011
  }
3012
+ /**
3013
+ * RFC 9728: the protected resource is the MCP endpoint clients connect to,
3014
+ * and the metadata served at `/.well-known/oauth-protected-resource<endpoint>`
3015
+ * must name it. An auth provider only knows its base URL, so the endpoint is
3016
+ * appended once the server knows it. An explicit `oauth` config is left as
3017
+ * it is.
3018
+ */
3019
+ #useEndpointAsResource(endpoint) {
3020
+ const oauth = this.#options.oauth;
3021
+ if (this.#providerResourceBase === void 0 || !_optionalChain([oauth, 'optionalAccess', _96 => _96.protectedResource]))
3022
+ return;
3023
+ this.#options = {
3024
+ ...this.#options,
3025
+ oauth: {
3026
+ ...oauth,
3027
+ protectedResource: {
3028
+ ...oauth.protectedResource,
3029
+ resource: `${this.#providerResourceBase.replace(/\/+$/, "")}${normalizePath(endpoint)}`
3030
+ }
3031
+ }
3032
+ };
3033
+ }
2933
3034
  };
2934
3035
 
2935
3036
 
@@ -2946,4 +3047,4 @@ var FastMCP = class extends FastMCPEventEmitter {
2946
3047
 
2947
3048
 
2948
3049
  exports.DiscoveryDocumentCache = DiscoveryDocumentCache; exports.jsonSchemaAdapter = jsonSchemaAdapter; exports.MEDIA_FETCH_TIMEOUT_MS = MEDIA_FETCH_TIMEOUT_MS; exports.imageContent = imageContent; exports.audioContent = audioContent; exports.FastMCPError = FastMCPError; exports.SessionError = SessionError; exports.UnexpectedStateError = UnexpectedStateError; exports.UserError = UserError; exports.ServerState = ServerState; exports.FastMCPSession = FastMCPSession; exports.FastMCP = FastMCP;
2949
- //# sourceMappingURL=chunk-C5VOVQPC.cjs.map
3050
+ //# sourceMappingURL=chunk-V4JBWBT4.cjs.map