fastmcp 4.26.1 → 4.26.2

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 _chunkUNS6EZVPcjs = require('./chunk-UNS6EZVP.cjs');
3
+ var _chunkHVKGDRTLcjs = require('./chunk-HVKGDRTL.cjs');
4
4
 
5
5
 
6
6
 
@@ -141,7 +141,7 @@ var DiscoveryDocumentCache = class {
141
141
  throw error;
142
142
  }
143
143
  if (!res.ok) {
144
- await _chunkUNS6EZVPcjs.cancelResponseBody.call(void 0, res);
144
+ await _chunkHVKGDRTLcjs.cancelResponseBody.call(void 0, res);
145
145
  throw new Error(
146
146
  `Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`
147
147
  );
@@ -258,7 +258,7 @@ var imageContent = async (input) => {
258
258
  signal: AbortSignal.timeout(timeoutMs)
259
259
  });
260
260
  if (!response.ok) {
261
- await _chunkUNS6EZVPcjs.cancelResponseBody.call(void 0, response);
261
+ await _chunkHVKGDRTLcjs.cancelResponseBody.call(void 0, response);
262
262
  throw new Error(
263
263
  `Server responded with status: ${response.status} - ${response.statusText}`
264
264
  );
@@ -340,7 +340,7 @@ var audioContent = async (input) => {
340
340
  signal: AbortSignal.timeout(timeoutMs)
341
341
  });
342
342
  if (!response.ok) {
343
- await _chunkUNS6EZVPcjs.cancelResponseBody.call(void 0, response);
343
+ await _chunkHVKGDRTLcjs.cancelResponseBody.call(void 0, response);
344
344
  throw new Error(
345
345
  `Server responded with status: ${response.status} - ${response.statusText}`
346
346
  );
@@ -1942,6 +1942,28 @@ function convertObjectToSnakeCase(obj) {
1942
1942
  function cookieHeaders(req) {
1943
1943
  return req.headers.cookie ? { cookie: req.headers.cookie } : {};
1944
1944
  }
1945
+ function isLoopbackHost(host) {
1946
+ let name;
1947
+ try {
1948
+ name = new URL(
1949
+ `http://${host.includes(":") && !host.startsWith("[") ? `[${host}]` : host}`
1950
+ ).hostname;
1951
+ } catch (e6) {
1952
+ return false;
1953
+ }
1954
+ return isLoopbackHostname(name.replace(/\.$/, ""));
1955
+ }
1956
+ function isLoopbackHostname(name) {
1957
+ return name === "localhost" || name.endsWith(".localhost") || /^127\.\d+\.\d+\.\d+$/.test(name) || name === "[::1]" || // `::ffff:127.0.0.1`, an IPv4 loopback address written for IPv6.
1958
+ /^\[::ffff:7f[\da-f]{2}:[\da-f]{1,4}\]$/.test(name);
1959
+ }
1960
+ function isLoopbackOrigin(origin) {
1961
+ try {
1962
+ return isLoopbackHostname(new URL(origin).hostname);
1963
+ } catch (e7) {
1964
+ return false;
1965
+ }
1966
+ }
1945
1967
  function isStreamableHttpTransport(transport) {
1946
1968
  return "handleRequest" in transport && typeof transport.handleRequest === "function";
1947
1969
  }
@@ -2007,7 +2029,7 @@ function parseBasicAuthHeader(authHeader) {
2007
2029
  clientId: decodeURIComponent(credentials.slice(0, separator)),
2008
2030
  clientSecret: decodeURIComponent(credentials.slice(separator + 1))
2009
2031
  };
2010
- } catch (e6) {
2032
+ } catch (e8) {
2011
2033
  return "malformed";
2012
2034
  }
2013
2035
  }
