fastmcp 4.13.0 → 4.14.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.
@@ -355,6 +355,8 @@ function assertToolSchemas(tool) {
355
355
  assertStandardSchema(tool.name, "outputSchema", tool.outputSchema);
356
356
  }
357
357
  }
358
+ var STREAM_KEEPALIVE_LOGGER = "fastmcp-keepalive";
359
+ var STREAM_KEEPALIVE_DEFAULT_INTERVAL_MS = 2e4;
358
360
  var TextContentZodSchema = z.object({
359
361
  /**
360
362
  * The text content of the message.
@@ -483,6 +485,7 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
483
485
  * instance — so capabilities can never be inferred here.
484
486
  */
485
487
  #stateless;
488
+ #streamKeepaliveConfig;
486
489
  /**
487
490
  * Resource URIs the connected client has subscribed to via
488
491
  * `resources/subscribe`. Used to scope `notifications/resources/updated`
@@ -503,6 +506,7 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
503
506
  roots,
504
507
  sessionId,
505
508
  stateless = false,
509
+ streamKeepalive,
506
510
  tools,
507
511
  transportType,
508
512
  utils,
@@ -516,6 +520,7 @@ var FastMCPSession = class extends FastMCPSessionEventEmitter {
516
520
  this.#rootsConfig = roots;
517
521
  this.#sessionId = sessionId;
518
522
  this.#stateless = stateless;
523
+ this.#streamKeepaliveConfig = streamKeepalive;
519
524
  this.#needsEventLoopFlush = transportType === "httpStream";
520
525
  if (tools.length) {
521
526
  this.#capabilities.tools = {};
@@ -843,6 +848,44 @@ ${error instanceof Error ? error.stack : JSON.stringify(error)}`
843
848
  logLevel: pingConfig.logLevel || "debug"
844
849
  };
845
850
  }
851
+ /**
852
+ * Periodically writes to the response stream of an in-flight tool call, so an
853
+ * idle-connection timeout (proxy, load balancer) does not close it while a
854
+ * long-running tool produces no output of its own.
855
+ *
856
+ * The notification is related to the tool call, so it travels on that
857
+ * request's own stream, which is the only server-to-client route that exists
858
+ * when running stateless.
859
+ *
860
+ * @returns a function that stops the keepalive.
861
+ */
862
+ #startStreamKeepalive(extra, toolName) {
863
+ const config = this.#streamKeepaliveConfig;
864
+ if (!config?.enabled) {
865
+ return () => {
866
+ };
867
+ }
868
+ const intervalMs = config.intervalMs && config.intervalMs > 0 ? config.intervalMs : STREAM_KEEPALIVE_DEFAULT_INTERVAL_MS;
869
+ const timer = setInterval(() => {
870
+ extra.sendNotification({
871
+ method: "notifications/message",
872
+ params: {
873
+ data: { message: `keepalive while '${toolName}' is running` },
874
+ level: config.logLevel ?? "debug",
875
+ logger: STREAM_KEEPALIVE_LOGGER
876
+ }
877
+ }).catch((error) => {
878
+ this.#logger.debug(
879
+ `[FastMCP debug] stream keepalive for '${toolName}' failed:`,
880
+ error instanceof Error ? error.message : String(error)
881
+ );
882
+ });
883
+ }, intervalMs);
884
+ timer.unref?.();
885
+ const stop = () => clearInterval(timer);
886
+ extra.signal?.addEventListener("abort", stop, { once: true });
887
+ return stop;
888
+ }
846
889
  async #validateStructuredContent(tool, value, toolName) {
