fastmcp 4.26.0 → 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.
Files changed (36) hide show
  1. package/README.md +16 -6
  2. package/dist/FastMCP.cjs +3 -3
  3. package/dist/FastMCP.d.cts +2 -2
  4. package/dist/FastMCP.d.ts +2 -2
  5. package/dist/FastMCP.js +2 -2
  6. package/dist/{OAuthProvider-CPC9zG96.d.cts → OAuthProvider-B7VDZGyx.d.cts} +55 -3
  7. package/dist/{OAuthProvider-CPC9zG96.d.ts → OAuthProvider-B7VDZGyx.d.ts} +55 -3
  8. package/dist/auth/index.cjs +2 -2
  9. package/dist/auth/index.d.cts +17 -3
  10. package/dist/auth/index.d.ts +17 -3
  11. package/dist/auth/index.js +1 -1
  12. package/dist/{chunk-LUGELV2V.js → chunk-ASOZUCE2.js} +180 -36
  13. package/dist/chunk-ASOZUCE2.js.map +1 -0
  14. package/dist/{chunk-AKHG27NY.cjs → chunk-HVKGDRTL.cjs} +286 -66
  15. package/dist/chunk-HVKGDRTL.cjs.map +1 -0
  16. package/dist/{chunk-ZHTH5HQD.cjs → chunk-UULT6NOS.cjs} +212 -68
  17. package/dist/chunk-UULT6NOS.cjs.map +1 -0
  18. package/dist/{chunk-3VYVXSBB.js → chunk-W6P57SNV.js} +272 -52
  19. package/dist/chunk-W6P57SNV.js.map +1 -0
  20. package/dist/edge/index.cjs +110 -16
  21. package/dist/edge/index.cjs.map +1 -1
  22. package/dist/edge/index.d.cts +7 -2
  23. package/dist/edge/index.d.ts +7 -2
  24. package/dist/edge/index.js +110 -16
  25. package/dist/edge/index.js.map +1 -1
  26. package/dist/examples/custom-routes.cjs +3 -3
  27. package/dist/examples/custom-routes.js +2 -2
  28. package/dist/openapi/index.cjs +8 -8
  29. package/dist/openapi/index.d.cts +1 -1
  30. package/dist/openapi/index.d.ts +1 -1
  31. package/dist/openapi/index.js +2 -2
  32. package/package.json +1 -1
  33. package/dist/chunk-3VYVXSBB.js.map +0 -1
  34. package/dist/chunk-AKHG27NY.cjs.map +0 -1
  35. package/dist/chunk-LUGELV2V.js.map +0 -1
  36. package/dist/chunk-ZHTH5HQD.cjs.map +0 -1
@@ -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 _chunkAKHG27NYcjs = require('./chunk-AKHG27NY.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 _chunkAKHG27NYcjs.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 _chunkAKHG27NYcjs.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 _chunkAKHG27NYcjs.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
  );
@@ -697,7 +697,7 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
697
697
  this.setupCompleteHandlers();
