mcponce 0.3.0 → 1.0.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.
Files changed (64) hide show
  1. package/README.md +8 -8
  2. package/dist/cli/bin.d.ts.map +1 -1
  3. package/dist/cli/bin.js +6 -1
  4. package/dist/cli/bin.js.map +1 -1
  5. package/dist/cli/index.d.ts.map +1 -1
  6. package/dist/cli/index.js +6 -1
  7. package/dist/cli/index.js.map +1 -1
  8. package/dist/cli/installer.d.ts +15 -4
  9. package/dist/cli/installer.d.ts.map +1 -1
  10. package/dist/cli/installer.js +142 -25
  11. package/dist/cli/installer.js.map +1 -1
  12. package/dist/index.d.ts +6 -5
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +3 -2
  15. package/dist/index.js.map +1 -1
  16. package/dist/logging/mcp-logger.d.ts +15 -0
  17. package/dist/logging/mcp-logger.d.ts.map +1 -0
  18. package/dist/logging/mcp-logger.js +46 -0
  19. package/dist/logging/mcp-logger.js.map +1 -0
  20. package/dist/runtime/config.d.ts +7 -1
  21. package/dist/runtime/config.d.ts.map +1 -1
  22. package/dist/runtime/config.js +8 -0
  23. package/dist/runtime/config.js.map +1 -1
  24. package/dist/runtime/instance.d.ts.map +1 -1
  25. package/dist/runtime/instance.js +6 -1
  26. package/dist/runtime/instance.js.map +1 -1
  27. package/dist/runtime/lock.d.ts +4 -2
  28. package/dist/runtime/lock.d.ts.map +1 -1
  29. package/dist/runtime/lock.js +33 -8
  30. package/dist/runtime/lock.js.map +1 -1
  31. package/dist/runtime/unitup.d.ts +10 -2
  32. package/dist/runtime/unitup.d.ts.map +1 -1
  33. package/dist/runtime/unitup.js +96 -3
  34. package/dist/runtime/unitup.js.map +1 -1
  35. package/dist/server/app.d.ts +19 -0
  36. package/dist/server/app.d.ts.map +1 -1
  37. package/dist/server/app.js +253 -164
  38. package/dist/server/app.js.map +1 -1
  39. package/dist/server/hono.d.ts +3 -0
  40. package/dist/server/hono.d.ts.map +1 -1
  41. package/dist/server/hono.js +174 -58
  42. package/dist/server/hono.js.map +1 -1
  43. package/dist/server/inspector.d.ts.map +1 -1
  44. package/dist/server/inspector.js +12 -2
  45. package/dist/server/inspector.js.map +1 -1
  46. package/dist/server/mcp.d.ts +7 -1
  47. package/dist/server/mcp.d.ts.map +1 -1
  48. package/dist/server/mcp.js +81 -17
  49. package/dist/server/mcp.js.map +1 -1
  50. package/dist/types.d.ts +92 -2
  51. package/dist/types.d.ts.map +1 -1
  52. package/dist/utils/elicitation.d.ts +34 -0
  53. package/dist/utils/elicitation.d.ts.map +1 -0
  54. package/dist/utils/elicitation.js +136 -0
  55. package/dist/utils/elicitation.js.map +1 -0
  56. package/dist/utils/media.d.ts +38 -3
  57. package/dist/utils/media.d.ts.map +1 -1
  58. package/dist/utils/media.js +151 -3
  59. package/dist/utils/media.js.map +1 -1
  60. package/dist/utils/security.d.ts +12 -0
  61. package/dist/utils/security.d.ts.map +1 -1
  62. package/dist/utils/security.js +47 -0
  63. package/dist/utils/security.js.map +1 -1
  64. package/package.json +11 -3
@@ -4,6 +4,7 @@ import { resolveCompletion } from '../utils/completion.js';
4
4
  import { AnalyticsCollector } from './analytics.js';