847
890
  if (!tool.outputSchema) {
848
891
  return value;
@@ -1260,169 +1303,178 @@ ${error instanceof Error ? error.stack : JSON.stringify(error)}`
1260
1303
  tools: cachedToolsList
1261
1304
  };
1262
1305
  });
1263
- this.#server.setRequestHandler(CallToolRequestSchema, async (request) => {
1264
- const tool = toolsMap.get(request.params.name);
1265
- if (!tool) {
1266
- throw new McpError(
1267
- ErrorCode.MethodNotFound,
1268
- `Unknown tool: ${request.params.name}`
1269
- );
1270
- }
1271
- let args = void 0;
1272
- if (tool.parameters) {
1273
- const parsed = await tool.parameters["~standard"].validate(
1274
- request.params.arguments
1275
- );
1276
- if (parsed.issues) {
1277
- const friendlyErrors = this.#formatSchemaIssues(parsed.issues);
1306
+ this.#server.setRequestHandler(
1307
+ CallToolRequestSchema,
1308
+ async (request, extra) => {
1309
+ const tool = toolsMap.get(request.params.name);
1310
+ if (!tool) {
1278
1311
  throw new McpError(
1279
- ErrorCode.InvalidParams,
1280
- `Tool '${request.params.name}' parameter validation failed: ${friendlyErrors}. Please check the parameter types and values according to the tool's schema.`
1312
+ ErrorCode.MethodNotFound,
1313
+ `Unknown tool: ${request.params.name}`
1281
1314
  );
1282
1315
  }
1283
- args = parsed.value;
1284
- }
1285
- const progressToken = request.params?._meta?.progressToken;
1286
- let result;
1287
- try {
1288
- const reportProgress = async (progress) => {
1289
- if (progressToken === void 0) {
1290
- return;
1316
+ let args = void 0;
1317
+ if (tool.parameters) {
1318
+ const parsed = await tool.parameters["~standard"].validate(
1319
+ request.params.arguments
1320
+ );
1321
+ if (parsed.issues) {
1322
+ const friendlyErrors = this.#formatSchemaIssues(parsed.issues);
1323
+ throw new McpError(
1324
+ ErrorCode.InvalidParams,
1325
+ `Tool '${request.params.name}' parameter validation failed: ${friendlyErrors}. Please check the parameter types and values according to the tool's schema.`
1326
+ );
1291
1327
  }
1292
- try {
1293
- await this.#server.notification({
1294
- method: "notifications/progress",
1295
- params: {
1296
- ...progress,
1297
- progressToken
1328
+ args = parsed.value;
1329
+ }
1330
+ const progressToken = request.params?._meta?.progressToken;
1331
+ let result;
1332
+ try {
1333
+ const reportProgress = async (progress) => {
1334
+ if (progressToken === void 0) {
1335
+ return;
1336
+ }
1337
+ try {
1338
+ await this.#server.notification({
1339
+ method: "notifications/progress",
1340
+ params: {
1341
+ ...progress,
1342
+ progressToken
1343
+ }
1344
+ });
1345
+ if (this.#needsEventLoopFlush) {
1346
+ await new Promise((resolve) => setImmediate(resolve));
1298
1347
  }
1299
- });
1300
- if (this.#needsEventLoopFlush) {
1301
- await new Promise((resolve) => setImmediate(resolve));
1348
+ } catch (progressError) {
1349
+ this.#logger.warn(
1350
+ `[FastMCP warning] Failed to report progress for tool '${request.params.name}':`,
1351
+ progressError instanceof Error ? progressError.message : String(progressError)
1352
+ );
1302
1353
  }
1303
- } catch (progressError) {
1304
- this.#logger.warn(
1305
- `[FastMCP warning] Failed to report progress for tool '${request.params.name}':`,
1306
- progressError instanceof Error ? progressError.message : String(progressError)
1307
- );
1308
- }
1309
- };
1310
- const log = this.#createLog();
1311
- const streamContent = async (content) => {
1312
- const contentArray = Array.isArray(content) ? content : [content];
1313
- try {
1314
- await this.#server.notification({
1315
- method: "notifications/tool/streamContent",
1316
- params: {
1317
- content: contentArray,
1318
- toolName: request.params.name
1354
+ };
1355
+ const log = this.#createLog();
1356
+ const streamContent = async (content) => {
1357
+ const contentArray = Array.isArray(content) ? content : [content];
1358
+ try {
1359
+ await this.#server.notification({
1360
+ method: "notifications/tool/streamContent",
1361
+ params: {
1362
+ content: contentArray,
1363
+ toolName: request.params.name
1364
+ }
1365
+ });
1366
+ if (this.#needsEventLoopFlush) {
1367
+ await new Promise((resolve) => setImmediate(resolve));
1319
1368
  }
1320
- });
1321
- if (this.#needsEventLoopFlush) {
1322
- await new Promise((resolve) => setImmediate(resolve));
1369
+ } catch (streamError) {
1370
+ this.#logger.warn(
1371
+ `[FastMCP warning] Failed to stream content for tool '${request.params.name}':`,
1372
+ streamError instanceof Error ? streamError.message : String(streamError)
1373
+ );
1323
1374
  }