698
698
  if (supportsTools) {
699
699
  this.setupToolHandlers(
700
- toolsVisibleTo(tools, this.#auth, this.#authRequired)
700
+ toolsVisibleTo(tools, this.#auth, this.#authRequired, this.#logger)
701
701
  );
702
702
  }
703
703
  if (resources.length || resourcesTemplates.length) {
@@ -839,7 +839,7 @@ ${error instanceof Error ? error.stack : JSON.stringify(error)}`
839
839
  }
840
840
  this.#tools = tools;
841
841
  this.setupToolHandlers(
842
- toolsVisibleTo(tools, this.#auth, this.#authRequired)
842
+ toolsVisibleTo(tools, this.#auth, this.#authRequired, this.#logger)
843
843
  );
844
844
  this.triggerListChangedNotification("notifications/tools/list_changed");
845
845
  }
@@ -862,7 +862,12 @@ ${error instanceof Error ? error.stack : JSON.stringify(error)}`
862
862
  */
863
863
  updateAuth(auth) {
864
864
  this.#auth = auth;
865
- const tools = toolsVisibleTo(this.#tools, auth, this.#authRequired);
865
+ const tools = toolsVisibleTo(
866
+ this.#tools,
867
+ auth,
868
+ this.#authRequired,
869
+ this.#logger
870
+ );
866
871
  if (tools.length !== this.#visibleTools.length || tools.some((tool, index) => tool !== this.#visibleTools[index])) {
867
872
  this.setupToolHandlers(tools);
868
873
  this.triggerListChangedNotification("notifications/tools/list_changed");
@@ -1934,6 +1939,31 @@ function convertObjectToSnakeCase(obj) {
1934
1939
  }
1935
1940
  return result;
1936
1941
  }
1942
+ function cookieHeaders(req) {
1943
+ return req.headers.cookie ? { cookie: req.headers.cookie } : {};
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
+ }
1937
1967
  function isStreamableHttpTransport(transport) {
1938
1968
  return "handleRequest" in transport && typeof transport.handleRequest === "function";
1939
1969
  }
@@ -1999,7 +2029,7 @@ function parseBasicAuthHeader(authHeader) {
1999
2029
  clientId: decodeURIComponent(credentials.slice(0, separator)),
2000
2030
  clientSecret: decodeURIComponent(credentials.slice(separator + 1))
2001
2031
  };
2002
- } catch (e6) {
2032
+ } catch (e8) {
2003
2033
  return "malformed";
2004
2034
  }
2005
2035
  }
@@ -2036,7 +2066,7 @@ function protectedResourceMetadataUrl(resource) {
2036
2066
  let url;
2037
2067
  try {
2038
2068
  url = new URL(resource);
2039
- } catch (e7) {
2069
+ } catch (e9) {
2040
2070
  return `${resource}/.well-known/oauth-protected-resource`;
2041
2071
  }
2042
2072
  const path = url.pathname === "/" ? "" : url.pathname;
@@ -2058,6 +2088,60 @@ function grantedScopes(auth) {
2058
2088
  const values = Array.isArray(scopes) ? scopes : scopes instanceof Set ? [...scopes] : [];
2059
2089
  return values.filter((scope) => typeof scope === "string");
2060
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
+ }
2123
+ async function sendOAuthProxyResponse(res, response) {
2124
+ const body = await response.text();
2125
+ const headers = {};
2126
+ response.headers.forEach((value, key) => {
2127
+ if (key.toLowerCase() !== "set-cookie") {
2128
+ headers[key] = value;
2129
+ }
2130
+ });
2131
+ const setCookies = response.headers.getSetCookie();
2132
+ if (setCookies.length > 0) {
2133
+ headers["set-cookie"] = setCookies;
2134
+ }
2135
+ res.writeHead(response.status, headers).end(body);
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
+ }
2061
2145
  function stripBasePath(path, basePath) {
2062
2146
  if (!basePath) {
2063
2147
  return path;
@@ -2070,12 +2154,32 @@ function stripBasePath(path, basePath) {
2070
2154
  }
2071
2155
  return null;
2072
2156
  }
2073
- function toolsVisibleTo(tools, auth, authRequired) {
2074
- if (auth) {
2075
- return tools.filter(
2076
- (tool) => tool.canAccess ? tool.canAccess(auth) : true
2157
+ var toolsWithInvalidCanAccess = /* @__PURE__ */ new WeakSet();
2158
+ function toolAdmits(tool, auth, logger) {
2159
+ if (!tool.canAccess) {
2160
+ return true;
2161
+ }
2162
+ const admitted = tool.canAccess(auth);
2163
+ if (typeof admitted === "boolean") {
2164
+ return admitted;
2165
+ }
2166
+ const isPromise = typeof _optionalChain([admitted, 'optionalAccess', _71 => _71.then]) === "function";
2167
+ if (isPromise) {
2168
+ Promise.resolve(admitted).catch(() => {
2169
+ });
2170
+ }
2171
+ if (admitted && !toolsWithInvalidCanAccess.has(tool)) {
2172
+ toolsWithInvalidCanAccess.add(tool);
2173
+ logger.warn(
2174
+ `[FastMCP warning] Tool '${tool.name}' is hidden: its canAccess returned ${isPromise ? "a Promise" : "a non-boolean value"}. canAccess must return a boolean synchronously.`
2077
2175
  );
2078
2176
  }
2177
+ return false;
2178
+ }
2179
+ function toolsVisibleTo(tools, auth, authRequired, logger) {
2180
+ if (auth) {
2181
+ return tools.filter((tool) => toolAdmits(tool, auth, logger));
2182
+ }
2079
2183
  return authRequired ? tools.filter((tool) => !tool.canAccess) : tools;
2080
2184
  }
2081
2185
  var FastMCPEventEmitterBase = _events.EventEmitter;
@@ -2116,6 +2220,11 @@ var FastMCP = class extends FastMCPEventEmitter {
2116
2220
  #prompts = [];
2117
2221
  /** The auth provider's base URL, when it supplied the OAuth config. */
2118
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();
2119
2228
  #resources = [];
2120
2229
  #resourcesTemplates = [];
2121
2230
  #serverState = "stopped" /* Stopped */;
@@ -2540,6 +2649,10 @@ var FastMCP = class extends FastMCPEventEmitter {
2540
2649
  httpConfig.endpoint
2541
2650
  );
2542
2651
  this.#useEndpointAsResource(httpConfig.endpoint);
2652
+ const originPolicy = resolveOriginPolicy(
2653
+ httpConfig.host,
2654
+ httpConfig.cors
2655
+ );
2543
2656
  if (httpConfig.stateless) {
2544
2657
  this.#logger.info(
2545
2658
  `[FastMCP info] Starting server in stateless mode on HTTP Stream at ${protocol}://${httpConfig.host}:${httpConfig.port}${streamEndpoint}`
@@ -2547,9 +2660,13 @@ var FastMCP = class extends FastMCPEventEmitter {
2547
2660
  const authenticate = this.#authenticate ? this.#memoizedAuthenticate() : void 0;
2548
2661
  this.#httpStreamServer = await _mcpproxy.startHTTPServer.call(void 0, {
2549
2662
  ...authenticate ? { authenticate } : {},
2550
- beforeDispatch: ({ message, server }) => this.#answerScopeChallenge(message, server),
2551
- cors: httpConfig.cors,
2663
+ beforeDispatch: ({ message, request, server }) => _nullishCoalesce(this.#originRefusal(request, originPolicy), () => ( this.#answerScopeChallenge(message, server))),
2664
+ cors: originPolicy.cors,
2552
2665
  createServer: async (request) => {
2666
+ const refusal = this.#originRefusal(request, originPolicy);
2667
+ if (refusal) {
2668
+ throw refusal;
2669
+ }
2553
2670
  let auth;
2554
2671
  if (authenticate) {
2555
2672
  auth = this.#requireAuthenticated(await authenticate(request));
@@ -2596,9 +2713,13 @@ var FastMCP = class extends FastMCPEventEmitter {
2596
2713
  const authenticate = this.#authenticate ? this.#memoizedAuthenticate() : void 0;
2597
2714
  this.#httpStreamServer = await _mcpproxy.startHTTPServer.call(void 0, {
2598
2715
  ...authenticate ? { authenticate } : {},
2599
- beforeDispatch: ({ message, server }) => this.#answerScopeChallenge(message, server),
2600
- cors: httpConfig.cors,
2716
+ beforeDispatch: ({ message, request, server }) => _nullishCoalesce(this.#originRefusal(request, originPolicy), () => ( this.#answerScopeChallenge(message, server))),
2717
+ cors: originPolicy.cors,
2601
2718
  createServer: async (request) => {
2719
+ const refusal = this.#originRefusal(request, originPolicy);
2720
+ if (refusal) {
2721
+ throw refusal;
2722
+ }
2602
2723
  let auth;
2603
2724
  if (authenticate) {
2604
2725
  auth = this.#requireAuthenticated(await authenticate(request));
@@ -2697,9 +2818,9 @@ var FastMCP = class extends FastMCPEventEmitter {
2697
2818
  const originalOnClose = transport.onclose;
2698
2819
  transport.onclose = () => {
2699
2820
  closed = true;
2700
- _optionalChain([onClose, 'optionalCall', _71 => _71()]);
2821
+ _optionalChain([onClose, 'optionalCall', _72 => _72()]);
2701
2822
  this.#removeSession(session);
2702
- _optionalChain([originalOnClose, 'optionalCall', _72 => _72()]);
2823
+ _optionalChain([originalOnClose, 'optionalCall', _73 => _73()]);
2703
2824
  };
2704
2825
  await session.connect(transport);
2705
2826
  if (closed) {
@@ -2726,7 +2847,7 @@ var FastMCP = class extends FastMCPEventEmitter {
2726
2847
  */
2727
2848
  #createInsufficientScopeResponse(challenge, id) {
2728
2849
  const oauth = this.#options.oauth;
2729
- const resource = _optionalChain([oauth, 'optionalAccess', _73 => _73.enabled]) ? _optionalChain([oauth, 'access', _74 => _74.protectedResource, 'optionalAccess', _75 => _75.resource]) : void 0;
2850
+ const resource = _optionalChain([oauth, 'optionalAccess', _74 => _74.enabled]) ? _optionalChain([oauth, 'access', _75 => _75.protectedResource, 'optionalAccess', _76 => _76.resource]) : void 0;
2730
2851
  const wwwAuthenticateParts = [
2731
2852
  'error="insufficient_scope"',
2732
2853
  `scope="${challenge.scopes.filter((scope) => SCOPE_TOKEN.test(scope)).join(" ")}"`
@@ -2812,7 +2933,7 @@ var FastMCP = class extends FastMCPEventEmitter {
2812
2933
  */
2813
2934
  #createUnauthorizedResponse(message) {
2814
2935
  const oauth = this.#options.oauth;
2815
- const resource = _optionalChain([oauth, 'optionalAccess', _76 => _76.enabled]) ? _optionalChain([oauth, 'access', _77 => _77.protectedResource, 'optionalAccess', _78 => _78.resource]) : void 0;
2936
+ const resource = _optionalChain([oauth, 'optionalAccess', _77 => _77.enabled]) ? _optionalChain([oauth, 'access', _78 => _78.protectedResource, 'optionalAccess', _79 => _79.resource]) : void 0;
2816
2937
  const wwwAuthenticateParts = [
2817
2938
  'error="invalid_token"',
2818
2939
  `error_description="${message.replace(/"/g, '\\"')}"`
@@ -2951,7 +3072,7 @@ var FastMCP = class extends FastMCPEventEmitter {
2951
3072
  }
2952
3073
  }
2953
3074
  const oauthConfig = this.#options.oauth;
2954
- if (_optionalChain([oauthConfig, 'optionalAccess', _79 => _79.enabled]) && req.method === "GET") {
3075
+ if (_optionalChain([oauthConfig, 'optionalAccess', _80 => _80.enabled]) && req.method === "GET") {
2955
3076
  const url2 = new URL(req.url || "", `http://${host}`);
2956
3077
  const authorizationServerMetadataPath = joinPaths(
2957
3078
  "",
@@ -2985,8 +3106,8 @@ var FastMCP = class extends FastMCPEventEmitter {
2985
3106
  }
2986
3107
  }
2987
3108
  }
2988
- const oauthProxy = _optionalChain([oauthConfig, 'optionalAccess', _80 => _80.proxy]);
2989
- if (oauthProxy && _optionalChain([oauthConfig, 'optionalAccess', _81 => _81.enabled])) {
3109
+ const oauthProxy = _optionalChain([oauthConfig, 'optionalAccess', _81 => _81.proxy]);
3110
+ if (oauthProxy && _optionalChain([oauthConfig, 'optionalAccess', _82 => _82.enabled])) {
2990
3111
  const url2 = new URL(req.url || "", `http://${host}`);
2991
3112
  const oauthPath = basePathRelativePath;
2992
3113
  try {
@@ -3039,7 +3160,7 @@ var FastMCP = class extends FastMCPEventEmitter {
3039
3160
  const statusCode = error.statusCode || 400;
3040
3161
  res.writeHead(statusCode, OAUTH_CREDENTIAL_RESPONSE_HEADERS).end(
3041
3162
  JSON.stringify(
3042
- _optionalChain([error, 'access', _82 => _82.toJSON, 'optionalCall', _83 => _83()]) || {
3163
+ _optionalChain([error, 'access', _83 => _83.toJSON, 'optionalCall', _84 => _84()]) || {
3043
3164
  error: "invalid_request"
3044
3165
  }
3045
3166
  )
@@ -3054,19 +3175,17 @@ var FastMCP = class extends FastMCPEventEmitter {
3054
3175
  try {
3055
3176
  const params = Object.fromEntries(url2.searchParams.entries());
3056
3177
  const response = await oauthProxy.authorize(
3057
- params
3178
+ params,
3179
+ // The consent cookie this browser already holds, if any
3180
+ new Request(`http://${host}${req.url}`, {
3181
+ headers: cookieHeaders(req)
3182
+ })
3058
3183
  );
3059
- const location = response.headers.get("Location");
3060
- if (location) {
3061
- res.writeHead(response.status, { Location: location }).end();
3062
- } else {
3063
- const html = await response.text();
3064
- res.writeHead(response.status, { "Content-Type": "text/html" }).end(html);
3065
- }
3184
+ await sendOAuthProxyResponse(res, response);
3066
3185
  } catch (error) {
3067
3186
  res.writeHead(400, { "Content-Type": "application/json" }).end(
3068
3187
  JSON.stringify(
3069
- _optionalChain([error, 'access', _84 => _84.toJSON, 'optionalCall', _85 => _85()]) || {
3188
+ _optionalChain([error, 'access', _85 => _85.toJSON, 'optionalCall', _86 => _86()]) || {
3070
3189
  error: "invalid_request"
3071
3190
  }
3072
3191
  )
@@ -3076,19 +3195,15 @@ var FastMCP = class extends FastMCPEventEmitter {
3076
3195
  }
3077
3196
  if (req.method === "GET" && oauthPath === "/oauth/callback") {
3078
3197
  try {
3079
- const mockRequest = new Request(`http://${host}${req.url}`);
3198
+ const mockRequest = new Request(`http://${host}${req.url}`, {
3199
+ headers: cookieHeaders(req)
3200
+ });
3080
3201
  const response = await oauthProxy.handleCallback(mockRequest);
3081
- const location = response.headers.get("Location");
3082
- if (location) {
3083
- res.writeHead(response.status, { Location: location }).end();
3084
- } else {
3085
- const text = await response.text();
3086
- res.writeHead(response.status).end(text);
3087
- }
3202
+ await sendOAuthProxyResponse(res, response);
3088
3203
  } catch (error) {
3089
3204
  res.writeHead(400, { "Content-Type": "application/json" }).end(
3090
3205
  JSON.stringify(
3091
- _optionalChain([error, 'access', _86 => _86.toJSON, 'optionalCall', _87 => _87()]) || {
3206
+ _optionalChain([error, 'access', _87 => _87.toJSON, 'optionalCall', _88 => _88()]) || {
3092
3207
  error: "server_error"
3093
3208
  }
3094
3209
  )
@@ -3141,23 +3256,18 @@ var FastMCP = class extends FastMCPEventEmitter {
3141
3256
  {
3142
3257
  body: Buffer.concat(bodyChunks).toString("utf8"),
3143
3258
  headers: {
3259
+ ...cookieHeaders(req),
3144
3260
  "Content-Type": "application/x-www-form-urlencoded"
3145
3261
  },
3146
3262
  method: "POST"
3147
3263
  }
3148
3264
  );
3149
3265
  const response = await oauthProxy.handleConsent(mockRequest);
3150
- const location = response.headers.get("Location");
3151
- if (location) {
3152
- res.writeHead(response.status, { Location: location }).end();
3153
- } else {
3154
- const text = await response.text();
3155
- res.writeHead(response.status).end(text);
3156
- }
3266
+ await sendOAuthProxyResponse(res, response);
3157
3267
  } catch (error) {
3158
3268
  res.writeHead(400, { "Content-Type": "application/json" }).end(
3159
3269
  JSON.stringify(
3160
- _optionalChain([error, 'access', _88 => _88.toJSON, 'optionalCall', _89 => _89()]) || {
3270
+ _optionalChain([error, 'access', _89 => _89.toJSON, 'optionalCall', _90 => _90()]) || {
3161
3271
  error: "server_error"
3162
3272
  }
3163
3273
  )
@@ -3272,7 +3382,7 @@ var FastMCP = class extends FastMCPEventEmitter {
3272
3382
  }
3273
3383
  res.writeHead(200, OAUTH_CREDENTIAL_RESPONSE_HEADERS).end(JSON.stringify(response));
3274
3384
  } catch (error) {
3275
- const body = _optionalChain([error, 'access', _90 => _90.toJSON, 'optionalCall', _91 => _91()]) || {
3385
+ const body = _optionalChain([error, 'access', _91 => _91.toJSON, 'optionalCall', _92 => _92()]) || {
3276
3386
  error: "invalid_request"
3277
3387
  };
3278
3388
  if (body.error === "invalid_client") {
@@ -3302,7 +3412,7 @@ var FastMCP = class extends FastMCPEventEmitter {
3302
3412
  * regardless (RFC 7235), so no config is needed just to get the header.
3303
3413
  */
3304
3414
  #httpStreamOAuthConfig() {
3305
- const resource = _optionalChain([this, 'access', _92 => _92.#options, 'access', _93 => _93.oauth, 'optionalAccess', _94 => _94.enabled]) ? _optionalChain([this, 'access', _95 => _95.#options, 'access', _96 => _96.oauth, 'access', _97 => _97.protectedResource, 'optionalAccess', _98 => _98.resource]) : void 0;
3415
+ const resource = _optionalChain([this, 'access', _93 => _93.#options, 'access', _94 => _94.oauth, 'optionalAccess', _95 => _95.enabled]) ? _optionalChain([this, 'access', _96 => _96.#options, 'access', _97 => _97.oauth, 'access', _98 => _98.protectedResource, 'optionalAccess', _99 => _99.resource]) : void 0;
3306
3416
  if (!resource) {
3307
3417
  return {};
3308
3418
  }
@@ -3381,6 +3491,40 @@ var FastMCP = class extends FastMCPEventEmitter {
3381
3491
  });
3382
3492
  }
3383
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
+ }
3384
3528
  #parseRuntimeConfig(overrides) {
3385
3529
  const args = process.argv.slice(2);
3386
3530
  const getArg = (name) => {
@@ -3408,25 +3552,25 @@ var FastMCP = class extends FastMCPEventEmitter {
3408
3552
  const envBasePath = process.env.FASTMCP_BASE_PATH;
3409
3553
  const envStateless = process.env.FASTMCP_STATELESS;
3410
3554
  const envHost = process.env.FASTMCP_HOST;
3411
- const transportType = _optionalChain([overrides, 'optionalAccess', _99 => _99.transportType]) || parseTransportSetting(transportArg, "--transport") || parseTransportSetting(envTransport, "FASTMCP_TRANSPORT") || "stdio";
3555
+ const transportType = _optionalChain([overrides, 'optionalAccess', _100 => _100.transportType]) || parseTransportSetting(transportArg, "--transport") || parseTransportSetting(envTransport, "FASTMCP_TRANSPORT") || "stdio";
3412
3556
  if (transportType === "httpStream") {
3413
3557
  const port = parseInt(
3414
- _optionalChain([overrides, 'optionalAccess', _100 => _100.httpStream, 'optionalAccess', _101 => _101.port, 'optionalAccess', _102 => _102.toString, 'call', _103 => _103()]) || portArg || envPort || "8080"
3558
+ _optionalChain([overrides, 'optionalAccess', _101 => _101.httpStream, 'optionalAccess', _102 => _102.port, 'optionalAccess', _103 => _103.toString, 'call', _104 => _104()]) || portArg || envPort || "8080"
3415
3559
  );
3416
- const host = _optionalChain([overrides, 'optionalAccess', _104 => _104.httpStream, 'optionalAccess', _105 => _105.host]) || hostArg || envHost || "localhost";
3417
- const endpoint = _optionalChain([overrides, 'optionalAccess', _106 => _106.httpStream, 'optionalAccess', _107 => _107.endpoint]) || endpointArg || envEndpoint || "/mcp";
3560
+ const host = _optionalChain([overrides, 'optionalAccess', _105 => _105.httpStream, 'optionalAccess', _106 => _106.host]) || hostArg || envHost || "localhost";
3561
+ const endpoint = _optionalChain([overrides, 'optionalAccess', _107 => _107.httpStream, 'optionalAccess', _108 => _108.endpoint]) || endpointArg || envEndpoint || "/mcp";
3418
3562
  const basePath = normalizeBasePath(
3419
- _optionalChain([overrides, 'optionalAccess', _108 => _108.httpStream, 'optionalAccess', _109 => _109.basePath]) || basePathArg || envBasePath
3563
+ _optionalChain([overrides, 'optionalAccess', _109 => _109.httpStream, 'optionalAccess', _110 => _110.basePath]) || basePathArg || envBasePath
3420
3564
  );
3421
- const enableJsonResponse = _optionalChain([overrides, 'optionalAccess', _110 => _110.httpStream, 'optionalAccess', _111 => _111.enableJsonResponse]) || false;
3422
- const stateless = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([overrides, 'optionalAccess', _112 => _112.httpStream, 'optionalAccess', _113 => _113.stateless]), () => ( // A bare `--stateless` means `--stateless true`.
3565
+ const enableJsonResponse = _optionalChain([overrides, 'optionalAccess', _111 => _111.httpStream, 'optionalAccess', _112 => _112.enableJsonResponse]) || false;
3566
+ const stateless = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([overrides, 'optionalAccess', _113 => _113.httpStream, 'optionalAccess', _114 => _114.stateless]), () => ( // A bare `--stateless` means `--stateless true`.
3423
3567
  (statelessArg === "" ? true : parseBooleanSetting(statelessArg, "--stateless")))), () => ( parseBooleanSetting(envStateless, "FASTMCP_STATELESS"))), () => ( false));
3424
- const cors = _optionalChain([overrides, 'optionalAccess', _114 => _114.httpStream, 'optionalAccess', _115 => _115.cors]);
3425
- const eventStore = _optionalChain([overrides, 'optionalAccess', _116 => _116.httpStream, 'optionalAccess', _117 => _117.eventStore]);
3426
- const sseEndpoint = _optionalChain([overrides, 'optionalAccess', _118 => _118.httpStream, 'optionalAccess', _119 => _119.sseEndpoint]);
3427
- const sslCa = _optionalChain([overrides, 'optionalAccess', _120 => _120.httpStream, 'optionalAccess', _121 => _121.sslCa]);
3428
- const sslCert = _optionalChain([overrides, 'optionalAccess', _122 => _122.httpStream, 'optionalAccess', _123 => _123.sslCert]);
3429
- const sslKey = _optionalChain([overrides, 'optionalAccess', _124 => _124.httpStream, 'optionalAccess', _125 => _125.sslKey]);
3568
+ const cors = _optionalChain([overrides, 'optionalAccess', _115 => _115.httpStream, 'optionalAccess', _116 => _116.cors]);
3569
+ const eventStore = _optionalChain([overrides, 'optionalAccess', _117 => _117.httpStream, 'optionalAccess', _118 => _118.eventStore]);
3570
+ const sseEndpoint = _optionalChain([overrides, 'optionalAccess', _119 => _119.httpStream, 'optionalAccess', _120 => _120.sseEndpoint]);
3571
+ const sslCa = _optionalChain([overrides, 'optionalAccess', _121 => _121.httpStream, 'optionalAccess', _122 => _122.sslCa]);
3572
+ const sslCert = _optionalChain([overrides, 'optionalAccess', _123 => _123.httpStream, 'optionalAccess', _124 => _124.sslCert]);
3573
+ const sslKey = _optionalChain([overrides, 'optionalAccess', _125 => _125.httpStream, 'optionalAccess', _126 => _126.sslKey]);
3430
3574
  return {
3431
3575
  httpStream: {
3432
3576
  basePath,
@@ -3518,7 +3662,7 @@ var FastMCP = class extends FastMCPEventEmitter {
3518
3662
  */
3519
3663
  #useEndpointAsResource(endpoint) {
3520
3664
  const oauth = this.#options.oauth;
3521
- if (this.#providerResourceBase === void 0 || !_optionalChain([oauth, 'optionalAccess', _126 => _126.protectedResource]))
3665
+ if (this.#providerResourceBase === void 0 || !_optionalChain([oauth, 'optionalAccess', _127 => _127.protectedResource]))
3522
3666
  return;
3523
3667
  this.#options = {
3524
3668
  ...this.#options,
@@ -3547,4 +3691,4 @@ var FastMCP = class extends FastMCPEventEmitter {
3547
3691
 
3548
3692
 
3549
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;
3550
- //# sourceMappingURL=chunk-ZHTH5HQD.cjs.map
3694
+ //# sourceMappingURL=chunk-UULT6NOS.cjs.map