mcponce 0.2.3 → 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 (97) 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 +162 -25
  11. package/dist/cli/installer.js.map +1 -1
  12. package/dist/cli/tool-caller.d.ts.map +1 -1
  13. package/dist/cli/tool-caller.js +1 -0
  14. package/dist/cli/tool-caller.js.map +1 -1
  15. package/dist/index.d.ts +7 -6
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +4 -3
  18. package/dist/index.js.map +1 -1
  19. package/dist/logging/file-logger.d.ts.map +1 -1
  20. package/dist/logging/file-logger.js +1 -4
  21. package/dist/logging/file-logger.js.map +1 -1
  22. package/dist/logging/mcp-logger.d.ts +15 -0
  23. package/dist/logging/mcp-logger.d.ts.map +1 -0
  24. package/dist/logging/mcp-logger.js +46 -0
  25. package/dist/logging/mcp-logger.js.map +1 -0
  26. package/dist/registry/central.d.ts.map +1 -1
  27. package/dist/registry/central.js +2 -10
  28. package/dist/registry/central.js.map +1 -1
  29. package/dist/registry/tools.d.ts +1 -1
  30. package/dist/registry/tools.d.ts.map +1 -1
  31. package/dist/registry/tools.js +85 -18
  32. package/dist/registry/tools.js.map +1 -1
  33. package/dist/runtime/config.d.ts +7 -1
  34. package/dist/runtime/config.d.ts.map +1 -1
  35. package/dist/runtime/config.js +8 -0
  36. package/dist/runtime/config.js.map +1 -1
  37. package/dist/runtime/instance.d.ts.map +1 -1
  38. package/dist/runtime/instance.js +7 -2
  39. package/dist/runtime/instance.js.map +1 -1
  40. package/dist/runtime/lock.d.ts +4 -2
  41. package/dist/runtime/lock.d.ts.map +1 -1
  42. package/dist/runtime/lock.js +26 -37
  43. package/dist/runtime/lock.js.map +1 -1
  44. package/dist/runtime/paths.d.ts.map +1 -1
  45. package/dist/runtime/paths.js +8 -1
  46. package/dist/runtime/paths.js.map +1 -1
  47. package/dist/runtime/state.d.ts.map +1 -1
  48. package/dist/runtime/state.js +4 -11
  49. package/dist/runtime/state.js.map +1 -1
  50. package/dist/runtime/unitup.d.ts +10 -2
  51. package/dist/runtime/unitup.d.ts.map +1 -1
  52. package/dist/runtime/unitup.js +96 -3
  53. package/dist/runtime/unitup.js.map +1 -1
  54. package/dist/server/app.d.ts +34 -1
  55. package/dist/server/app.d.ts.map +1 -1
  56. package/dist/server/app.js +406 -199
  57. package/dist/server/app.js.map +1 -1
  58. package/dist/server/hono.d.ts +3 -0
  59. package/dist/server/hono.d.ts.map +1 -1
  60. package/dist/server/hono.js +176 -50
  61. package/dist/server/hono.js.map +1 -1
  62. package/dist/server/inspector.d.ts.map +1 -1
  63. package/dist/server/inspector.js +12 -2
  64. package/dist/server/inspector.js.map +1 -1
  65. package/dist/server/mcp.d.ts +25 -5
  66. package/dist/server/mcp.d.ts.map +1 -1
  67. package/dist/server/mcp.js +422 -295
  68. package/dist/server/mcp.js.map +1 -1
  69. package/dist/transport/proxy.d.ts.map +1 -1
  70. package/dist/transport/proxy.js +18 -16
  71. package/dist/transport/proxy.js.map +1 -1
  72. package/dist/types.d.ts +177 -4
  73. package/dist/types.d.ts.map +1 -1
  74. package/dist/utils/cache.d.ts.map +1 -1
  75. package/dist/utils/cache.js +3 -2
  76. package/dist/utils/cache.js.map +1 -1
  77. package/dist/utils/coercion.d.ts +3 -3
  78. package/dist/utils/coercion.d.ts.map +1 -1
  79. package/dist/utils/coercion.js +101 -12
  80. package/dist/utils/coercion.js.map +1 -1
  81. package/dist/utils/elicitation.d.ts +34 -0
  82. package/dist/utils/elicitation.d.ts.map +1 -0
  83. package/dist/utils/elicitation.js +136 -0
  84. package/dist/utils/elicitation.js.map +1 -0
  85. package/dist/utils/media.d.ts +41 -6
  86. package/dist/utils/media.d.ts.map +1 -1
  87. package/dist/utils/media.js +162 -7
  88. package/dist/utils/media.js.map +1 -1
  89. package/dist/utils/retry.d.ts +20 -1
  90. package/dist/utils/retry.d.ts.map +1 -1
  91. package/dist/utils/retry.js +103 -7
  92. package/dist/utils/retry.js.map +1 -1
  93. package/dist/utils/security.d.ts +12 -0
  94. package/dist/utils/security.d.ts.map +1 -1
  95. package/dist/utils/security.js +47 -0
  96. package/dist/utils/security.js.map +1 -1
  97. package/package.json +14 -5