1324
- } catch (streamError) {
1325
- this.#logger.warn(
1326
- `[FastMCP warning] Failed to stream content for tool '${request.params.name}':`,
1327
- streamError instanceof Error ? streamError.message : String(streamError)
1328
- );
1375
+ };
1376
+ if (this.#onToolCall) {
1377
+ await this.#onToolCall({
1378
+ arguments: args ?? {},
1379
+ toolName: request.params.name
1380
+ });
1329
1381
  }
1330
- };
1331
- if (this.#onToolCall) {
1332
- await this.#onToolCall({
1333
- arguments: args ?? {},
1334
- toolName: request.params.name
1335
- });
1336
- }
1337
- const executeToolPromise = tool.execute(args, {
1338
- client: {
1339
- version: this.#server.getClientVersion()
1340
- },
1341
- elicit: (params, options) => this.#server.elicitInput(params, options),
1342
- log,
1343
- reportProgress,
1344
- requestId: typeof request.params?._meta?.requestId === "string" ? request.params._meta.requestId : void 0,
1345
- session: this.#auth,
1346
- sessionId: this.#sessionId,
1347
- streamContent
1348
- });
1349
- const maybeStringResult = await (tool.timeoutMs ? Promise.race([
1350
- executeToolPromise,
1351
- new Promise((_, reject) => {
1352
- const timeoutId = setTimeout(() => {
1353
- reject(
1354
- new UserError(
1355
- `Tool '${request.params.name}' timed out after ${tool.timeoutMs}ms. Consider increasing timeoutMs or optimizing the tool implementation.`
1356
- )
1382
+ const executeToolPromise = Promise.resolve(
1383
+ tool.execute(args, {
1384
+ client: {
1385
+ version: this.#server.getClientVersion()
1386
+ },
1387
+ elicit: (params, options) => this.#server.elicitInput(params, options),
1388
+ log,
1389
+ reportProgress,
1390
+ requestId: typeof request.params?._meta?.requestId === "string" ? request.params._meta.requestId : void 0,
1391
+ session: this.#auth,
1392
+ sessionId: this.#sessionId,
1393
+ streamContent
1394
+ })
1395
+ );
1396
+ const stopStreamKeepalive = this.#startStreamKeepalive(
1397
+ extra,
1398
+ request.params.name
1399
+ );
1400
+ const maybeStringResult = await (tool.timeoutMs ? Promise.race([
1401
+ executeToolPromise,
1402
+ new Promise((_, reject) => {
1403
+ const timeoutId = setTimeout(() => {
1404
+ reject(
1405
+ new UserError(
1406
+ `Tool '${request.params.name}' timed out after ${tool.timeoutMs}ms. Consider increasing timeoutMs or optimizing the tool implementation.`
1407
+ )
1408
+ );
1409
+ }, tool.timeoutMs);
1410
+ executeToolPromise.then(
1411
+ () => clearTimeout(timeoutId),
1412
+ () => clearTimeout(timeoutId)
1357
1413
  );
1358
- }, tool.timeoutMs);
1359
- executeToolPromise.then(
1360
- () => clearTimeout(timeoutId),
1361
- () => clearTimeout(timeoutId)
1362
- );
1363
- })
1364
- ]) : executeToolPromise);
1365
- await delay(1);
1366
- if (maybeStringResult === void 0 || maybeStringResult === null) {
1367
- result = ContentResultZodSchema.parse({
1368
- content: []
1369
- });
1370
- } else if (typeof maybeStringResult === "string") {
1371
- result = ContentResultZodSchema.parse({
1372
- content: [{ text: maybeStringResult, type: "text" }]
1373
- });
1374
- } else if ("type" in maybeStringResult) {
1375
- result = ContentResultZodSchema.parse({
1376
- content: [maybeStringResult]
1377
- });
1378
- } else if ("content" in maybeStringResult) {
1379
- result = ContentResultZodSchema.parse(maybeStringResult);
1380
- if (result.structuredContent !== void 0 && tool.outputSchema) {
1381
- result.structuredContent = await this.#validateStructuredContent(
1414
+ })
1415
+ ]) : executeToolPromise).finally(stopStreamKeepalive);
1416
+ await delay(1);
1417
+ if (maybeStringResult === void 0 || maybeStringResult === null) {
1418
+ result = ContentResultZodSchema.parse({
1419
+ content: []
1420
+ });
1421
+ } else if (typeof maybeStringResult === "string") {
1422
+ result = ContentResultZodSchema.parse({
1423
+ content: [{ text: maybeStringResult, type: "text" }]
1424
+ });
1425
+ } else if ("type" in maybeStringResult) {
1426
+ result = ContentResultZodSchema.parse({
1427
+ content: [maybeStringResult]
1428
+ });
1429
+ } else if ("content" in maybeStringResult) {
1430
+ result = ContentResultZodSchema.parse(maybeStringResult);
1431
+ if (result.structuredContent !== void 0 && tool.outputSchema) {
1432
+ result.structuredContent = await this.#validateStructuredContent(
1433
+ tool,
1434
+ result.structuredContent,
1435
+ request.params.name
1436
+ );
1437
+ }
1438
+ } else if (tool.outputSchema) {
1439
+ const structuredContent = await this.#validateStructuredContent(
1382
1440
  tool,
1383
- result.structuredContent,
1441
+ maybeStringResult,
1384
1442
  request.params.name
1385
1443
  );
1444
+ result = ContentResultZodSchema.parse({
1445
+ content: [
1446
+ {
1447
+ text: JSON.stringify(structuredContent),
1448
+ type: "text"
1449
+ }
1450
+ ],
1451
+ structuredContent
1452
+ });
1453
+ } else {
1454
+ result = ContentResultZodSchema.parse(maybeStringResult);
1386
1455
  }