@@ -2044,7 +2066,7 @@ function protectedResourceMetadataUrl(resource) {
2044
2066
  let url;
2045
2067
  try {
2046
2068
  url = new URL(resource);
2047
- } catch (e7) {
2069
+ } catch (e9) {
2048
2070
  return `${resource}/.well-known/oauth-protected-resource`;
2049
2071
  }
2050
2072
  const path = url.pathname === "/" ? "" : url.pathname;
@@ -2066,6 +2088,38 @@ function grantedScopes(auth) {
2066
2088
  const values = Array.isArray(scopes) ? scopes : scopes instanceof Set ? [...scopes] : [];
2067
2089
  return values.filter((scope) => typeof scope === "string");
2068
2090
  }
2091
+ function printable(text) {
2092
+ return text.replace(
2093
+ /[^\x20-\x7e]/g,
2094
+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
2095
+ );
2096
+ }
2097
+ function resolveOriginPolicy(host, cors) {
2098
+ if (!isLoopbackHost(host) || cors === true) {
2099
+ return { cors };
2100
+ }
2101
+ if (typeof cors === "object" && cors.origin) {
2102
+ const { origin } = cors;
2103
+ if (origin === "*") {
2104
+ return { cors };
2105
+ }
2106
+ return {
2107
+ allows: typeof origin === "function" ? origin : (candidate) => (Array.isArray(origin) ? origin : [origin]).includes(candidate),
2108
+ cors,
2109
+ refusal: "It is not one of the origins httpStream.cors.origin allows."
2110
+ };
2111
+ }
2112
+ return {
2113
+ allows: isLoopbackOrigin,
2114
+ cors: cors === false ? false : (
2115
+ // No credentials either: as with every origin, they take one named
2116
+ // in `cors.origin`. A page on another local port is same-site, so
2117
+ // its requests would carry this server's cookies.
2118
+ { ...cors, credentials: void 0, origin: isLoopbackOrigin }
2119
+ ),
2120
+ refusal: "A server bound to a loopback address answers pages served from loopback only; name the origins to answer in httpStream.cors.origin."
2121
+ };
2122
+ }
2069
2123
  async function sendOAuthProxyResponse(res, response) {
2070
2124
  const body = await response.text();
2071
2125
  const headers = {};
@@ -2080,6 +2134,14 @@ async function sendOAuthProxyResponse(res, response) {
2080
2134
  }
2081
2135
  res.writeHead(response.status, headers).end(body);
2082
2136
  }
2137
+ function serializeOrigin(header) {
2138
+ try {
2139
+ const { origin } = new URL(header);
2140
+ return origin === "null" ? header.trim() : origin;
2141
+ } catch (e10) {
2142
+ return header.trim();
2143
+ }
2144
+ }
2083
2145
  function stripBasePath(path, basePath) {
2084
2146
  if (!basePath) {
2085
2147
  return path;
@@ -2158,6 +2220,11 @@ var FastMCP = class extends FastMCPEventEmitter {
2158
2220
  #prompts = [];
2159
2221
  /** The auth provider's base URL, when it supplied the OAuth config. */
2160
2222
  #providerResourceBase;
2223
+ /**
2224
+ * Origins already reported as refused, so that a page retrying does not
2225
+ * fill the log. Capped, since the origin is whatever the request says.
2226
+ */
2227
+ #refusedOrigins = /* @__PURE__ */ new Set();
2161
2228
  #resources = [];
2162
2229
  #resourcesTemplates = [];
2163
2230
  #serverState = "stopped" /* Stopped */;
@@ -2582,6 +2649,10 @@ var FastMCP = class extends FastMCPEventEmitter {
2582
2649
  httpConfig.endpoint
2583
2650
  );
2584
2651
  this.#useEndpointAsResource(httpConfig.endpoint);
2652
+ const originPolicy = resolveOriginPolicy(
2653
+ httpConfig.host,
2654
+ httpConfig.cors
2655
+ );
2585
2656
  if (httpConfig.stateless) {
2586
2657
  this.#logger.info(
2587
2658
  `[FastMCP info] Starting server in stateless mode on HTTP Stream at ${protocol}://${httpConfig.host}:${httpConfig.port}${streamEndpoint}`
@@ -2589,9 +2660,13 @@ var FastMCP = class extends FastMCPEventEmitter {
2589
2660
  const authenticate = this.#authenticate ? this.#memoizedAuthenticate() : void 0;
2590
2661
  this.#httpStreamServer = await _mcpproxy.startHTTPServer.call(void 0, {
2591
2662
  ...authenticate ? { authenticate } : {},
2592
- beforeDispatch: ({ message, server }) => this.#answerScopeChallenge(message, server),
2593
- cors: httpConfig.cors,
2663
+ beforeDispatch: ({ message, request, server }) => _nullishCoalesce(this.#originRefusal(request, originPolicy), () => ( this.#answerScopeChallenge(message, server))),
2664
+ cors: originPolicy.cors,
2594
2665
  createServer: async (request) => {
2666
+ const refusal = this.#originRefusal(request, originPolicy);
2667
+ if (refusal) {
2668
+ throw refusal;
2669
+ }
2595
2670
  let auth;
2596
2671
  if (authenticate) {
2597
2672
  auth = this.#requireAuthenticated(await authenticate(request));
@@ -2638,9 +2713,13 @@ var FastMCP = class extends FastMCPEventEmitter {
2638
2713
  const authenticate = this.#authenticate ? this.#memoizedAuthenticate() : void 0;
2639
2714
  this.#httpStreamServer = await _mcpproxy.startHTTPServer.call(void 0, {
2640
2715
  ...authenticate ? { authenticate } : {},
2641
- beforeDispatch: ({ message, server }) => this.#answerScopeChallenge(message, server),
2642
- cors: httpConfig.cors,
2716
+ beforeDispatch: ({ message, request, server }) => _nullishCoalesce(this.#originRefusal(request, originPolicy), () => ( this.#answerScopeChallenge(message, server))),
2717
+ cors: originPolicy.cors,
2643
2718
  createServer: async (request) => {
2719
+ const refusal = this.#originRefusal(request, originPolicy);
2720
+ if (refusal) {
2721
+ throw refusal;
2722
+ }
2644
2723
  let auth;
2645
2724
  if (authenticate) {
2646
2725
  auth = this.#requireAuthenticated(await authenticate(request));
@@ -3412,6 +3491,40 @@ var FastMCP = class extends FastMCPEventEmitter {
3412
3491
  });
3413
3492
  }
3414
3493
  }
3494
+ /**
3495
+ * The 403 MCP asks for, for a request a browser sent on behalf of a page
3496
+ * the server does not answer (see `resolveOriginPolicy`). Checked before a
3497
+ * session is created, and for every message posted to one that exists. A
3498
+ * request without an `Origin` header does not come from a page, and passes.
3499
+ */
3500
+ #originRefusal(request, policy) {
3501
+ const header = request.headers.origin;
3502
+ if (!policy.allows || !header) {
3503
+ return void 0;
3504
+ }
3505
+ const origin = serializeOrigin(header);
3506
+ if (policy.allows(origin)) {
3507
+ return void 0;
3508
+ }
3509
+ const refused = printable(origin.slice(0, 200));
3510
+ if (!this.#refusedOrigins.has(refused) && this.#refusedOrigins.size < 50) {
3511
+ this.#refusedOrigins.add(refused);
3512
+ this.#logger.warn(
3513
+ `[FastMCP warning] Refused a request from the origin ${refused}. ${policy.refusal}`
3514
+ );
3515
+ }
3516
+ return new Response(
3517
+ JSON.stringify({
3518
+ error: {
3519
+ code: -32e3,
3520
+ message: `Forbidden: the origin ${refused} is not allowed`
3521
+ },
3522
+ id: null,
3523
+ jsonrpc: "2.0"
3524
+ }),
3525
+ { headers: { "Content-Type": "application/json" }, status: 403 }
3526
+ );
3527
+ }
3415
3528
  #parseRuntimeConfig(overrides) {
3416
3529
  const args = process.argv.slice(2);
3417
3530
  const getArg = (name) => {
@@ -3578,4 +3691,4 @@ var FastMCP = class extends FastMCPEventEmitter {
3578
3691
 
3579
3692
 
3580
3693
  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;
3581
- //# sourceMappingURL=chunk-MT5SJOZ5.cjs.map
3694
+ //# sourceMappingURL=chunk-UULT6NOS.cjs.map