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
  import {
2
2
  cancelResponseBody
3
- } from "./chunk-3VYVXSBB.js";
3
+ } from "./chunk-W6P57SNV.js";
4
4
  import {
5
5
  objectRootSchema,
6
6
  strictInputSchema,
@@ -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 {
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 {
1964
+ return false;
1965
+ }
1966
+ }
1937
1967
  function isStreamableHttpTransport(transport) {
1938
1968
  return "handleRequest" in transport && typeof transport.handleRequest === "function";
1939
1969
  }
@@ -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 {
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 admitted?.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 = 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 startHTTPServer({
2549
2662
  ...authenticate ? { authenticate } : {},
2550
- beforeDispatch: ({ message, server }) => this.#answerScopeChallenge(message, server),
2551
- cors: httpConfig.cors,
2663
+ beforeDispatch: ({ message, request, server }) => 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 startHTTPServer({
2598
2715
  ...authenticate ? { authenticate } : {},
2599
- beforeDispatch: ({ message, server }) => this.#answerScopeChallenge(message, server),
2600
- cors: httpConfig.cors,
2716
+ beforeDispatch: ({ message, request, server }) => 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));
@@ -3054,15 +3175,13 @@ 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(
@@ -3076,15 +3195,11 @@ 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(
@@ -3141,19 +3256,14 @@ 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(
@@ -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) => {
@@ -3547,4 +3691,4 @@ export {
3547
3691
  FastMCPSession,
3548
3692
  FastMCP
3549
3693
  };
3550
- //# sourceMappingURL=chunk-LUGELV2V.js.map
3694
+ //# sourceMappingURL=chunk-ASOZUCE2.js.map