@@ -4,7 +4,6 @@ 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 { StateManager } from '../runtime/state.js';
8
7
  import { LockManager } from '../runtime/lock.js';
9
8
  import { checkHealth, fetchInfo, isPidRunning } from '../runtime/health.js';
10
9
  import { DefaultLogger } from '../logging/logger.js';
@@ -13,10 +12,11 @@ import { ResourceRegistry } from '../registry/resources.js';
13
12
  import { SubscriptionRegistry } from '../registry/subscriptions.js';
14
13
  import { PromptRegistry } from '../registry/prompts.js';
15
14
  import { ContextManager } from './context.js';
16
- import { normalizeToolResult } from './mcp.js';
15
+ import { normalizeToolResult, registerSingleTool, registerSingleResource, registerSingleTemplate, registerSinglePrompt } from './mcp.js';
17
16
  import { normalizeResourceResult } from '../utils/media.js';
18
17
  import { createHonoApp } from './hono.js';
19
18
  import { executeSample, executeListRoots } from '../utils/sampling.js';
19
+ import { executeElicit } from '../utils/elicitation.js';
20
20
  import { createOpenApiTools } from '../utils/openapi.js';
21
21
  import { startHttpServer } from '../transport/http.js';
22
22
  import { startStdioProxy } from '../transport/proxy.js';
@@ -27,6 +27,7 @@ import { ToolCacheManager } from '../utils/cache.js';
27
27
  import { executeWithRetry, raceWithSignal } from '../utils/retry.js';
28
28
  import { coerceArguments } from '../utils/coercion.js';
29
29
  import { createProgressReporter } from '../utils/progress.js';
30
+ import { createToolLogger } from '../logging/mcp-logger.js';
30
31
  import { MiddlewareManager } from '../utils/middleware.js';
31
32
  import { getUnitup, startBackgroundProcess, stopBackgroundProcess } from '../runtime/unitup.js';