1387
- } else if (tool.outputSchema) {
1388
- const structuredContent = await this.#validateStructuredContent(
1389
- tool,
1390
- maybeStringResult,
1391
- request.params.name
1392
- );
1393
- result = ContentResultZodSchema.parse({
1456
+ } catch (error) {
1457
+ if (error instanceof UserError) {
1458
+ return {
1459
+ content: [{ text: error.message, type: "text" }],
1460
+ isError: true,
1461
+ ...error.extras ? { structuredContent: error.extras } : {}
1462
+ };
1463
+ }
1464
+ const errorMessage = error instanceof Error ? error.message : String(error);
1465
+ return {
1394
1466
  content: [
1395
1467
  {
1396
- text: JSON.stringify(structuredContent),
1468
+ text: `Tool '${request.params.name}' execution failed: ${errorMessage}`,
1397
1469
  type: "text"
1398
1470
  }
1399
1471
  ],
1400
- structuredContent
1401
- });
1402
- } else {
1403
- result = ContentResultZodSchema.parse(maybeStringResult);
1404
- }
1405
- } catch (error) {
1406
- if (error instanceof UserError) {
1407
- return {
1408
- content: [{ text: error.message, type: "text" }],
1409
- isError: true,
1410
- ...error.extras ? { structuredContent: error.extras } : {}
1472
+ isError: true
1411
1473
  };
1412
1474
  }
1413
- const errorMessage = error instanceof Error ? error.message : String(error);
1414
- return {
1415
- content: [
1416
- {
1417
- text: `Tool '${request.params.name}' execution failed: ${errorMessage}`,
1418
- type: "text"
1419
- }
1420
- ],
1421
- isError: true
1422
- };
1475
+ return result;
1423
1476
  }
1424
- return result;
1425
- });
1477
+ );
1426
1478
  }
1427
1479
  };