5
5
  import { resolveConfig } from '../runtime/config.js';
6
6
  import { InstanceCoordinator } from '../runtime/instance.js';
7
+ import { LockManager } from '../runtime/lock.js';
7
8
  import { checkHealth, fetchInfo, isPidRunning } from '../runtime/health.js';
8
9
  import { DefaultLogger } from '../logging/logger.js';
9
10
  import { ToolRegistry, normalizeInputSchema } from '../registry/tools.js';
@@ -15,6 +16,7 @@ import { normalizeToolResult, registerSingleTool, registerSingleResource, regist
15
16
  import { normalizeResourceResult } from '../utils/media.js';
16
17
  import { createHonoApp } from './hono.js';
17
18
  import { executeSample, executeListRoots } from '../utils/sampling.js';
19
+ import { executeElicit } from '../utils/elicitation.js';
18
20
  import { createOpenApiTools } from '../utils/openapi.js';
19
21
  import { startHttpServer } from '../transport/http.js';
20
22
  import { startStdioProxy } from '../transport/proxy.js';
@@ -25,6 +27,7 @@ import { ToolCacheManager } from '../utils/cache.js';
25
27
  import { executeWithRetry, raceWithSignal } from '../utils/retry.js';
26
28
  import { coerceArguments } from '../utils/coercion.js';
27
29
  import { createProgressReporter } from '../utils/progress.js';
30
+ import { createToolLogger } from '../logging/mcp-logger.js';
28
31
  import { MiddlewareManager } from '../utils/middleware.js';
29
32
  import { getUnitup, startBackgroundProcess, stopBackgroundProcess } from '../runtime/unitup.js';
30
33
  export class McpApp {
@@ -43,6 +46,7 @@ export class McpApp {
43
46
  instanceCoordinator;
44
47
  stateManager;
45
48
  lockManager;
49
+ bootstrapLockManager;
46
50
  _centralRegistry;
47
51
  get centralRegistry() {
48
52
  if (!this._centralRegistry) {
@@ -52,11 +56,13 @@ export class McpApp {
52
56
  }
53
57
  httpHandle;
54
58
  stdioProxyHandle;
59
+ httpCleanupCallbacks = [];
55
60
  sessions = new Map();
56
61
  metrics;
57
62
  isOwner = false;
58
63
  sampleFallback;
59
64
  listRootsFallback;
65
+ elicitFallback;
60
66
  rootsListChangedListeners = [];
61
67
  constructor(config) {
62
68
  this.config = resolveConfig(config);
@@ -68,6 +74,9 @@ export class McpApp {
68
74
  if (raw.onListRoots) {
69
75
  this.listRootsFallback = raw.onListRoots;
70
76
  }
77
+ if (raw.onElicit) {
78
+ this.elicitFallback = raw.onElicit;
79
+ }
71
80
  }
72
81
  this.logger = raw.logger || new DefaultLogger({
73
82
  logDir: this.config.logDir,
@@ -83,6 +92,7 @@ export class McpApp {
83
92
  this.instanceCoordinator = new InstanceCoordinator(this.config);
84
93
  this.stateManager = this.instanceCoordinator.stateManager;
85
94
  this.lockManager = this.instanceCoordinator.lockManager;
95
+ this.bootstrapLockManager = new LockManager(this.config.dataDir, 'bootstrap.lock');
86
96
  this.metrics = {
87
97
  startedAt: new Date().toISOString(),
88
98
  activeSessions: 0,
@@ -360,6 +370,14 @@ export class McpApp {
360
370
  const listRootsHelper = () => {
361
371
  return executeListRoots(sessionServer, this.listRootsFallback, mergedSignal);
362
372
  };
373
+ const elicitHelper = (elicitOpts) => {
374
+ return executeElicit(elicitOpts, sessionServer, this.elicitFallback, mergedSignal);
375
+ };
376
+ const logHelper = createToolLogger({
377
+ toolName: tool.name,
378
+ server: sessionServer,
379
+ localLogger: this.logger
380
+ });
363
381
  const extra = {
364
382
  signal: mergedSignal,
365
383
  callTool: callToolHelper,
@@ -368,7 +386,9 @@ export class McpApp {
368
386
  progressToken: options.progressToken,
369
387
  sample: sampleHelper,
370
388
  listRoots: listRootsHelper,
371
- auth: options.auth
389
+ elicit: elicitHelper,
390
+ auth: options.auth,
391
+ log: logHelper
372
392
  };
373
393
  const queueConfig = this.resolveQueueConfig(tool, options, callStack.length > 0);
374
394
  let release;
@@ -391,7 +411,9 @@ export class McpApp {
391
411
  reportProgress,
392
412
  sample: sampleHelper,
393
413
  listRoots: listRootsHelper,
394
- auth: options.auth
414
+ elicit: elicitHelper,
415
+ auth: options.auth,
416
+ log: logHelper
395
417
  })
396
418
  : {
397
419
  callTool: callToolHelper,
@@ -400,7 +422,9 @@ export class McpApp {
400
422
  reportProgress,
401
423
  sample: sampleHelper,
402
424
  listRoots: listRootsHelper,
403
- auth: options.auth
425
+ elicit: elicitHelper,
426
+ auth: options.auth,
427
+ log: logHelper
404
428
  };
405
429
  this.logger.info('tool:start', { name: tool.name, caller: callStack[callStack.length - 1] });
406
430
  const effectiveRetry = options.retry !== undefined ? options.retry : tool.retry;
@@ -900,6 +924,22 @@ export class McpApp {
900
924
  this.listRootsFallback = handler;
901
925
  return this;
902
926
  }
927
+ /**
928
+ * Requests structured user input or out-of-band URL interaction from the connected client via MCP elicitation/create.
929
+ * If running offline or in tests, delegates to any fallback handler configured with app.onElicit().
930
+ */
931
+ async elicit(options) {
932
+ const activeSession = this.sessions.size > 0 ? Array.from(this.sessions.values())[this.sessions.size - 1] : undefined;
933
+ const sessionServer = activeSession?.server;
934
+ return executeElicit(options, sessionServer, this.elicitFallback);
935
+ }
936
+ /**
937
+ * Registers a fallback/offline handler for elicitation requests.
938
+ */
939
+ onElicit(handler) {
940
+ this.elicitFallback = handler;
941
+ return this;
942
+ }
903
943
  /**
904
944
  * Listens for client roots/list_changed notifications.
905
945
  * Returns an unbind function.
@@ -987,66 +1027,106 @@ export class McpApp {
987
1027
  };
988
1028
  }
989
1029
  /**
990
- * Starts the server programmatically. If a server is already running,
991
- * reuses it and returns `{ reused: true, ... }`.
1030
+ * Coordinates background worker startup using a dedicated `bootstrap.lock` so concurrent
1031
+ * callers cannot invoke `startBackgroundProcess()` more than once, and holds the bootstrap
1032
+ * lock until the spawned worker passes its `/health` check.
992
1033
  */
993
- async start(options = {}) {
994
- const isBackgroundWorker = process.env.MCPONCE_BACKGROUND_SERVER === '1' ||
995
- process.argv.includes('--mcponce-background');
996
- const shouldRunBackground = options.background !== undefined ? options.background : this.config.background;
997
- if (shouldRunBackground && !isBackgroundWorker && !options.noSingleton) {
998
- await getUnitup();
999
- const existingState = this.stateManager.read();
1000
- if (existingState && existingState.name === this.config.name) {
1001
- const health = await checkHealth(existingState.host, existingState.port, this.config.name, 300);
1002
- if (health) {
1003
- return {
1004
- reused: true,
1005
- role: 'bridge',
1006
- pid: existingState.pid,
1007
- port: existingState.port,
1008
- host: existingState.host
1009
- };
1010
- }
1034
+ async ensureBackgroundWorkerStarted() {
1035
+ await getUnitup();
1036
+ const checkHealthyState = async () => {
1037
+ const st = this.stateManager.read();
1038
+ if (st && st.name === this.config.name) {
1039
+ const h = await checkHealth(st.host, st.port, this.config.name, 300);
1040
+ if (h)
1041
+ return st;
1042
+ }
1043
+ return null;
1044
+ };
1045
+ const waitForHealthy = async (timeoutMs) => {
1046
+ const startTime = Date.now();
1047
+ while (Date.now() - startTime < timeoutMs) {
1048
+ const healthy = await checkHealthyState();
1049
+ if (healthy)
1050
+ return healthy;
1051
+ await new Promise((r) => setTimeout(r, 25));
1011
1052
  }
1012
- const initialLock = this.lockManager.readLock();
1013
- if (!initialLock || !isPidRunning(initialLock.pid)) {
1014
- this.lockManager.forceRelease();
1015
- this.stateManager.forceClean();
1053
+ return null;
1054
+ };
1055
+ // Fast path: already running and healthy
1056
+ const existingHealthy = await checkHealthyState();
1057
+ if (existingHealthy) {
1058
+ return { state: existingHealthy, reused: true };
1059
+ }
1060
+ // Only clean stale runtime state/lock when the recorded PID is confirmed dead
1061
+ const existingState = this.stateManager.read();
1062
+ if (existingState && existingState.name === this.config.name && !isPidRunning(existingState.pid)) {
1063
+ this.lockManager.forceRelease();
1064
+ this.stateManager.forceClean();
1065
+ }
1066
+ const maxWaitMs = 20000;
1067
+ const deadline = Date.now() + maxWaitMs;
1068
+ while (Date.now() < deadline) {
1069
+ // Clear stale bootstrap lock if its holder process died mid-spawn
1070
+ const bootLock = this.bootstrapLockManager.readLock();
1071
+ if (bootLock && !isPidRunning(bootLock.pid)) {
1072
+ this.bootstrapLockManager.forceRelease();
1016
1073
  }
1017
- if (this.lockManager.tryAcquire(this.config.name)) {
1074
+ if (this.bootstrapLockManager.tryAcquire(this.config.name)) {
1018
1075
  try {
1076
+ // Double-check after acquiring bootstrap lock in case a peer just finished starting it
1077
+ const healthyAfterLock = await checkHealthyState();
1078
+ if (healthyAfterLock) {
1079
+ return { state: healthyAfterLock, reused: true };
1080
+ }
1081
+ // Re-verify stale instance lock before spawning
1082
+ const instLock = this.lockManager.readLock();
1083
+ if (instLock && !isPidRunning(instLock.pid)) {
1084
+ this.lockManager.forceRelease();
1085
+ this.stateManager.forceClean();
1086
+ }
1019
1087
  await startBackgroundProcess({
1020
1088
  name: this.config.name,
1021
1089
  scriptPath: this.config.entrypoint,
1022
1090
  dataDir: this.config.dataDir,
1023
1091
  logDir: this.config.logDir
1024
1092
  });
1093
+ const remainingMs = Math.max(1000, deadline - Date.now());
1094
+ const healthyState = await waitForHealthy(remainingMs);
1095
+ if (!healthyState) {
1096
+ try {
1097
+ await stopBackgroundProcess(this.config.name, this.config.dataDir);
1098
+ }
1099
+ catch { }
1100
+ throw new Error(`Failed to start background MCP server for "${this.config.name}" through Unitup: health check timed out`);
1101
+ }
1102
+ return { state: healthyState, reused: false };
1025
1103
  }
1026
1104
  finally {
1027
- this.lockManager.release();
1028
- }
1029
- }
1030
- const maxWaitMs = 20000;
1031
- const startTime = Date.now();
1032
- let healthyState = null;
1033
- while (Date.now() - startTime < maxWaitMs) {
1034
- await new Promise((r) => setTimeout(r, 25));
1035
- const st = this.stateManager.read();
1036
- if (st && st.name === this.config.name) {
1037
- const h = await checkHealth(st.host, st.port, this.config.name, 300);
1038
- if (h) {
1039
- healthyState = st;
1040
- break;
1041
- }
1105
+ this.bootstrapLockManager.release();
1042
1106
  }
1043
1107
  }
1044
- if (!healthyState) {
1045
- throw new Error(`Failed to start background MCP server for "${this.config.name}" through Unitup: health check timed out`);
1108
+ // Another live process holds bootstrap.lock and is spawning the worker: wait for health
1109
+ const healthyWhileWaiting = await checkHealthyState();
1110
+ if (healthyWhileWaiting) {
1111
+ return { state: healthyWhileWaiting, reused: true };
1046
1112
  }
1113
+ await new Promise((r) => setTimeout(r, 25));
1114
+ }
1115
+ throw new Error(`Failed to start background MCP server for "${this.config.name}" through Unitup: health check timed out`);
1116
+ }
1117
+ /**
1118
+ * Starts the server programmatically. If a server is already running,
1119
+ * reuses it and returns `{ reused: true, ... }`.
1120
+ */
1121
+ async start(options = {}) {
1122
+ const isBackgroundWorker = process.env.MCPONCE_BACKGROUND_SERVER === '1' ||
1123
+ process.argv.includes('--mcponce-background');
1124
+ const shouldRunBackground = options.background !== undefined ? options.background : this.config.background;
1125
+ if (shouldRunBackground && !isBackgroundWorker && !options.noSingleton) {
1126
+ const { state: healthyState, reused } = await this.ensureBackgroundWorkerStarted();
1047
1127
  return {
1048
- reused: false,
1049
- role: 'owner',
1128
+ reused,
1129
+ role: reused ? 'bridge' : 'owner',
1050
1130
  pid: healthyState.pid,
1051
1131
  port: healthyState.port,
1052
1132
  host: healthyState.host
@@ -1067,35 +1147,46 @@ export class McpApp {
1067
1147
  }
1068
1148
  // Role is owner: initialize context and start HTTP server
1069
1149
  this.isOwner = true;
1070
- await this.contextManager.initialize(this.logger);
1071
- let currentPort = this.config.port;
1072
- const honoApp = createHonoApp({
1073
- config: this.config,
1074
- toolRegistry: this.toolRegistry,
1075
- resourceRegistry: this.resourceRegistry,
1076
- promptRegistry: this.promptRegistry,
1077
- contextManager: this.contextManager,
1078
- metrics: this.metrics,
1079
- analytics: this.analytics,
1080
- portProvider: () => currentPort,
1081
- callTool: (name, args, options, stack) => this.callTool(name, args, options, stack),
1082
- logger: this.logger,
1083
- queueManager: this.queueManager,
1084
- cacheManager: this.cacheManager,
1085
- middlewareManager: this.middlewareManager,
1086
- resolveQueueConfig: (tool, opts) => this.resolveQueueConfig(tool, opts),
1087
- sessions: this.sessions,
1088
- subscriptionRegistry: this.subscriptionRegistry,
1089
- onSample: this.sampleFallback,
1090
- onListRoots: this.listRootsFallback,
1091
- onRootsListChanged: (roots) => {
1092
- for (const listener of this.rootsListChangedListeners) {
1093
- listener(roots);
1150
+ try {
1151
+ await this.contextManager.initialize(this.logger);
1152
+ let currentPort = this.config.port;
1153
+ const honoApp = createHonoApp({
1154
+ config: this.config,
1155
+ toolRegistry: this.toolRegistry,
1156
+ resourceRegistry: this.resourceRegistry,
1157
+ promptRegistry: this.promptRegistry,
1158
+ contextManager: this.contextManager,
1159
+ metrics: this.metrics,
1160
+ analytics: this.analytics,
1161
+ portProvider: () => currentPort,
1162
+ callTool: (name, args, options, stack) => this.callTool(name, args, options, stack),
1163
+ logger: this.logger,
1164
+ queueManager: this.queueManager,
1165
+ cacheManager: this.cacheManager,
1166
+ middlewareManager: this.middlewareManager,
1167
+ resolveQueueConfig: (tool, opts) => this.resolveQueueConfig(tool, opts),
1168
+ sessions: this.sessions,
1169
+ subscriptionRegistry: this.subscriptionRegistry,
1170
+ onSample: this.sampleFallback,
1171
+ onListRoots: this.listRootsFallback,
1172
+ onElicit: this.elicitFallback,
1173
+ onDispose: (fn) => this.httpCleanupCallbacks.push(fn),
1174
+ onRootsListChanged: (roots) => {
1175
+ for (const listener of this.rootsListChangedListeners) {
1176
+ listener(roots);
1177
+ }
1094
1178
  }
1179
+ });
1180
+ this.httpHandle = await startHttpServer(honoApp, this.config.host, this.config.port);
1181
+ currentPort = this.httpHandle.port;
1182
+ }
1183
+ catch (err) {
1184
+ this.isOwner = false;
1185
+ if (!options.noSingleton) {
1186
+ this.lockManager.release();
1095
1187
  }
1096
- });
1097
- this.httpHandle = await startHttpServer(honoApp, this.config.host, this.config.port);
1098
- currentPort = this.httpHandle.port;
1188
+ throw err;
1189
+ }
1099
1190
  this.stateManager.write({
1100
1191
  name: this.config.name,
1101
1192
  version: this.config.version,
@@ -1141,6 +1232,31 @@ export class McpApp {
1141
1232
  await this.stdioProxyHandle.close();
1142
1233
  this.stdioProxyHandle = undefined;
1143
1234
  }
1235
+ // Close all active MCP sessions cleanly and clear subscriptions
1236
+ if (this.sessions.size > 0) {
1237
+ const entries = Array.from(this.sessions.entries());
1238
+ this.sessions.clear();
1239
+ this.metrics.activeSessions = 0;
1240
+ await Promise.allSettled(entries.map(async ([sid, session]) => {
1241
+ this.subscriptionRegistry.removeSession(sid);
1242
+ try {
1243
+ await session.transport?.close?.();
1244
+ }
1245
+ catch { }
1246
+ try {
1247
+ await session.server?.close?.();
1248
+ }
1249
+ catch { }
1250
+ }));
1251
+ }
1252
+ // Run HTTP middleware cleanup hooks (e.g. RateLimiter.destroy())
1253
+ while (this.httpCleanupCallbacks.length > 0) {
1254
+ const fn = this.httpCleanupCallbacks.pop();
1255
+ try {
1256
+ fn?.();
1257
+ }
1258
+ catch { }
1259
+ }
1144
1260
  if (this.httpHandle) {
1145
1261
  await this.httpHandle.close();
1146
1262
  this.httpHandle = undefined;
@@ -1148,7 +1264,7 @@ export class McpApp {
1148
1264
  const shouldStopBackground = options.background !== undefined ? options.background : this.config.background;
1149
1265
  if (shouldStopBackground) {
1150
1266
  try {
1151
- await stopBackgroundProcess(this.config.name);
1267
+ await stopBackgroundProcess(this.config.name, this.config.dataDir);
1152
1268
  }
1153
1269
  catch { }
1154
1270
  if (this.config.registerInCentral) {
@@ -1159,6 +1275,7 @@ export class McpApp {
1159
1275
  }
1160
1276
  this.stateManager.forceClean();
1161
1277
  this.lockManager.forceRelease();
1278
+ this.bootstrapLockManager.forceRelease();
1162
1279
  this.isOwner = false;
1163
1280
  return;
1164
1281
  }
@@ -1214,6 +1331,15 @@ export class McpApp {
1214
1331
  process.argv.includes('--mcponce-background');
1215
1332
  if (isBackgroundWorker) {
1216
1333
  const startResult = await this.start({ noSingleton: false });
1334
+ if (startResult.reused || startResult.role === 'bridge') {
1335
+ this.logger.info('Duplicate background MCP worker detected; exiting cleanly', {
1336
+ name: this.config.name,
1337
+ pid: process.pid,
1338
+ existingPid: startResult.pid,
1339
+ port: startResult.port
1340
+ });
1341
+ process.exit(0);
1342
+ }
1217
1343
  this.logger.info('Background MCP worker running', {
1218
1344
  name: this.config.name,
1219
1345
  pid: process.pid,
@@ -1231,58 +1357,10 @@ export class McpApp {
1231
1357
  }
1232
1358
  const backgroundMode = this.config.background || cliOptions.background;
1233
1359
  if (backgroundMode) {
1234
- await getUnitup();
1235
- let targetPort;
1236
- let targetHost;
1237
- let serverPid;
1238
- const existingState = this.stateManager.read();
1239
- const isHealthy = existingState && existingState.name === this.config.name
1240
- ? await checkHealth(existingState.host, existingState.port, this.config.name, 300)
1241
- : null;
1242
- if (isHealthy && existingState) {
1243
- targetPort = existingState.port;
1244
- targetHost = existingState.host;
1245
- serverPid = existingState.pid;
1246
- }
1247
- else {
1248
- if (existingState && !isHealthy) {
1249
- this.lockManager.forceRelease();
1250
- this.stateManager.forceClean();
1251
- }
1252
- if (this.lockManager.tryAcquire(this.config.name)) {
1253
- try {
1254
- await startBackgroundProcess({
1255
- name: this.config.name,
1256
- scriptPath: this.config.entrypoint,
1257
- dataDir: this.config.dataDir,
1258
- logDir: this.config.logDir
1259
- });
1260
- }
1261
- finally {
1262
- this.lockManager.release();
1263
- }
1264
- }
1265
- const maxWaitMs = 20000;
1266
- const start = Date.now();
1267
- let healthyState = null;
1268
- while (Date.now() - start < maxWaitMs) {
1269
- await new Promise((r) => setTimeout(r, 25));
1270
- const st = this.stateManager.read();
1271
- if (st && st.name === this.config.name) {
1272
- const h = await checkHealth(st.host, st.port, this.config.name, 300);
1273
- if (h) {
1274
- healthyState = st;
1275
- break;
1276
- }
1277
- }
1278
- }
1279
- if (!healthyState) {
1280
- throw new Error(`Failed to start background MCP server for "${this.config.name}" through Unitup: health check timed out`);
1281
- }
1282
- targetPort = healthyState.port;
1283
- targetHost = healthyState.host;
1284
- serverPid = healthyState.pid;
1285
- }
1360
+ const { state: healthyState } = await this.ensureBackgroundWorkerStarted();
1361
+ const targetPort = healthyState.port;
1362
+ const targetHost = healthyState.host;
1363
+ const serverPid = healthyState.pid;
1286
1364
  this.logger.info('bridge:start', {
1287
1365
  pid: process.pid,
1288
1366
  serverPid,
@@ -1309,45 +1387,56 @@ export class McpApp {
1309
1387
  let ownerStdioClosed = false;
1310
1388
  if (roleResult.role === 'owner') {
1311
1389
  this.isOwner = true;
1312
- await this.contextManager.initialize(this.logger);
1313
- let currentPort = this.config.port;
1314
- const honoApp = createHonoApp({
1315
- config: this.config,
1316
- toolRegistry: this.toolRegistry,
1317
- resourceRegistry: this.resourceRegistry,
1318
- promptRegistry: this.promptRegistry,
1319
- contextManager: this.contextManager,
1320
- metrics: this.metrics,
1321
- analytics: this.analytics,
1322
- portProvider: () => currentPort,
1323
- callTool: (name, args, options, stack) => this.callTool(name, args, options, stack),
1324
- logger: this.logger,
1325
- queueManager: this.queueManager,
1326
- cacheManager: this.cacheManager,
1327
- middlewareManager: this.middlewareManager,
1328
- resolveQueueConfig: (tool, opts) => this.resolveQueueConfig(tool, opts),
1329
- sessions: this.sessions,
1330
- subscriptionRegistry: this.subscriptionRegistry,
1331
- onSample: this.sampleFallback,
1332
- onListRoots: this.listRootsFallback,
1333
- onRootsListChanged: (roots) => {
1334
- for (const listener of this.rootsListChangedListeners) {
1335
- listener(roots);
1336
- }
1337
- },
1338
- onSessionClosed: () => {
1339
- if (ownerStdioClosed && this.sessions.size === 0) {
1340
- this.logger.info('All sessions closed after owner stdio ended, shutting down', {
1341
- pid: process.pid
1342
- });
1343
- shutdown();
1390
+ try {
1391
+ await this.contextManager.initialize(this.logger);
1392
+ let currentPort = this.config.port;
1393
+ const honoApp = createHonoApp({
1394
+ config: this.config,
1395
+ toolRegistry: this.toolRegistry,
1396
+ resourceRegistry: this.resourceRegistry,
1397
+ promptRegistry: this.promptRegistry,
1398
+ contextManager: this.contextManager,
1399
+ metrics: this.metrics,
1400
+ analytics: this.analytics,
1401
+ portProvider: () => currentPort,
1402
+ callTool: (name, args, options, stack) => this.callTool(name, args, options, stack),
1403
+ logger: this.logger,
1404
+ queueManager: this.queueManager,
1405
+ cacheManager: this.cacheManager,
1406
+ middlewareManager: this.middlewareManager,
1407
+ resolveQueueConfig: (tool, opts) => this.resolveQueueConfig(tool, opts),
1408
+ sessions: this.sessions,
1409
+ subscriptionRegistry: this.subscriptionRegistry,
1410
+ onSample: this.sampleFallback,
1411
+ onListRoots: this.listRootsFallback,
1412
+ onElicit: this.elicitFallback,
1413
+ onDispose: (fn) => this.httpCleanupCallbacks.push(fn),
1414
+ onRootsListChanged: (roots) => {
1415
+ for (const listener of this.rootsListChangedListeners) {
1416
+ listener(roots);
1417
+ }
1418
+ },
1419
+ onSessionClosed: () => {
1420
+ if (ownerStdioClosed && this.sessions.size === 0) {
1421
+ this.logger.info('All sessions closed after owner stdio ended, shutting down', {
1422
+ pid: process.pid
1423
+ });
1424
+ shutdown();
1425
+ }
1344
1426
  }
1427
+ });
1428
+ this.httpHandle = await startHttpServer(honoApp, this.config.host, this.config.port);
1429
+ currentPort = this.httpHandle.port;
1430
+ targetPort = this.httpHandle.port;
1431
+ targetHost = this.httpHandle.host;
1432
+ }
1433
+ catch (err) {
1434
+ this.isOwner = false;
1435
+ if (!cliOptions.noSingleton) {
1436
+ this.lockManager.release();
1345
1437
  }
1346
- });
1347
- this.httpHandle = await startHttpServer(honoApp, this.config.host, this.config.port);
1348
- currentPort = this.httpHandle.port;
1349
- targetPort = this.httpHandle.port;
1350
- targetHost = this.httpHandle.host;
1438
+ throw err;
1439
+ }
1351
1440
  this.stateManager.write({
1352
1441
  name: this.config.name,
1353
1442
  version: this.config.version,