32
33
  export class McpApp {
@@ -45,14 +46,23 @@ export class McpApp {
45
46
  instanceCoordinator;
46
47
  stateManager;
47
48
  lockManager;
48
- centralRegistry = new CentralRegistry();
49
+ bootstrapLockManager;
50
+ _centralRegistry;
51
+ get centralRegistry() {
52
+ if (!this._centralRegistry) {
53
+ this._centralRegistry = new CentralRegistry();
54
+ }
55
+ return this._centralRegistry;
56
+ }
49
57
  httpHandle;
50
58
  stdioProxyHandle;
59
+ httpCleanupCallbacks = [];
51
60
  sessions = new Map();
52
61
  metrics;
53
62
  isOwner = false;
54
63
  sampleFallback;
55
64
  listRootsFallback;
65
+ elicitFallback;
56
66
  rootsListChangedListeners = [];
57
67
  constructor(config) {
58
68
  this.config = resolveConfig(config);
@@ -64,6 +74,9 @@ export class McpApp {
64
74
  if (raw.onListRoots) {
65
75
  this.listRootsFallback = raw.onListRoots;
66
76
  }
77
+ if (raw.onElicit) {
78
+ this.elicitFallback = raw.onElicit;
79
+ }
67
80
  }
68
81
  this.logger = raw.logger || new DefaultLogger({
69
82
  logDir: this.config.logDir,
@@ -77,8 +90,9 @@ export class McpApp {
77
90
  });
78
91
  this.middlewareManager = new MiddlewareManager(raw.middleware);
79
92
  this.instanceCoordinator = new InstanceCoordinator(this.config);
80
- this.stateManager = new StateManager(this.config.dataDir);
81
- this.lockManager = new LockManager(this.config.dataDir);
93
+ this.stateManager = this.instanceCoordinator.stateManager;
94
+ this.lockManager = this.instanceCoordinator.lockManager;
95
+ this.bootstrapLockManager = new LockManager(this.config.dataDir, 'bootstrap.lock');
82
96
  this.metrics = {
83
97
  startedAt: new Date().toISOString(),
84
98
  activeSessions: 0,
@@ -136,37 +150,56 @@ export class McpApp {
136
150
  return this;
137
151
  }
138
152
  tool(nameOrDef, descOrSchemaOrHandler, schemaOrHandler, maybeHandler) {
153
+ let toolDef;
139
154
  if (typeof nameOrDef === 'object' && nameOrDef !== null) {
140
- this.toolRegistry.register(nameOrDef);
141
- return this;
142
- }
143
- const name = nameOrDef;
144
- let description;
145
- let inputSchema;
146
- let handler;
147
- if (typeof descOrSchemaOrHandler === 'function') {
148
- handler = descOrSchemaOrHandler;
149
- }
150
- else if (typeof descOrSchemaOrHandler === 'string') {
151
- description = descOrSchemaOrHandler;
152
- if (typeof schemaOrHandler === 'function') {
153
- handler = schemaOrHandler;
155
+ toolDef = nameOrDef;
156
+ }
157
+ else {
158
+ const name = nameOrDef;
159
+ let description;
160
+ let inputSchema;
161
+ let handler;
162
+ if (typeof descOrSchemaOrHandler === 'function') {
163
+ handler = descOrSchemaOrHandler;
164
+ }
165
+ else if (typeof descOrSchemaOrHandler === 'string') {
166
+ description = descOrSchemaOrHandler;
167
+ if (typeof schemaOrHandler === 'function') {
168
+ handler = schemaOrHandler;
169
+ }
170
+ else {
171
+ inputSchema = schemaOrHandler;
172
+ handler = maybeHandler;
173
+ }
154
174
  }
155
175
  else {
156
- inputSchema = schemaOrHandler;
157
- handler = maybeHandler;
176
+ inputSchema = descOrSchemaOrHandler;
177
+ handler = schemaOrHandler;
158
178
  }
179
+ toolDef = {
180
+ name,
181
+ description,
182
+ inputSchema: inputSchema,
183
+ handler
184
+ };
185
+ }
186
+ const registered = this.toolRegistry.register(toolDef);
187
+ if (this.sessions.size > 0) {
188
+ for (const session of this.sessions.values()) {
189
+ if (session.server && session.server._sessionOptions) {
190
+ try {
191
+ registerSingleTool(session.server, registered, session.server._sessionOptions, session.server._sessionCtx);
192
+ }
193
+ catch (err) {
194
+ this.logger.debug('Failed to dynamically register tool on session', {
195
+ tool: registered.name,
196
+ error: err.message
197
+ });
198
+ }
199
+ }
200
+ }
201
+ this.notifyToolListChanged().catch(() => { });
159
202
  }
160
- else {
161
- inputSchema = descOrSchemaOrHandler;
162
- handler = schemaOrHandler;
163
- }
164
- this.toolRegistry.register({
165
- name,
166
- description,
167
- inputSchema: inputSchema,
168
- handler
169
- });
170
203
  return this;
171
204
  }
172
205
  /**
@@ -337,6 +370,14 @@ export class McpApp {
337
370
  const listRootsHelper = () => {
338
371
  return executeListRoots(sessionServer, this.listRootsFallback, mergedSignal);
339
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
+ });
340
381
  const extra = {
341
382
  signal: mergedSignal,
342
383
  callTool: callToolHelper,
@@ -345,7 +386,9 @@ export class McpApp {
345
386
  progressToken: options.progressToken,
346
387
  sample: sampleHelper,
347
388
  listRoots: listRootsHelper,
348
- auth: options.auth
389
+ elicit: elicitHelper,
390
+ auth: options.auth,
391
+ log: logHelper
349
392
  };
350
393
  const queueConfig = this.resolveQueueConfig(tool, options, callStack.length > 0);
351
394
  let release;
@@ -368,7 +411,9 @@ export class McpApp {
368
411
  reportProgress,
369
412
  sample: sampleHelper,
370
413
  listRoots: listRootsHelper,
371
- auth: options.auth
414
+ elicit: elicitHelper,
415
+ auth: options.auth,
416
+ log: logHelper
372
417
  })
373
418
  : {
374
419
  callTool: callToolHelper,
@@ -377,7 +422,9 @@ export class McpApp {
377
422
  reportProgress,
378
423
  sample: sampleHelper,
379
424
  listRoots: listRootsHelper,
380
- auth: options.auth
425
+ elicit: elicitHelper,
426
+ auth: options.auth,
427
+ log: logHelper
381
428
  };
382
429
  this.logger.info('tool:start', { name: tool.name, caller: callStack[callStack.length - 1] });
383
430
  const effectiveRetry = options.retry !== undefined ? options.retry : tool.retry;
@@ -565,6 +612,23 @@ export class McpApp {
565
612
  */
566
613
  resourceTemplate(definition) {
567
614
  this.resourceRegistry.registerTemplate(definition);
615
+ if (this.sessions.size > 0) {
616
+ const ctx = this.contextManager.getContext();
617
+ for (const session of this.sessions.values()) {
618
+ if (session.server) {
619
+ try {
620
+ registerSingleTemplate(session.server, definition, ctx);
621
+ }
622
+ catch (err) {
623
+ this.logger.debug('Failed to dynamically register resource template on session', {
624
+ template: definition.uriTemplate,
625
+ error: err.message
626
+ });
627
+ }
628
+ }
629
+ }
630
+ this.notifyResourceListChanged().catch(() => { });
631
+ }
568
632
  return this;
569
633
  }
570
634
  /**
@@ -575,8 +639,7 @@ export class McpApp {
575
639
  resource(definition) {
576
640
  if ('uriTemplate' in definition &&
577
641
  typeof definition.uriTemplate === 'string') {
578
- this.resourceRegistry.registerTemplate(definition);
579
- return this;
642
+ return this.resourceTemplate(definition);
580
643
  }
581
644
  const staticDef = definition;
582
645
  if (staticDef.uri && staticDef.uri.includes('{') && staticDef.uri.includes('}')) {
@@ -587,10 +650,26 @@ export class McpApp {
587
650
  mimeType: staticDef.mimeType,
588
651
  handler: (uri, params, ctx) => staticDef.handler(uri, params, ctx)
589
652
  };
590
- this.resourceRegistry.registerTemplate(templateDef);
591
- return this;
653
+ return this.resourceTemplate(templateDef);
592
654
  }
593
655
  this.resourceRegistry.register(staticDef);
656
+ if (this.sessions.size > 0) {
657
+ const ctx = this.contextManager.getContext();
658
+ for (const session of this.sessions.values()) {
659
+ if (session.server) {
660
+ try {
661
+ registerSingleResource(session.server, staticDef, ctx);
662
+ }
663
+ catch (err) {
664
+ this.logger.debug('Failed to dynamically register resource on session', {
665
+ uri: staticDef.uri,
666
+ error: err.message
667
+ });
668
+ }
669
+ }
670
+ }
671
+ this.notifyResourceListChanged().catch(() => { });
672
+ }
594
673
  return this;
595
674
  }
596
675
  /**
@@ -598,6 +677,23 @@ export class McpApp {
598
677
  */
599
678
  prompt(definition) {
600
679
  this.promptRegistry.register(definition);
680
+ if (this.sessions.size > 0) {
681
+ const ctx = this.contextManager.getContext();
682
+ for (const session of this.sessions.values()) {
683
+ if (session.server) {
684
+ try {
685
+ registerSinglePrompt(session.server, definition, ctx);
686
+ }
687
+ catch (err) {
688
+ this.logger.debug('Failed to dynamically register prompt on session', {
689
+ prompt: definition.name,
690
+ error: err.message
691
+ });
692
+ }
693
+ }
694
+ }
695
+ this.notifyPromptListChanged().catch(() => { });
696
+ }
601
697
  return this;
602
698
  }
603
699
  /**
@@ -709,6 +805,52 @@ export class McpApp {
709
805
  }
710
806
  return notifiedCount;
711
807
  }
808
+ /**
809
+ * Notifies connected MCP clients that the list of available tools has changed.
810
+ * Sends `notifications/tools/list_changed`.
811
+ * Returns the count of client sessions successfully notified.
812
+ */
813
+ async notifyToolListChanged() {
814
+ let notifiedCount = 0;
815
+ for (const [sessionId, session] of this.sessions.entries()) {
816
+ if (session.server?.server) {
817
+ try {
818
+ await session.server.server.sendToolListChanged();
819
+ notifiedCount++;
820
+ }
821
+ catch (err) {
822
+ this.logger.debug('Failed to send tool list changed notification to session', {
823
+ session: sessionId,
824
+ error: err.message
825
+ });
826
+ }
827
+ }
828
+ }
829
+ return notifiedCount;
830
+ }
831
+ /**
832
+ * Notifies connected MCP clients that the list of available prompts has changed.
833
+ * Sends `notifications/prompts/list_changed`.
834
+ * Returns the count of client sessions successfully notified.
835
+ */
836
+ async notifyPromptListChanged() {
837
+ let notifiedCount = 0;
838
+ for (const [sessionId, session] of this.sessions.entries()) {
839
+ if (session.server?.server) {
840
+ try {
841
+ await session.server.server.sendPromptListChanged();
842
+ notifiedCount++;
843
+ }
844
+ catch (err) {
845
+ this.logger.debug('Failed to send prompt list changed notification to session', {
846
+ session: sessionId,
847
+ error: err.message
848
+ });
849
+ }
850
+ }
851
+ }
852
+ return notifiedCount;
853
+ }
712
854
  /**
713
855
  * Notifies connected MCP clients that the list of available resources has changed.
714
856
  * Sends `notifications/resources/list_changed`.
@@ -782,6 +924,22 @@ export class McpApp {
782
924
  this.listRootsFallback = handler;
783
925
  return this;
784
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
+ }
785
943
  /**
786
944
  * Listens for client roots/list_changed notifications.
787
945
  * Returns an unbind function.
@@ -869,66 +1027,106 @@ export class McpApp {
869
1027
  };
870
1028
  }
871
1029
  /**
872
- * Starts the server programmatically. If a server is already running,
873
- * 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.
874
1033
  */
875
- async start(options = {}) {
876
- const isBackgroundWorker = process.env.MCPONCE_BACKGROUND_SERVER === '1' ||
877
- process.argv.includes('--mcponce-background');
878
- const shouldRunBackground = options.background !== undefined ? options.background : this.config.background;
879
- if (shouldRunBackground && !isBackgroundWorker && !options.noSingleton) {
880
- await getUnitup();
881
- const existingState = this.stateManager.read();
882
- if (existingState && existingState.name === this.config.name) {
883
- const health = await checkHealth(existingState.host, existingState.port, this.config.name, 1000);
884
- if (health) {
885
- return {
886
- reused: true,
887
- role: 'bridge',
888
- pid: existingState.pid,
889
- port: existingState.port,
890
- host: existingState.host
891
- };
892
- }
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;
893
1042
  }
894
- const initialLock = this.lockManager.readLock();
895
- if (!initialLock || !isPidRunning(initialLock.pid)) {
896
- this.lockManager.forceRelease();
897
- this.stateManager.forceClean();
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));
898
1052
  }
899
- if (this.lockManager.tryAcquire(this.config.name)) {
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();
1073
+ }
1074
+ if (this.bootstrapLockManager.tryAcquire(this.config.name)) {
900
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
+ }
901
1087
  await startBackgroundProcess({
902
1088
  name: this.config.name,
903
1089
  scriptPath: this.config.entrypoint,
904
1090
  dataDir: this.config.dataDir,
905
1091
  logDir: this.config.logDir
906
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 };
907
1103
  }
908
1104
  finally {
909
- this.lockManager.release();
910
- }
911
- }
912
- const maxWaitMs = 20000;
913
- const startTime = Date.now();
914
- let healthyState = null;
915
- while (Date.now() - startTime < maxWaitMs) {
916
- await new Promise((r) => setTimeout(r, 25));
917
- const st = this.stateManager.read();
918
- if (st && st.name === this.config.name) {
919
- const h = await checkHealth(st.host, st.port, this.config.name, 300);
920
- if (h) {
921
- healthyState = st;
922
- break;
923
- }
1105
+ this.bootstrapLockManager.release();
924
1106
  }
925
1107
  }
926
- if (!healthyState) {
927
- 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 };
928
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();
929
1127
  return {
930
- reused: false,
931
- role: 'owner',
1128
+ reused,
1129
+ role: reused ? 'bridge' : 'owner',
932
1130
  pid: healthyState.pid,
933
1131
  port: healthyState.port,
934
1132
  host: healthyState.host
@@ -949,35 +1147,46 @@ export class McpApp {
949
1147
  }
950
1148
  // Role is owner: initialize context and start HTTP server
951
1149
  this.isOwner = true;
952
- await this.contextManager.initialize(this.logger);
953
- let currentPort = this.config.port;
954
- const honoApp = createHonoApp({
955
- config: this.config,
956
- toolRegistry: this.toolRegistry,
957
- resourceRegistry: this.resourceRegistry,
958
- promptRegistry: this.promptRegistry,
959
- contextManager: this.contextManager,
960
- metrics: this.metrics,
961
- analytics: this.analytics,
962
- portProvider: () => currentPort,
963
- callTool: (name, args, options, stack) => this.callTool(name, args, options, stack),
964
- logger: this.logger,
965
- queueManager: this.queueManager,
966
- cacheManager: this.cacheManager,
967
- middlewareManager: this.middlewareManager,
968
- resolveQueueConfig: (tool, opts) => this.resolveQueueConfig(tool, opts),
969
- sessions: this.sessions,
970
- subscriptionRegistry: this.subscriptionRegistry,
971
- onSample: this.sampleFallback,
972
- onListRoots: this.listRootsFallback,
973
- onRootsListChanged: (roots) => {
974
- for (const listener of this.rootsListChangedListeners) {
975
- 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
+ }
976
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();
977
1187
  }
978
- });
979
- this.httpHandle = await startHttpServer(honoApp, this.config.host, this.config.port);
980
- currentPort = this.httpHandle.port;
1188
+ throw err;
1189
+ }
981
1190
  this.stateManager.write({
982
1191
  name: this.config.name,
983
1192
  version: this.config.version,
@@ -1023,6 +1232,31 @@ export class McpApp {
1023
1232
  await this.stdioProxyHandle.close();
1024
1233
  this.stdioProxyHandle = undefined;
1025
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
+ }
1026
1260
  if (this.httpHandle) {
1027
1261
  await this.httpHandle.close();
1028
1262
  this.httpHandle = undefined;
@@ -1030,7 +1264,7 @@ export class McpApp {
1030
1264
  const shouldStopBackground = options.background !== undefined ? options.background : this.config.background;
1031
1265
  if (shouldStopBackground) {
1032
1266
  try {
1033
- await stopBackgroundProcess(this.config.name);
1267
+ await stopBackgroundProcess(this.config.name, this.config.dataDir);
1034
1268
  }
1035
1269
  catch { }
1036
1270
  if (this.config.registerInCentral) {
@@ -1041,6 +1275,7 @@ export class McpApp {
1041
1275
  }
1042
1276
  this.stateManager.forceClean();
1043
1277
  this.lockManager.forceRelease();
1278
+ this.bootstrapLockManager.forceRelease();
1044
1279
  this.isOwner = false;
1045
1280
  return;
1046
1281
  }
@@ -1096,6 +1331,15 @@ export class McpApp {
1096
1331
  process.argv.includes('--mcponce-background');
1097
1332
  if (isBackgroundWorker) {
1098
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
+ }
1099
1343
  this.logger.info('Background MCP worker running', {
1100
1344
  name: this.config.name,
1101
1345
  pid: process.pid,
@@ -1113,58 +1357,10 @@ export class McpApp {
1113
1357
  }
1114
1358
  const backgroundMode = this.config.background || cliOptions.background;
1115
1359
  if (backgroundMode) {
1116
- await getUnitup();
1117
- let targetPort;
1118
- let targetHost;
1119
- let serverPid;
1120
- const existingState = this.stateManager.read();
1121
- const isHealthy = existingState && existingState.name === this.config.name
1122
- ? await checkHealth(existingState.host, existingState.port, this.config.name, 1000)
1123
- : null;
1124
- if (isHealthy && existingState) {
1125
- targetPort = existingState.port;
1126
- targetHost = existingState.host;
1127
- serverPid = existingState.pid;
1128
- }
1129
- else {
1130
- if (existingState && !isHealthy) {
1131
- this.lockManager.forceRelease();
1132
- this.stateManager.forceClean();
1133
- }
1134
- if (this.lockManager.tryAcquire(this.config.name)) {
1135
- try {
1136
- await startBackgroundProcess({
1137
- name: this.config.name,
1138
- scriptPath: this.config.entrypoint,
1139
- dataDir: this.config.dataDir,
1140
- logDir: this.config.logDir
1141
- });
1142
- }
1143
- finally {
1144
- this.lockManager.release();
1145
- }
1146
- }
1147
- const maxWaitMs = 20000;
1148
- const start = Date.now();
1149
- let healthyState = null;
1150
- while (Date.now() - start < maxWaitMs) {
1151
- await new Promise((r) => setTimeout(r, 25));
1152
- const st = this.stateManager.read();
1153
- if (st && st.name === this.config.name) {
1154
- const h = await checkHealth(st.host, st.port, this.config.name, 300);
1155
- if (h) {
1156
- healthyState = st;
1157
- break;
1158
- }
1159
- }
1160
- }
1161
- if (!healthyState) {
1162
- throw new Error(`Failed to start background MCP server for "${this.config.name}" through Unitup: health check timed out`);
1163
- }
1164
- targetPort = healthyState.port;
1165
- targetHost = healthyState.host;
1166
- serverPid = healthyState.pid;
1167
- }
1360
+ const { state: healthyState } = await this.ensureBackgroundWorkerStarted();
1361
+ const targetPort = healthyState.port;
1362
+ const targetHost = healthyState.host;
1363
+ const serverPid = healthyState.pid;
1168
1364
  this.logger.info('bridge:start', {
1169
1365
  pid: process.pid,
1170
1366
  serverPid,
@@ -1191,45 +1387,56 @@ export class McpApp {
1191
1387
  let ownerStdioClosed = false;
1192
1388
  if (roleResult.role === 'owner') {
1193
1389
  this.isOwner = true;
1194
- await this.contextManager.initialize(this.logger);
1195
- let currentPort = this.config.port;
1196
- const honoApp = createHonoApp({
1197
- config: this.config,
1198
- toolRegistry: this.toolRegistry,
1199
- resourceRegistry: this.resourceRegistry,
1200
- promptRegistry: this.promptRegistry,
1201
- contextManager: this.contextManager,
1202
- metrics: this.metrics,
1203
- analytics: this.analytics,
1204
- portProvider: () => currentPort,
1205
- callTool: (name, args, options, stack) => this.callTool(name, args, options, stack),
1206
- logger: this.logger,
1207
- queueManager: this.queueManager,
1208
- cacheManager: this.cacheManager,
1209
- middlewareManager: this.middlewareManager,
1210
- resolveQueueConfig: (tool, opts) => this.resolveQueueConfig(tool, opts),
1211
- sessions: this.sessions,
1212
- subscriptionRegistry: this.subscriptionRegistry,
1213
- onSample: this.sampleFallback,
1214
- onListRoots: this.listRootsFallback,
1215
- onRootsListChanged: (roots) => {
1216
- for (const listener of this.rootsListChangedListeners) {
1217
- listener(roots);
1218
- }
1219
- },
1220
- onSessionClosed: () => {
1221
- if (ownerStdioClosed && this.sessions.size === 0) {
1222
- this.logger.info('All sessions closed after owner stdio ended, shutting down', {
1223
- pid: process.pid
1224
- });
1225
- 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
+ }
1226
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();
1227
1437
  }
1228
- });
1229
- this.httpHandle = await startHttpServer(honoApp, this.config.host, this.config.port);
1230
- currentPort = this.httpHandle.port;
1231
- targetPort = this.httpHandle.port;
1232
- targetHost = this.httpHandle.host;
1438
+ throw err;
1439
+ }
1233
1440
  this.stateManager.write({
1234
1441
  name: this.config.name,
1235
1442
  version: this.config.version,