1428
1480
  function camelToSnakeCase(str) {
@@ -1844,7 +1896,7 @@ var FastMCP = class extends FastMCPEventEmitter {
1844
1896
  try {
1845
1897
  auth = await this.#authenticate(
1846
1898
  void 0
1847
- );
1899
+ ) ?? void 0;
1848
1900
  } catch (error) {
1849
1901
  this.#logger.error(
1850
1902
  "[FastMCP error] Authentication failed for stdio transport:",
@@ -1863,6 +1915,7 @@ var FastMCP = class extends FastMCPEventEmitter {
1863
1915
  resources: this.#resources,
1864
1916
  resourcesTemplates: this.#resourcesTemplates,
1865
1917
  roots: this.#options.roots,
1918
+ streamKeepalive: this.#options.streamKeepalive,
1866
1919
  tools: this.#tools,
1867
1920
  transportType: "stdio",
1868
1921
  utils: this.#options.utils,
@@ -1922,12 +1975,9 @@ var FastMCP = class extends FastMCPEventEmitter {
1922
1975
  createServer: async (request) => {
1923
1976
  let auth;
1924
1977
  if (this.#authenticate) {
1925
- auth = await this.#authenticate(request);
1926
- if (auth === void 0 || auth === null) {
1927
- throw this.#createUnauthorizedResponse(
1928
- "Authentication required"
1929
- );
1930
- }
1978
+ auth = this.#requireAuthenticated(
1979
+ await this.#authenticate(request)
1980
+ );
1931
1981
  }
1932
1982
  const sessionId = Array.isArray(request.headers["mcp-session-id"]) ? request.headers["mcp-session-id"][0] : request.headers["mcp-session-id"];
1933
1983
  return this.#createSession(auth, sessionId, true);
@@ -1974,7 +2024,9 @@ var FastMCP = class extends FastMCPEventEmitter {
1974
2024
  createServer: async (request) => {
1975
2025
  let auth;
1976
2026
  if (this.#authenticate) {
1977
- auth = await this.#authenticate(request);
2027
+ auth = this.#requireAuthenticated(
2028
+ await this.#authenticate(request)
2029
+ );
1978
2030
  }
1979
2031
  const sessionId = Array.isArray(request.headers["mcp-session-id"]) ? request.headers["mcp-session-id"][0] : request.headers["mcp-session-id"];
1980
2032
  return this.#createSession(auth, sessionId);
@@ -2063,6 +2115,7 @@ var FastMCP = class extends FastMCPEventEmitter {
2063
2115
  roots: this.#options.roots,
2064
2116
  sessionId,
2065
2117
  stateless,
2118
+ streamKeepalive: this.#options.streamKeepalive,
2066
2119
  tools: allowedTools,
2067
2120
  transportType: "httpStream",
2068
2121
  utils: this.#options.utils,
@@ -2615,6 +2668,28 @@ var FastMCP = class extends FastMCPEventEmitter {
2615
2668
  });
2616
2669
  }
2617
2670
  }
2671
+ /**
2672
+ * Rejects a failed authentication result before it can become a session.
2673
+ *
2674
+ * Authentication is REQUIRED whenever an `authenticate` function is
2675
+ * configured. mcp-proxy gates the HTTP Stream endpoint before `createServer`
2676
+ * runs, but it does not gate the SSE endpoint it serves at `/sse` by default:
2677
+ * `handleSSERequest` never receives `authenticate`. Throwing here is what
2678
+ * stops `/sse` from handing out a session — with access to every tool, since
2679
+ * `#createSession` skips `canAccess` filtering when `auth` is falsy — to a
2680
+ * client that `/mcp` would have answered with a 401.
2681
+ *
2682
+ * The falsy test matches mcp-proxy's own check so that both endpoints agree
2683
+ * on what counts as a failed authentication. Returning a nullish value is the
2684
+ * idiomatic way to signal failure, and is what the built-in OAuth
2685
+ * `AuthProvider` does for a missing or invalid bearer token.
2686
+ */
2687
+ #requireAuthenticated(auth) {
2688
+ if (!auth) {
2689
+ throw this.#createUnauthorizedResponse("Authentication required");
2690
+ }
2691
+ return auth;
2692
+ }
2618
2693
  /**
2619
2694
  * Notifies all sessions that the resources list has changed.
2620
2695
  */
@@ -2655,4 +2730,4 @@ export {
2655
2730
  FastMCPSession,
2656
2731
  FastMCP
2657
2732
  };
2658
- //# sourceMappingURL=chunk-HIIPZVNY.js.map
2733
+ //# sourceMappingURL=chunk-LMDMFMPI.js.map