mcponce 0.1.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 (186) hide show
  1. package/README.md +1013 -0
  2. package/dist/cli/analytics.d.ts +5 -0
  3. package/dist/cli/analytics.d.ts.map +1 -0
  4. package/dist/cli/analytics.js +93 -0
  5. package/dist/cli/analytics.js.map +1 -0
  6. package/dist/cli/bin.d.ts +20 -0
  7. package/dist/cli/bin.d.ts.map +1 -0
  8. package/dist/cli/bin.js +510 -0
  9. package/dist/cli/bin.js.map +1 -0
  10. package/dist/cli/index.d.ts +9 -0
  11. package/dist/cli/index.d.ts.map +1 -0
  12. package/dist/cli/index.js +196 -0
  13. package/dist/cli/index.js.map +1 -0
  14. package/dist/cli/info.d.ts +3 -0
  15. package/dist/cli/info.d.ts.map +1 -0
  16. package/dist/cli/info.js +42 -0
  17. package/dist/cli/info.js.map +1 -0
  18. package/dist/cli/installer.d.ts +64 -0
  19. package/dist/cli/installer.d.ts.map +1 -0
  20. package/dist/cli/installer.js +183 -0
  21. package/dist/cli/installer.js.map +1 -0
  22. package/dist/cli/logs.d.ts +3 -0
  23. package/dist/cli/logs.d.ts.map +1 -0
  24. package/dist/cli/logs.js +19 -0
  25. package/dist/cli/logs.js.map +1 -0
  26. package/dist/cli/tool-caller.d.ts +70 -0
  27. package/dist/cli/tool-caller.d.ts.map +1 -0
  28. package/dist/cli/tool-caller.js +404 -0
  29. package/dist/cli/tool-caller.js.map +1 -0
  30. package/dist/index.d.ts +31 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +27 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/logging/file-logger.d.ts +21 -0
  35. package/dist/logging/file-logger.d.ts.map +1 -0
  36. package/dist/logging/file-logger.js +96 -0
  37. package/dist/logging/file-logger.js.map +1 -0
  38. package/dist/logging/logger.d.ts +22 -0
  39. package/dist/logging/logger.d.ts.map +1 -0
  40. package/dist/logging/logger.js +57 -0
  41. package/dist/logging/logger.js.map +1 -0
  42. package/dist/logging/rotation.d.ts +6 -0
  43. package/dist/logging/rotation.d.ts.map +1 -0
  44. package/dist/logging/rotation.js +32 -0
  45. package/dist/logging/rotation.js.map +1 -0
  46. package/dist/registry/central.d.ts +54 -0
  47. package/dist/registry/central.d.ts.map +1 -0
  48. package/dist/registry/central.js +205 -0
  49. package/dist/registry/central.js.map +1 -0
  50. package/dist/registry/prompts.d.ts +9 -0
  51. package/dist/registry/prompts.d.ts.map +1 -0
  52. package/dist/registry/prompts.js +18 -0
  53. package/dist/registry/prompts.js.map +1 -0
  54. package/dist/registry/resources.d.ts +52 -0
  55. package/dist/registry/resources.d.ts.map +1 -0
  56. package/dist/registry/resources.js +102 -0
  57. package/dist/registry/resources.js.map +1 -0
  58. package/dist/registry/subscriptions.d.ts +44 -0
  59. package/dist/registry/subscriptions.d.ts.map +1 -0
  60. package/dist/registry/subscriptions.js +96 -0
  61. package/dist/registry/subscriptions.js.map +1 -0
  62. package/dist/registry/tools.d.ts +24 -0
  63. package/dist/registry/tools.d.ts.map +1 -0
  64. package/dist/registry/tools.js +120 -0
  65. package/dist/registry/tools.js.map +1 -0
  66. package/dist/runtime/config.d.ts +30 -0
  67. package/dist/runtime/config.d.ts.map +1 -0
  68. package/dist/runtime/config.js +79 -0
  69. package/dist/runtime/config.js.map +1 -0
  70. package/dist/runtime/health.d.ts +15 -0
  71. package/dist/runtime/health.d.ts.map +1 -0
  72. package/dist/runtime/health.js +63 -0
  73. package/dist/runtime/health.js.map +1 -0
  74. package/dist/runtime/instance.d.ts +33 -0
  75. package/dist/runtime/instance.d.ts.map +1 -0
  76. package/dist/runtime/instance.js +148 -0
  77. package/dist/runtime/instance.js.map +1 -0
  78. package/dist/runtime/lock.d.ts +33 -0
  79. package/dist/runtime/lock.d.ts.map +1 -0
  80. package/dist/runtime/lock.js +105 -0
  81. package/dist/runtime/lock.js.map +1 -0
  82. package/dist/runtime/paths.d.ts +16 -0
  83. package/dist/runtime/paths.d.ts.map +1 -0
  84. package/dist/runtime/paths.js +54 -0
  85. package/dist/runtime/paths.js.map +1 -0
  86. package/dist/runtime/state.d.ts +24 -0
  87. package/dist/runtime/state.d.ts.map +1 -0
  88. package/dist/runtime/state.js +71 -0
  89. package/dist/runtime/state.js.map +1 -0
  90. package/dist/runtime/unitup.d.ts +44 -0
  91. package/dist/runtime/unitup.d.ts.map +1 -0
  92. package/dist/runtime/unitup.js +134 -0
  93. package/dist/runtime/unitup.js.map +1 -0
  94. package/dist/server/analytics.d.ts +47 -0
  95. package/dist/server/analytics.d.ts.map +1 -0
  96. package/dist/server/analytics.js +327 -0
  97. package/dist/server/analytics.js.map +1 -0
  98. package/dist/server/app.d.ts +249 -0
  99. package/dist/server/app.d.ts.map +1 -0
  100. package/dist/server/app.js +1332 -0
  101. package/dist/server/app.js.map +1 -0
  102. package/dist/server/context.d.ts +12 -0
  103. package/dist/server/context.d.ts.map +1 -0
  104. package/dist/server/context.js +52 -0
  105. package/dist/server/context.js.map +1 -0
  106. package/dist/server/hono.d.ts +54 -0
  107. package/dist/server/hono.d.ts.map +1 -0
  108. package/dist/server/hono.js +423 -0
  109. package/dist/server/hono.js.map +1 -0
  110. package/dist/server/inspector.d.ts +21 -0
  111. package/dist/server/inspector.d.ts.map +1 -0
  112. package/dist/server/inspector.js +834 -0
  113. package/dist/server/inspector.js.map +1 -0
  114. package/dist/server/mcp.d.ts +41 -0
  115. package/dist/server/mcp.d.ts.map +1 -0
  116. package/dist/server/mcp.js +425 -0
  117. package/dist/server/mcp.js.map +1 -0
  118. package/dist/transport/http.d.ts +14 -0
  119. package/dist/transport/http.d.ts.map +1 -0
  120. package/dist/transport/http.js +48 -0
  121. package/dist/transport/http.js.map +1 -0
  122. package/dist/transport/proxy.d.ts +12 -0
  123. package/dist/transport/proxy.d.ts.map +1 -0
  124. package/dist/transport/proxy.js +115 -0
  125. package/dist/transport/proxy.js.map +1 -0
  126. package/dist/types.d.ts +602 -0
  127. package/dist/types.d.ts.map +1 -0
  128. package/dist/types.js +2 -0
  129. package/dist/types.js.map +1 -0
  130. package/dist/utils/browser.d.ts +6 -0
  131. package/dist/utils/browser.d.ts.map +1 -0
  132. package/dist/utils/browser.js +39 -0
  133. package/dist/utils/browser.js.map +1 -0
  134. package/dist/utils/cache.d.ts +43 -0
  135. package/dist/utils/cache.d.ts.map +1 -0
  136. package/dist/utils/cache.js +126 -0
  137. package/dist/utils/cache.js.map +1 -0
  138. package/dist/utils/coercion.d.ts +38 -0
  139. package/dist/utils/coercion.d.ts.map +1 -0
  140. package/dist/utils/coercion.js +175 -0
  141. package/dist/utils/coercion.js.map +1 -0
  142. package/dist/utils/completion.d.ts +30 -0
  143. package/dist/utils/completion.d.ts.map +1 -0
  144. package/dist/utils/completion.js +79 -0
  145. package/dist/utils/completion.js.map +1 -0
  146. package/dist/utils/media.d.ts +65 -0
  147. package/dist/utils/media.d.ts.map +1 -0
  148. package/dist/utils/media.js +305 -0
  149. package/dist/utils/media.js.map +1 -0
  150. package/dist/utils/middleware.d.ts +48 -0
  151. package/dist/utils/middleware.d.ts.map +1 -0
  152. package/dist/utils/middleware.js +133 -0
  153. package/dist/utils/middleware.js.map +1 -0
  154. package/dist/utils/openapi.d.ts +102 -0
  155. package/dist/utils/openapi.d.ts.map +1 -0
  156. package/dist/utils/openapi.js +368 -0
  157. package/dist/utils/openapi.js.map +1 -0
  158. package/dist/utils/progress.d.ts +26 -0
  159. package/dist/utils/progress.d.ts.map +1 -0
  160. package/dist/utils/progress.js +91 -0
  161. package/dist/utils/progress.js.map +1 -0
  162. package/dist/utils/queue.d.ts +51 -0
  163. package/dist/utils/queue.d.ts.map +1 -0
  164. package/dist/utils/queue.js +136 -0
  165. package/dist/utils/queue.js.map +1 -0
  166. package/dist/utils/retry.d.ts +26 -0
  167. package/dist/utils/retry.d.ts.map +1 -0
  168. package/dist/utils/retry.js +125 -0
  169. package/dist/utils/retry.js.map +1 -0
  170. package/dist/utils/roots.d.ts +21 -0
  171. package/dist/utils/roots.d.ts.map +1 -0
  172. package/dist/utils/roots.js +74 -0
  173. package/dist/utils/roots.js.map +1 -0
  174. package/dist/utils/sampling.d.ts +129 -0
  175. package/dist/utils/sampling.d.ts.map +1 -0
  176. package/dist/utils/sampling.js +177 -0
  177. package/dist/utils/sampling.js.map +1 -0
  178. package/dist/utils/security.d.ts +35 -0
  179. package/dist/utils/security.d.ts.map +1 -0
  180. package/dist/utils/security.js +113 -0
  181. package/dist/utils/security.js.map +1 -0
  182. package/dist/utils/validation.d.ts +52 -0
  183. package/dist/utils/validation.d.ts.map +1 -0
  184. package/dist/utils/validation.js +176 -0
  185. package/dist/utils/validation.js.map +1 -0
  186. package/package.json +61 -0
@@ -0,0 +1,1332 @@
1
+ import { z } from 'zod';
2
+ import { verifyToolScopes } from '../utils/security.js';
3
+ import { resolveCompletion } from '../utils/completion.js';
4
+ import { AnalyticsCollector } from './analytics.js';
5
+ import { resolveConfig } from '../runtime/config.js';
6
+ import { InstanceCoordinator } from '../runtime/instance.js';
7
+ import { StateManager } from '../runtime/state.js';
8
+ import { LockManager } from '../runtime/lock.js';
9
+ import { checkHealth, fetchInfo, isPidRunning } from '../runtime/health.js';
10
+ import { DefaultLogger } from '../logging/logger.js';
11
+ import { ToolRegistry, normalizeInputSchema } from '../registry/tools.js';
12
+ import { ResourceRegistry } from '../registry/resources.js';
13
+ import { SubscriptionRegistry } from '../registry/subscriptions.js';
14
+ import { PromptRegistry } from '../registry/prompts.js';
15
+ import { ContextManager } from './context.js';
16
+ import { normalizeToolResult } from './mcp.js';
17
+ import { normalizeResourceResult } from '../utils/media.js';
18
+ import { createHonoApp } from './hono.js';
19
+ import { executeSample, executeListRoots } from '../utils/sampling.js';
20
+ import { createOpenApiTools } from '../utils/openapi.js';
21
+ import { startHttpServer } from '../transport/http.js';
22
+ import { startStdioProxy } from '../transport/proxy.js';
23
+ import { handleCliArgs } from '../cli/index.js';
24
+ import { CentralRegistry } from '../registry/central.js';
25
+ import { QueueManager } from '../utils/queue.js';
26
+ import { ToolCacheManager } from '../utils/cache.js';
27
+ import { executeWithRetry, raceWithSignal } from '../utils/retry.js';
28
+ import { coerceArguments } from '../utils/coercion.js';
29
+ import { createProgressReporter } from '../utils/progress.js';
30
+ import { MiddlewareManager } from '../utils/middleware.js';
31
+ import { getUnitup, startBackgroundProcess, stopBackgroundProcess } from '../runtime/unitup.js';
32
+ export class McpApp {
33
+ config;
34
+ logger;
35
+ toolRegistry;
36
+ resourceRegistry = new ResourceRegistry();
37
+ subscriptionRegistry = new SubscriptionRegistry();
38
+ promptRegistry = new PromptRegistry();
39
+ contextManager;
40
+ analytics = new AnalyticsCollector();
41
+ queueManager = new QueueManager();
42
+ cacheManager = new ToolCacheManager();
43
+ middlewareManager;
44
+ resourceUpdateListeners = new Set();
45
+ instanceCoordinator;
46
+ stateManager;
47
+ lockManager;
48
+ centralRegistry = new CentralRegistry();
49
+ httpHandle;
50
+ stdioProxyHandle;
51
+ sessions = new Map();
52
+ metrics;
53
+ isOwner = false;
54
+ sampleFallback;
55
+ listRootsFallback;
56
+ rootsListChangedListeners = [];
57
+ constructor(config) {
58
+ this.config = resolveConfig(config);
59
+ const raw = typeof config === 'string' ? { name: config } : config;
60
+ if (typeof raw === 'object' && raw !== null) {
61
+ if (raw.onSample) {
62
+ this.sampleFallback = raw.onSample;
63
+ }
64
+ if (raw.onListRoots) {
65
+ this.listRootsFallback = raw.onListRoots;
66
+ }
67
+ }
68
+ this.logger = raw.logger || new DefaultLogger({
69
+ logDir: this.config.logDir,
70
+ level: this.config.logLevel,
71
+ retentionDays: this.config.retentionDays,
72
+ logToStderr: this.config.logToStderr
73
+ });
74
+ this.contextManager = new ContextManager(raw.context);
75
+ this.toolRegistry = new ToolRegistry({
76
+ defaultCoerceInputs: this.config.coerceInputs
77
+ });
78
+ this.middlewareManager = new MiddlewareManager(raw.middleware);
79
+ this.instanceCoordinator = new InstanceCoordinator(this.config);
80
+ this.stateManager = new StateManager(this.config.dataDir);
81
+ this.lockManager = new LockManager(this.config.dataDir);
82
+ this.metrics = {
83
+ startedAt: new Date().toISOString(),
84
+ activeSessions: 0,
85
+ totalSessions: 0
86
+ };
87
+ // Register built-in system resources
88
+ this.resourceRegistry.register({
89
+ uri: 'system://analytics',
90
+ name: 'Server Analytics',
91
+ description: 'Real-time tool execution metrics and inter-tool call graph',
92
+ mimeType: 'application/json',
93
+ handler: () => {
94
+ return {
95
+ contents: [
96
+ {
97
+ uri: 'system://analytics',
98
+ mimeType: 'application/json',
99
+ text: JSON.stringify(this.analytics.getSnapshot(), null, 2)
100
+ }
101
+ ]
102
+ };
103
+ }
104
+ });
105
+ this.resourceRegistry.register({
106
+ uri: 'system://metrics',
107
+ name: 'Prometheus Metrics',
108
+ description: 'Standard Prometheus text exposition metrics for scraping',
109
+ mimeType: 'text/plain; version=0.0.4; charset=utf-8',
110
+ handler: () => {
111
+ return {
112
+ contents: [
113
+ {
114
+ uri: 'system://metrics',
115
+ mimeType: 'text/plain; version=0.0.4; charset=utf-8',
116
+ text: this.getMetrics()
117
+ }
118
+ ]
119
+ };
120
+ }
121
+ });
122
+ // Register initial tools if provided
123
+ if (raw.tools) {
124
+ for (const t of raw.tools) {
125
+ this.tool(t);
126
+ }
127
+ }
128
+ }
129
+ use(filterOrHandler, maybeHandler) {
130
+ if (typeof filterOrHandler === 'function') {
131
+ this.middlewareManager.use(filterOrHandler);
132
+ }
133
+ else {
134
+ this.middlewareManager.use(filterOrHandler, maybeHandler);
135
+ }
136
+ return this;
137
+ }
138
+ /**
139
+ * Registers a tool.
140
+ */
141
+ tool(definition) {
142
+ this.toolRegistry.register(definition);
143
+ return this;
144
+ }
145
+ /**
146
+ * Automatically parses an OpenAPI v3 or Swagger v2 specification and registers all operations as MCP tools.
147
+ * Accepts an object, JSON string, file path, or remote URL.
148
+ */
149
+ async fromOpenApi(spec, options) {
150
+ const tools = await createOpenApiTools(spec, options);
151
+ for (const t of tools) {
152
+ this.tool(t);
153
+ }
154
+ return tools;
155
+ }
156
+ /**
157
+ * Returns all registered tools.
158
+ */
159
+ getTools() {
160
+ return this.toolRegistry.getAll();
161
+ }
162
+ /**
163
+ * Returns a specific registered tool by name.
164
+ */
165
+ getTool(name) {
166
+ return this.toolRegistry.get(name);
167
+ }
168
+ /**
169
+ * Invokes a registered tool programmatically by name.
170
+ * Can be called from outside the server or from inside other tools.
171
+ * Includes parameter validation, cycle/recursion detection, timeouts, cancellation, and result auto-normalization.
172
+ */
173
+ async callTool(name, args = {}, optionsOrStack, internalStack) {
174
+ const options = optionsOrStack && !Array.isArray(optionsOrStack) ? optionsOrStack : {};
175
+ const callStack = Array.isArray(optionsOrStack)
176
+ ? optionsOrStack
177
+ : (Array.isArray(internalStack) ? internalStack : []);
178
+ if (!name || typeof name !== 'string') {
179
+ throw new Error('Tool name must be a non-empty string');
180
+ }
181
+ if (callStack.includes(name)) {
182
+ throw new Error(`Circular tool invocation detected: ${[...callStack, name].join(' -> ')}`);
183
+ }
184
+ if (callStack.length >= 20) {
185
+ throw new Error(`Maximum tool call depth exceeded (20): ${[...callStack, name].join(' -> ')}`);
186
+ }
187
+ const tool = this.toolRegistry.get(name);
188
+ if (!tool) {
189
+ throw new Error(`Tool "${name}" not found`);
190
+ }
191
+ if (tool.requireAuth && !options.auth) {
192
+ throw new Error(`Authentication required for tool "${name}"`);
193
+ }
194
+ if (tool.scopes && tool.scopes.length > 0) {
195
+ if (!verifyToolScopes(tool.scopes, options.auth?.scopes)) {
196
+ throw new Error(`Forbidden: Tool "${name}" requires scopes: ${tool.scopes.join(', ')}`);
197
+ }
198
+ }
199
+ const start = Date.now();
200
+ let validatedArgs = args || {};
201
+ if (tool.normalizedSchema && Object.keys(tool.normalizedSchema).length > 0) {
202
+ const effectiveCoerce = options.coerceInputs !== undefined
203
+ ? options.coerceInputs
204
+ : (tool.coerceInputs !== undefined ? tool.coerceInputs : this.config.coerceInputs);
205
+ let argsToParse = validatedArgs;
206
+ if (effectiveCoerce) {
207
+ argsToParse = coerceArguments(validatedArgs, tool.inputSchema);
208
+ }
209
+ const schema = effectiveCoerce
210
+ ? (tool.compiledCoerceSchema || tool.compiledSchema)
211
+ : tool.compiledSchema;
212
+ if (schema) {
213
+ const parsed = schema.safeParse(argsToParse);
214
+ if (!parsed.success) {
215
+ const errorDetails = parsed.error.issues
216
+ .map((i) => `${i.path.join('.') || 'input'}: ${i.message}`)
217
+ .join(', ');
218
+ throw new Error(`Validation failed for tool "${name}": ${errorDetails}`);
219
+ }
220
+ validatedArgs = parsed.data;
221
+ }
222
+ else {
223
+ const activeSchema = effectiveCoerce
224
+ ? tool.normalizedSchema
225
+ : normalizeInputSchema(tool.inputSchema, tool.name, { coerceInputs: false });
226
+ const fallbackSchema = z.object(activeSchema);
227
+ const parsed = fallbackSchema.safeParse(argsToParse);
228
+ if (!parsed.success) {
229
+ const errorDetails = parsed.error.issues
230
+ .map((i) => `${i.path.join('.') || 'input'}: ${i.message}`)
231
+ .join(', ');
232
+ throw new Error(`Validation failed for tool "${name}": ${errorDetails}`);
233
+ }
234
+ validatedArgs = parsed.data;
235
+ }
236
+ }
237
+ // Early cache lookup: return immediately before allocating AbortControllers, timers, closures
238
+ const cacheConfig = typeof tool.cache === 'object' ? tool.cache : (tool.cache ? {} : undefined);
239
+ const bypassCache = options.noCache === true || options.bypassCache === true;
240
+ if (cacheConfig && !bypassCache) {
241
+ const cached = this.cacheManager.get(name, validatedArgs, cacheConfig);
242
+ if (cached) {
243
+ const durationMs = Date.now() - start;
244
+ const caller = callStack.length > 0 ? callStack[callStack.length - 1] : undefined;
245
+ this.analytics.recordInvocation({
246
+ tool: tool.name,
247
+ caller,
248
+ durationMs,
249
+ status: 'success',
250
+ isCacheHit: true
251
+ });
252
+ this.metrics.lastToolInvocation = {
253
+ name: tool.name,
254
+ timestamp: new Date().toISOString()
255
+ };
256
+ this.logger.info('tool:cache_hit', { name: tool.name, durationMs });
257
+ return cached;
258
+ }
259
+ }
260
+ const effectiveTimeout = options.timeoutMs !== undefined
261
+ ? options.timeoutMs
262
+ : (tool.timeoutMs !== undefined ? tool.timeoutMs : this.config.toolTimeoutMs);
263
+ const timeoutController = effectiveTimeout > 0 ? new AbortController() : null;
264
+ let timeoutTimer;
265
+ if (effectiveTimeout > 0 && timeoutController) {
266
+ timeoutTimer = setTimeout(() => {
267
+ timeoutController.abort(new Error(`Tool "${tool.name}" execution timed out after ${effectiveTimeout}ms`));
268
+ }, effectiveTimeout);
269
+ }
270
+ const signals = [];
271
+ if (options.signal) {
272
+ signals.push(options.signal);
273
+ }
274
+ if (timeoutController) {
275
+ signals.push(timeoutController.signal);
276
+ }
277
+ const mergedSignal = signals.length > 1
278
+ ? (typeof AbortSignal.any === 'function' ? AbortSignal.any(signals) : signals[0])
279
+ : signals[0];
280
+ const currentStack = [...callStack, name];
281
+ const callToolHelper = (targetName, targetArgs = {}, targetOptions) => {
282
+ const mergedOptions = {
283
+ signal: targetOptions?.signal || mergedSignal,
284
+ timeoutMs: targetOptions?.timeoutMs,
285
+ throwOnError: targetOptions?.throwOnError,
286
+ noCache: targetOptions?.noCache,
287
+ bypassCache: targetOptions?.bypassCache,
288
+ retry: targetOptions?.retry,
289
+ coerceInputs: targetOptions?.coerceInputs,
290
+ onProgress: targetOptions?.onProgress,
291
+ progressToken: targetOptions?.progressToken,
292
+ auth: targetOptions?.auth || options.auth
293
+ };
294
+ return this.callTool(targetName, targetArgs, mergedOptions, currentStack);
295
+ };
296
+ const clearCacheHelper = (targetToolName) => {
297
+ return this.clearCache(targetToolName);
298
+ };
299
+ const reportProgress = createProgressReporter({
300
+ toolName: tool.name,
301
+ progressToken: options.progressToken,
302
+ onProgress: options.onProgress,
303
+ logger: this.logger
304
+ });
305
+ const activeSession = this.sessions.size > 0 ? Array.from(this.sessions.values())[this.sessions.size - 1] : undefined;
306
+ const sessionServer = activeSession?.server;
307
+ const sampleHelper = (input, opts) => {
308
+ return executeSample(input, opts, sessionServer, this.sampleFallback, mergedSignal);
309
+ };
310
+ const listRootsHelper = () => {
311
+ return executeListRoots(sessionServer, this.listRootsFallback, mergedSignal);
312
+ };
313
+ const extra = {
314
+ signal: mergedSignal,
315
+ callTool: callToolHelper,
316
+ clearCache: clearCacheHelper,
317
+ reportProgress,
318
+ progressToken: options.progressToken,
319
+ sample: sampleHelper,
320
+ listRoots: listRootsHelper,
321
+ auth: options.auth
322
+ };
323
+ const queueConfig = this.resolveQueueConfig(tool, options, callStack.length > 0);
324
+ let release;
325
+ let retriesCount = 0;
326
+ try {
327
+ if (queueConfig) {
328
+ release = await this.queueManager
329
+ .getQueue(queueConfig.key, queueConfig.maxConcurrency)
330
+ .acquire(mergedSignal);
331
+ }
332
+ if (!this.contextManager.isInitialized()) {
333
+ await this.contextManager.initialize(this.logger);
334
+ }
335
+ const ctx = this.contextManager.getContext();
336
+ const handlerCtx = ctx && typeof ctx === 'object'
337
+ ? Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, {
338
+ callTool: callToolHelper,
339
+ signal: mergedSignal,
340
+ clearCache: clearCacheHelper,
341
+ reportProgress,
342
+ sample: sampleHelper,
343
+ listRoots: listRootsHelper,
344
+ auth: options.auth
345
+ })
346
+ : {
347
+ callTool: callToolHelper,
348
+ signal: mergedSignal,
349
+ clearCache: clearCacheHelper,
350
+ reportProgress,
351
+ sample: sampleHelper,
352
+ listRoots: listRootsHelper,
353
+ auth: options.auth
354
+ };
355
+ this.logger.info('tool:start', { name: tool.name, caller: callStack[callStack.length - 1] });
356
+ const effectiveRetry = options.retry !== undefined ? options.retry : tool.retry;
357
+ const middlewarePipeline = this.middlewareManager.composeForTool(tool.name, (pCtx) => Promise.resolve(tool.handler(pCtx.args, pCtx.context, pCtx.extra)), tool.middleware);
358
+ const runAttempt = () => {
359
+ const middlewareCtx = {
360
+ tool: tool.name,
361
+ args: validatedArgs,
362
+ context: handlerCtx,
363
+ extra,
364
+ options,
365
+ callStack
366
+ };
367
+ const executionPromise = middlewarePipeline(middlewareCtx);
368
+ return raceWithSignal(executionPromise, mergedSignal, () => new Error(`Tool "${tool.name}" execution was cancelled`));
369
+ };
370
+ const { result: rawResult, retries } = await executeWithRetry(runAttempt, {
371
+ name: tool.name,
372
+ config: effectiveRetry,
373
+ signal: mergedSignal,
374
+ onRetry: (err, attempt, delayMs) => {
375
+ retriesCount = attempt;
376
+ this.logger.warn('tool:retry', {
377
+ name: tool.name,
378
+ attempt,
379
+ delayMs,
380
+ error: err?.message || String(err)
381
+ });
382
+ }
383
+ });
384
+ retriesCount = retries;
385
+ const durationMs = Date.now() - start;
386
+ const caller = callStack.length > 0 ? callStack[callStack.length - 1] : undefined;
387
+ this.analytics.recordInvocation({
388
+ tool: tool.name,
389
+ caller,
390
+ durationMs,
391
+ status: 'success',
392
+ retries: retriesCount
393
+ });
394
+ this.metrics.lastToolInvocation = {
395
+ name: tool.name,
396
+ timestamp: new Date().toISOString()
397
+ };
398
+ this.logger.info('tool:end', { name: tool.name, durationMs });
399
+ const normalized = normalizeToolResult(rawResult);
400
+ if (cacheConfig && !bypassCache && !normalized.isError) {
401
+ this.cacheManager.set(name, validatedArgs, normalized, cacheConfig);
402
+ }
403
+ return normalized;
404
+ }
405
+ catch (error) {
406
+ const durationMs = Date.now() - start;
407
+ const isTimeout = String(error?.message || error).includes('timed out');
408
+ const isCancelled = Boolean(mergedSignal?.aborted && !isTimeout);
409
+ const status = isTimeout ? 'timeout' : (isCancelled ? 'cancelled' : 'error');
410
+ const caller = callStack.length > 0 ? callStack[callStack.length - 1] : undefined;
411
+ this.analytics.recordInvocation({
412
+ tool: tool.name,
413
+ caller,
414
+ durationMs,
415
+ status,
416
+ errorMessage: error.message || String(error),
417
+ retries: retriesCount || (error?.retries ?? 0)
418
+ });
419
+ this.metrics.lastToolInvocation = {
420
+ name: tool.name,
421
+ timestamp: new Date().toISOString()
422
+ };
423
+ this.logger.error('tool:error', {
424
+ name: tool.name,
425
+ durationMs,
426
+ isTimeout,
427
+ isCancelled,
428
+ error: error.message || String(error),
429
+ stack: error.stack
430
+ });
431
+ if (options.throwOnError !== false) {
432
+ throw error;
433
+ }
434
+ return {
435
+ isError: true,
436
+ content: [
437
+ {
438
+ type: 'text',
439
+ text: `Error in tool "${tool.name}": ${error.message || String(error)}`
440
+ }
441
+ ],
442
+ data: undefined,
443
+ text: `Error in tool "${tool.name}": ${error.message || String(error)}`
444
+ };
445
+ }
446
+ finally {
447
+ if (timeoutTimer) {
448
+ clearTimeout(timeoutTimer);
449
+ }
450
+ release?.();
451
+ }
452
+ }
453
+ /**
454
+ * Resolves the queue key and maxConcurrency for a tool invocation.
455
+ * Returns null if no concurrency limiting is requested.
456
+ */
457
+ resolveQueueConfig(tool, options, isChildCall = false) {
458
+ const callSequential = options?.sequential;
459
+ if (callSequential === true) {
460
+ return { key: `tool:${tool.name}`, maxConcurrency: 1 };
461
+ }
462
+ if (typeof callSequential === 'string') {
463
+ return { key: `mutex:${callSequential}`, maxConcurrency: 1 };
464
+ }
465
+ if (tool.sequential === true) {
466
+ return { key: `tool:${tool.name}`, maxConcurrency: 1 };
467
+ }
468
+ if (typeof tool.sequential === 'string') {
469
+ return { key: `mutex:${tool.sequential}`, maxConcurrency: 1 };
470
+ }
471
+ if (tool.maxConcurrency !== undefined && tool.maxConcurrency > 0) {
472
+ return { key: `tool:${tool.name}`, maxConcurrency: tool.maxConcurrency };
473
+ }
474
+ if (this.config.sequential || (this.config.maxConcurrency && this.config.maxConcurrency > 0)) {
475
+ if (isChildCall) {
476
+ return null;
477
+ }
478
+ return {
479
+ key: '__server_global__',
480
+ maxConcurrency: this.config.maxConcurrency || 1
481
+ };
482
+ }
483
+ return null;
484
+ }
485
+ /**
486
+ * Returns current concurrency queue statistics.
487
+ */
488
+ getQueueStats() {
489
+ return this.queueManager.getStats();
490
+ }
491
+ /**
492
+ * Clears in-memory cache entries.
493
+ * If toolName is provided, clears only that tool's cached responses.
494
+ * If omitted, clears all cached responses across all tools.
495
+ * Returns the count of evicted entries.
496
+ */
497
+ clearCache(toolName) {
498
+ return this.cacheManager.clear(toolName);
499
+ }
500
+ /**
501
+ * Returns current cache statistics (size, hits, misses, evictions).
502
+ */
503
+ getCacheStats() {
504
+ return this.cacheManager.getStats();
505
+ }
506
+ /**
507
+ * Returns a complete snapshot of tool analytics, execution times, and inter-tool relationships.
508
+ */
509
+ getAnalytics() {
510
+ return this.analytics.getSnapshot();
511
+ }
512
+ /**
513
+ * Returns standard Prometheus-formatted metrics text (exposition format 0.0.4) for scraping.
514
+ */
515
+ getMetrics() {
516
+ const uptimeSeconds = (Date.now() - new Date(this.metrics.startedAt).getTime()) / 1000;
517
+ return this.analytics.toPrometheusFormat({
518
+ serverName: this.config.name,
519
+ version: this.config.version,
520
+ activeSessions: this.metrics.activeSessions,
521
+ totalSessions: this.metrics.totalSessions,
522
+ uptimeSeconds: Math.max(0, uptimeSeconds),
523
+ cacheStats: this.cacheManager.getStats()
524
+ });
525
+ }
526
+ /**
527
+ * Resets all recorded analytics counters and history.
528
+ */
529
+ resetAnalytics() {
530
+ this.analytics.reset();
531
+ }
532
+ /**
533
+ * Registers a dynamic RFC 6570 resource template.
534
+ */
535
+ resourceTemplate(definition) {
536
+ this.resourceRegistry.registerTemplate(definition);
537
+ return this;
538
+ }
539
+ /**
540
+ * Registers a static resource or dynamic resource template.
541
+ * If definition contains `uriTemplate` or its `uri` contains template variables `{...}`,
542
+ * it will automatically be registered as a dynamic resource template.
543
+ */
544
+ resource(definition) {
545
+ if ('uriTemplate' in definition &&
546
+ typeof definition.uriTemplate === 'string') {
547
+ this.resourceRegistry.registerTemplate(definition);
548
+ return this;
549
+ }
550
+ const staticDef = definition;
551
+ if (staticDef.uri && staticDef.uri.includes('{') && staticDef.uri.includes('}')) {
552
+ const templateDef = {
553
+ uriTemplate: staticDef.uri,
554
+ name: staticDef.name,
555
+ description: staticDef.description,
556
+ mimeType: staticDef.mimeType,
557
+ handler: (uri, params, ctx) => staticDef.handler(uri, params, ctx)
558
+ };
559
+ this.resourceRegistry.registerTemplate(templateDef);
560
+ return this;
561
+ }
562
+ this.resourceRegistry.register(staticDef);
563
+ return this;
564
+ }
565
+ /**
566
+ * Registers a prompt.
567
+ */
568
+ prompt(definition) {
569
+ this.promptRegistry.register(definition);
570
+ return this;
571
+ }
572
+ /**
573
+ * Retrieves a registered static resource definition by URI.
574
+ */
575
+ getResource(uri) {
576
+ return this.resourceRegistry.get(uri);
577
+ }
578
+ /**
579
+ * Retrieves all registered static resource definitions.
580
+ */
581
+ getResources() {
582
+ return this.resourceRegistry.getAll();
583
+ }
584
+ /**
585
+ * Retrieves a registered resource template definition by URI template string or name.
586
+ */
587
+ getResourceTemplate(nameOrUriTemplate) {
588
+ return this.resourceRegistry.getTemplate(nameOrUriTemplate);
589
+ }
590
+ /**
591
+ * Retrieves all registered resource template definitions.
592
+ */
593
+ getResourceTemplates() {
594
+ return this.resourceRegistry.getAllTemplates();
595
+ }
596
+ /**
597
+ * Matches a concrete URI against registered resource templates and returns extracted variables.
598
+ */
599
+ matchResourceTemplate(uri) {
600
+ return this.resourceRegistry.findMatchingTemplate(uri);
601
+ }
602
+ /**
603
+ * Programmatically reads a resource by static URI or template match.
604
+ * Useful for testing, inter-service reads, and direct execution without an MCP client.
605
+ */
606
+ async readResource(uri, context) {
607
+ const uriString = typeof uri === 'string' ? uri : uri.href;
608
+ let urlObj;
609
+ try {
610
+ urlObj = typeof uri === 'string' ? new URL(uri) : uri;
611
+ }
612
+ catch {
613
+ urlObj = new URL(`resource:///${String(uri).replace(/^\/+/, '')}`);
614
+ }
615
+ let ctx;
616
+ if (context !== undefined) {
617
+ ctx = context;
618
+ }
619
+ else {
620
+ if (!this.contextManager.isInitialized()) {
621
+ await this.contextManager.initialize(this.logger);
622
+ }
623
+ ctx = this.contextManager.getContext();
624
+ }
625
+ // 1. Check static resources first
626
+ const staticRes = this.resourceRegistry.get(uriString) || this.resourceRegistry.get(urlObj.href);
627
+ if (staticRes) {
628
+ const raw = await staticRes.handler(urlObj, ctx);
629
+ return normalizeResourceResult(raw, urlObj, staticRes.mimeType);
630
+ }
631
+ // 2. Check dynamic resource templates
632
+ const match = this.resourceRegistry.findMatchingTemplate(uriString) ||
633
+ this.resourceRegistry.findMatchingTemplate(urlObj.href);
634
+ if (match) {
635
+ const raw = await match.template.handler(urlObj, match.params, ctx);
636
+ return normalizeResourceResult(raw, urlObj, match.template.mimeType);
637
+ }
638
+ throw new Error(`Resource not found: "${uriString}"`);
639
+ }
640
+ /**
641
+ * Notifies connected MCP clients subscribed to a resource URI that its contents have changed.
642
+ * Sends `notifications/resources/updated` with the updated URI.
643
+ * Returns the count of client sessions successfully notified.
644
+ */
645
+ async notifyResourceUpdated(uri) {
646
+ const uriString = typeof uri === 'string' ? uri : uri.href;
647
+ let notifiedCount = 0;
648
+ const subscriberSessions = new Set(this.subscriptionRegistry.getSubscribers(uriString));
649
+ for (const [sessionId, session] of this.sessions.entries()) {
650
+ const isSubscribed = subscriberSessions.has(sessionId) ||
651
+ this.subscriptionRegistry.isSubscribed(sessionId, uriString) ||
652
+ subscriberSessions.size === 0;
653
+ if (isSubscribed && session.server?.server) {
654
+ try {
655
+ await session.server.server.sendResourceUpdated({ uri: uriString });
656
+ notifiedCount++;
657
+ }
658
+ catch (err) {
659
+ this.logger.debug('Failed to send resource updated notification to session', {
660
+ session: sessionId,
661
+ uri: uriString,
662
+ error: err.message
663
+ });
664
+ }
665
+ }
666
+ }
667
+ // Trigger local server-side listeners
668
+ for (const listener of this.resourceUpdateListeners) {
669
+ try {
670
+ listener(uriString);
671
+ }
672
+ catch (err) {
673
+ this.logger.error('Error in resource update listener', {
674
+ uri: uriString,
675
+ error: err.message
676
+ });
677
+ }
678
+ }
679
+ return notifiedCount;
680
+ }
681
+ /**
682
+ * Notifies connected MCP clients that the list of available resources has changed.
683
+ * Sends `notifications/resources/list_changed`.
684
+ * Returns the count of client sessions successfully notified.
685
+ */
686
+ async notifyResourceListChanged() {
687
+ let notifiedCount = 0;
688
+ for (const [sessionId, session] of this.sessions.entries()) {
689
+ if (session.server?.server) {
690
+ try {
691
+ await session.server.server.sendResourceListChanged();
692
+ notifiedCount++;
693
+ }
694
+ catch (err) {
695
+ this.logger.debug('Failed to send resource list changed notification to session', {
696
+ session: sessionId,
697
+ error: err.message
698
+ });
699
+ }
700
+ }
701
+ }
702
+ return notifiedCount;
703
+ }
704
+ /**
705
+ * Subscribes a local event listener to resource update notifications.
706
+ * Returns an unsubscribe function.
707
+ */
708
+ onResourceUpdated(listener) {
709
+ this.resourceUpdateListeners.add(listener);
710
+ return () => {
711
+ this.resourceUpdateListeners.delete(listener);
712
+ };
713
+ }
714
+ /**
715
+ * Returns all active subscribed resource URIs across all sessions or for a specific session.
716
+ */
717
+ getSubscribedResources(sessionId) {
718
+ if (sessionId) {
719
+ return this.subscriptionRegistry.getSubscriptions(sessionId);
720
+ }
721
+ return this.subscriptionRegistry.getAllSubscribedUris();
722
+ }
723
+ /**
724
+ * Requests LLM completion/sampling back from the connected client via MCP sampling/createMessage.
725
+ * If running offline or in tests, delegates to any fallback handler configured with app.onSample().
726
+ */
727
+ async sample(input, options) {
728
+ const activeSession = this.sessions.size > 0 ? Array.from(this.sessions.values())[this.sessions.size - 1] : undefined;
729
+ const sessionServer = activeSession?.server;
730
+ return executeSample(input, options, sessionServer, this.sampleFallback);
731
+ }
732
+ /**
733
+ * Requests the list of root workspace directories from the connected client via MCP roots/list.
734
+ */
735
+ async listRoots() {
736
+ const activeSession = this.sessions.size > 0 ? Array.from(this.sessions.values())[this.sessions.size - 1] : undefined;
737
+ const sessionServer = activeSession?.server;
738
+ return executeListRoots(sessionServer, this.listRootsFallback);
739
+ }
740
+ /**
741
+ * Registers a fallback/offline handler for sampling requests.
742
+ */
743
+ onSample(handler) {
744
+ this.sampleFallback = handler;
745
+ return this;
746
+ }
747
+ /**
748
+ * Registers a fallback/offline handler for workspace roots requests.
749
+ */
750
+ onListRoots(handler) {
751
+ this.listRootsFallback = handler;
752
+ return this;
753
+ }
754
+ /**
755
+ * Listens for client roots/list_changed notifications.
756
+ * Returns an unbind function.
757
+ */
758
+ onRootsListChanged(listener) {
759
+ this.rootsListChangedListeners.push(listener);
760
+ return () => {
761
+ const idx = this.rootsListChangedListeners.indexOf(listener);
762
+ if (idx !== -1) {
763
+ this.rootsListChangedListeners.splice(idx, 1);
764
+ }
765
+ };
766
+ }
767
+ /**
768
+ * Resolves argument autocompletions for prompts, resource templates, or tools.
769
+ */
770
+ async complete(ref, argument) {
771
+ return resolveCompletion({
772
+ promptRegistry: this.promptRegistry,
773
+ resourceRegistry: this.resourceRegistry,
774
+ toolRegistry: this.toolRegistry,
775
+ ref,
776
+ argument,
777
+ context: this.contextManager.isInitialized() ? this.contextManager.getContext() : undefined
778
+ });
779
+ }
780
+ /**
781
+ * Returns the HTTP URL of the interactive Web Inspector for this server.
782
+ */
783
+ getInspectorUrl(host) {
784
+ const targetHost = host || this.httpHandle?.host || this.config.host || 'localhost';
785
+ const port = this.httpHandle?.port || this.config.port || 3000;
786
+ return `http://${targetHost}:${port}/inspect`;
787
+ }
788
+ /**
789
+ * Retrieves a registered prompt definition by name.
790
+ */
791
+ getPrompt(name) {
792
+ return this.promptRegistry.get(name);
793
+ }
794
+ /**
795
+ * Returns the directory where log files are stored.
796
+ */
797
+ async getLogDirectory() {
798
+ return this.config.logDir;
799
+ }
800
+ /**
801
+ * Reads recent log entries.
802
+ */
803
+ async readLogs(limit = 100) {
804
+ return this.logger.readLogs(limit);
805
+ }
806
+ /**
807
+ * Returns the current status of the server.
808
+ */
809
+ async status() {
810
+ const state = this.stateManager.read();
811
+ if (!state || state.name !== this.config.name) {
812
+ return {
813
+ status: 'stopped',
814
+ dataDir: this.config.dataDir,
815
+ logDir: this.config.logDir
816
+ };
817
+ }
818
+ const health = await checkHealth(state.host, state.port, this.config.name, 1000);
819
+ if (!health) {
820
+ return {
821
+ status: 'stopped',
822
+ dataDir: this.config.dataDir,
823
+ logDir: this.config.logDir
824
+ };
825
+ }
826
+ const info = await fetchInfo(state.host, state.port, 1000);
827
+ return {
828
+ status: 'running',
829
+ role: this.isOwner ? 'owner' : 'bridge',
830
+ pid: state.pid,
831
+ port: state.port,
832
+ host: state.host,
833
+ startedAt: state.startedAt,
834
+ dataDir: this.config.dataDir,
835
+ logDir: this.config.logDir,
836
+ activeSessions: info?.activeSessions ?? this.metrics.activeSessions,
837
+ totalSessions: info?.totalSessions ?? this.metrics.totalSessions
838
+ };
839
+ }
840
+ /**
841
+ * Starts the server programmatically. If a server is already running,
842
+ * reuses it and returns `{ reused: true, ... }`.
843
+ */
844
+ async start(options = {}) {
845
+ const isBackgroundWorker = process.env.MCPONCE_BACKGROUND_SERVER === '1' ||
846
+ process.argv.includes('--mcponce-background');
847
+ const shouldRunBackground = options.background !== undefined ? options.background : this.config.background;
848
+ if (shouldRunBackground && !isBackgroundWorker && !options.noSingleton) {
849
+ await getUnitup();
850
+ const existingState = this.stateManager.read();
851
+ if (existingState && existingState.name === this.config.name) {
852
+ const health = await checkHealth(existingState.host, existingState.port, this.config.name, 1000);
853
+ if (health) {
854
+ return {
855
+ reused: true,
856
+ role: 'bridge',
857
+ pid: existingState.pid,
858
+ port: existingState.port,
859
+ host: existingState.host
860
+ };
861
+ }
862
+ }
863
+ const initialLock = this.lockManager.readLock();
864
+ if (!initialLock || !isPidRunning(initialLock.pid)) {
865
+ this.lockManager.forceRelease();
866
+ this.stateManager.forceClean();
867
+ }
868
+ if (this.lockManager.tryAcquire(this.config.name)) {
869
+ try {
870
+ await startBackgroundProcess({
871
+ name: this.config.name,
872
+ scriptPath: this.config.entrypoint,
873
+ dataDir: this.config.dataDir,
874
+ logDir: this.config.logDir
875
+ });
876
+ }
877
+ finally {
878
+ this.lockManager.release();
879
+ }
880
+ }
881
+ const maxWaitMs = 20000;
882
+ const startTime = Date.now();
883
+ let healthyState = null;
884
+ while (Date.now() - startTime < maxWaitMs) {
885
+ await new Promise((r) => setTimeout(r, 25));
886
+ const st = this.stateManager.read();
887
+ if (st && st.name === this.config.name) {
888
+ const h = await checkHealth(st.host, st.port, this.config.name, 300);
889
+ if (h) {
890
+ healthyState = st;
891
+ break;
892
+ }
893
+ }
894
+ }
895
+ if (!healthyState) {
896
+ throw new Error(`Failed to start background MCP server for "${this.config.name}" through Unitup: health check timed out`);
897
+ }
898
+ return {
899
+ reused: false,
900
+ role: 'owner',
901
+ pid: healthyState.pid,
902
+ port: healthyState.port,
903
+ host: healthyState.host
904
+ };
905
+ }
906
+ const roleResult = await this.instanceCoordinator.ensureInstance({
907
+ noSingleton: options.noSingleton,
908
+ logger: this.logger
909
+ });
910
+ if (roleResult.role === 'bridge') {
911
+ return {
912
+ reused: true,
913
+ role: 'bridge',
914
+ pid: roleResult.state.pid,
915
+ port: roleResult.state.port,
916
+ host: roleResult.state.host
917
+ };
918
+ }
919
+ // Role is owner: initialize context and start HTTP server
920
+ this.isOwner = true;
921
+ await this.contextManager.initialize(this.logger);
922
+ let currentPort = this.config.port;
923
+ const honoApp = createHonoApp({
924
+ config: this.config,
925
+ toolRegistry: this.toolRegistry,
926
+ resourceRegistry: this.resourceRegistry,
927
+ promptRegistry: this.promptRegistry,
928
+ contextManager: this.contextManager,
929
+ metrics: this.metrics,
930
+ analytics: this.analytics,
931
+ portProvider: () => currentPort,
932
+ callTool: (name, args, options, stack) => this.callTool(name, args, options, stack),
933
+ logger: this.logger,
934
+ queueManager: this.queueManager,
935
+ cacheManager: this.cacheManager,
936
+ middlewareManager: this.middlewareManager,
937
+ resolveQueueConfig: (tool, opts) => this.resolveQueueConfig(tool, opts),
938
+ sessions: this.sessions,
939
+ subscriptionRegistry: this.subscriptionRegistry,
940
+ onSample: this.sampleFallback,
941
+ onListRoots: this.listRootsFallback,
942
+ onRootsListChanged: (roots) => {
943
+ for (const listener of this.rootsListChangedListeners) {
944
+ listener(roots);
945
+ }
946
+ }
947
+ });
948
+ this.httpHandle = await startHttpServer(honoApp, this.config.host, this.config.port);
949
+ currentPort = this.httpHandle.port;
950
+ this.stateManager.write({
951
+ name: this.config.name,
952
+ version: this.config.version,
953
+ pid: process.pid,
954
+ port: this.httpHandle.port,
955
+ host: this.httpHandle.host,
956
+ startedAt: this.metrics.startedAt
957
+ });
958
+ if (this.config.registerInCentral) {
959
+ try {
960
+ await this.centralRegistry.register({
961
+ name: this.config.name,
962
+ version: this.config.version,
963
+ status: 'running',
964
+ pid: process.pid,
965
+ port: this.httpHandle.port,
966
+ host: this.httpHandle.host,
967
+ dataDir: this.config.dataDir,
968
+ logDir: this.config.logDir,
969
+ startedAt: this.metrics.startedAt
970
+ });
971
+ }
972
+ catch { }
973
+ }
974
+ this.logger.info('server:start', {
975
+ pid: process.pid,
976
+ port: this.httpHandle.port,
977
+ host: this.httpHandle.host
978
+ });
979
+ return {
980
+ reused: false,
981
+ role: 'owner',
982
+ pid: process.pid,
983
+ port: this.httpHandle.port,
984
+ host: this.httpHandle.host
985
+ };
986
+ }
987
+ /**
988
+ * Stops the server if running as owner, or shuts down the running instance.
989
+ */
990
+ async stop(options = {}) {
991
+ if (this.stdioProxyHandle) {
992
+ await this.stdioProxyHandle.close();
993
+ this.stdioProxyHandle = undefined;
994
+ }
995
+ if (this.httpHandle) {
996
+ await this.httpHandle.close();
997
+ this.httpHandle = undefined;
998
+ }
999
+ const shouldStopBackground = options.background !== undefined ? options.background : this.config.background;
1000
+ if (shouldStopBackground) {
1001
+ try {
1002
+ await stopBackgroundProcess(this.config.name);
1003
+ }
1004
+ catch { }
1005
+ if (this.config.registerInCentral) {
1006
+ try {
1007
+ await this.centralRegistry.updateStatus(this.config.name, 'stopped');
1008
+ }
1009
+ catch { }
1010
+ }
1011
+ this.stateManager.forceClean();
1012
+ this.lockManager.forceRelease();
1013
+ this.isOwner = false;
1014
+ return;
1015
+ }
1016
+ if (this.isOwner) {
1017
+ if (this.config.registerInCentral) {
1018
+ try {
1019
+ await this.centralRegistry.updateStatus(this.config.name, 'stopped');
1020
+ }
1021
+ catch { }
1022
+ }
1023
+ this.stateManager.clean();
1024
+ this.lockManager.release();
1025
+ this.isOwner = false;
1026
+ }
1027
+ else {
1028
+ // If we are not owner in this process, check if an instance is running and signal it
1029
+ const state = this.stateManager.read();
1030
+ if (state && state.name === this.config.name && isPidRunning(state.pid)) {
1031
+ try {
1032
+ process.kill(state.pid, 'SIGTERM');
1033
+ }
1034
+ catch { }
1035
+ }
1036
+ }
1037
+ }
1038
+ /**
1039
+ * Restarts the server. If running in background mode, restarts the Unitup process
1040
+ * and waits for /health.
1041
+ */
1042
+ async restart(options = {}) {
1043
+ await this.stop(options);
1044
+ await new Promise((r) => setTimeout(r, 200));
1045
+ return await this.start(options);
1046
+ }
1047
+ /**
1048
+ * Primary entry point for running the executable.
1049
+ * Handles CLI commands (info, logs, --dev, etc.) and runs the automatic
1050
+ * single-instance MCP server and stdio bridge.
1051
+ */
1052
+ async run() {
1053
+ const cliOptions = await handleCliArgs(process.argv.slice(2), this.config, this);
1054
+ if (cliOptions.isCliCommand) {
1055
+ return;
1056
+ }
1057
+ if (cliOptions.devMode) {
1058
+ this.logger.setLogToStderr(true);
1059
+ try {
1060
+ process.stderr.write(`[${this.config.name}] Starting in development mode (pid: ${process.pid})...\n`);
1061
+ }
1062
+ catch { }
1063
+ }
1064
+ const isBackgroundWorker = process.env.MCPONCE_BACKGROUND_SERVER === '1' ||
1065
+ process.argv.includes('--mcponce-background');
1066
+ if (isBackgroundWorker) {
1067
+ const startResult = await this.start({ noSingleton: false });
1068
+ this.logger.info('Background MCP worker running', {
1069
+ name: this.config.name,
1070
+ pid: process.pid,
1071
+ port: startResult.port,
1072
+ host: startResult.host
1073
+ });
1074
+ const shutdown = async () => {
1075
+ await this.stop();
1076
+ process.exit(0);
1077
+ };
1078
+ process.on('SIGINT', shutdown);
1079
+ process.on('SIGTERM', shutdown);
1080
+ process.on('SIGHUP', shutdown);
1081
+ return;
1082
+ }
1083
+ const backgroundMode = this.config.background || cliOptions.background;
1084
+ if (backgroundMode) {
1085
+ await getUnitup();
1086
+ let targetPort;
1087
+ let targetHost;
1088
+ let serverPid;
1089
+ const existingState = this.stateManager.read();
1090
+ const isHealthy = existingState && existingState.name === this.config.name
1091
+ ? await checkHealth(existingState.host, existingState.port, this.config.name, 1000)
1092
+ : null;
1093
+ if (isHealthy && existingState) {
1094
+ targetPort = existingState.port;
1095
+ targetHost = existingState.host;
1096
+ serverPid = existingState.pid;
1097
+ }
1098
+ else {
1099
+ if (existingState && !isHealthy) {
1100
+ this.lockManager.forceRelease();
1101
+ this.stateManager.forceClean();
1102
+ }
1103
+ if (this.lockManager.tryAcquire(this.config.name)) {
1104
+ try {
1105
+ await startBackgroundProcess({
1106
+ name: this.config.name,
1107
+ scriptPath: this.config.entrypoint,
1108
+ dataDir: this.config.dataDir,
1109
+ logDir: this.config.logDir
1110
+ });
1111
+ }
1112
+ finally {
1113
+ this.lockManager.release();
1114
+ }
1115
+ }
1116
+ const maxWaitMs = 20000;
1117
+ const start = Date.now();
1118
+ let healthyState = null;
1119
+ while (Date.now() - start < maxWaitMs) {
1120
+ await new Promise((r) => setTimeout(r, 25));
1121
+ const st = this.stateManager.read();
1122
+ if (st && st.name === this.config.name) {
1123
+ const h = await checkHealth(st.host, st.port, this.config.name, 300);
1124
+ if (h) {
1125
+ healthyState = st;
1126
+ break;
1127
+ }
1128
+ }
1129
+ }
1130
+ if (!healthyState) {
1131
+ throw new Error(`Failed to start background MCP server for "${this.config.name}" through Unitup: health check timed out`);
1132
+ }
1133
+ targetPort = healthyState.port;
1134
+ targetHost = healthyState.host;
1135
+ serverPid = healthyState.pid;
1136
+ }
1137
+ this.logger.info('bridge:start', {
1138
+ pid: process.pid,
1139
+ serverPid,
1140
+ port: targetPort
1141
+ });
1142
+ if (cliOptions.devMode) {
1143
+ try {
1144
+ process.stderr.write(`[${this.config.name}] Connected to background server on http://${targetHost}:${targetPort} (pid: ${serverPid})\n`);
1145
+ }
1146
+ catch { }
1147
+ }
1148
+ const mcpUrl = `http://${targetHost}:${targetPort}/mcp`;
1149
+ this.stdioProxyHandle = await startStdioProxy(mcpUrl, this.logger);
1150
+ await this.stdioProxyHandle.done;
1151
+ process.exit(0);
1152
+ }
1153
+ // Single-instance determination
1154
+ const roleResult = await this.instanceCoordinator.ensureInstance({
1155
+ noSingleton: cliOptions.noSingleton,
1156
+ logger: this.logger
1157
+ });
1158
+ let targetPort;
1159
+ let targetHost;
1160
+ let ownerStdioClosed = false;
1161
+ if (roleResult.role === 'owner') {
1162
+ this.isOwner = true;
1163
+ await this.contextManager.initialize(this.logger);
1164
+ let currentPort = this.config.port;
1165
+ const honoApp = createHonoApp({
1166
+ config: this.config,
1167
+ toolRegistry: this.toolRegistry,
1168
+ resourceRegistry: this.resourceRegistry,
1169
+ promptRegistry: this.promptRegistry,
1170
+ contextManager: this.contextManager,
1171
+ metrics: this.metrics,
1172
+ analytics: this.analytics,
1173
+ portProvider: () => currentPort,
1174
+ callTool: (name, args, options, stack) => this.callTool(name, args, options, stack),
1175
+ logger: this.logger,
1176
+ queueManager: this.queueManager,
1177
+ cacheManager: this.cacheManager,
1178
+ middlewareManager: this.middlewareManager,
1179
+ resolveQueueConfig: (tool, opts) => this.resolveQueueConfig(tool, opts),
1180
+ sessions: this.sessions,
1181
+ subscriptionRegistry: this.subscriptionRegistry,
1182
+ onSample: this.sampleFallback,
1183
+ onListRoots: this.listRootsFallback,
1184
+ onRootsListChanged: (roots) => {
1185
+ for (const listener of this.rootsListChangedListeners) {
1186
+ listener(roots);
1187
+ }
1188
+ },
1189
+ onSessionClosed: () => {
1190
+ if (ownerStdioClosed && this.sessions.size === 0) {
1191
+ this.logger.info('All sessions closed after owner stdio ended, shutting down', {
1192
+ pid: process.pid
1193
+ });
1194
+ shutdown();
1195
+ }
1196
+ }
1197
+ });
1198
+ this.httpHandle = await startHttpServer(honoApp, this.config.host, this.config.port);
1199
+ currentPort = this.httpHandle.port;
1200
+ targetPort = this.httpHandle.port;
1201
+ targetHost = this.httpHandle.host;
1202
+ this.stateManager.write({
1203
+ name: this.config.name,
1204
+ version: this.config.version,
1205
+ pid: process.pid,
1206
+ port: targetPort,
1207
+ host: targetHost,
1208
+ startedAt: this.metrics.startedAt
1209
+ });
1210
+ if (this.config.registerInCentral) {
1211
+ try {
1212
+ await this.centralRegistry.register({
1213
+ name: this.config.name,
1214
+ version: this.config.version,
1215
+ status: 'running',
1216
+ pid: process.pid,
1217
+ port: targetPort,
1218
+ host: targetHost,
1219
+ dataDir: this.config.dataDir,
1220
+ logDir: this.config.logDir,
1221
+ startedAt: this.metrics.startedAt
1222
+ });
1223
+ }
1224
+ catch { }
1225
+ }
1226
+ this.logger.info('server:start', {
1227
+ pid: process.pid,
1228
+ port: targetPort,
1229
+ host: targetHost
1230
+ });
1231
+ if (cliOptions.devMode) {
1232
+ try {
1233
+ process.stderr.write(`[${this.config.name}] Shared HTTP server listening on http://${targetHost}:${targetPort}\n`);
1234
+ }
1235
+ catch { }
1236
+ }
1237
+ }
1238
+ else {
1239
+ // Role is bridge
1240
+ targetPort = roleResult.state.port;
1241
+ targetHost = roleResult.state.host;
1242
+ this.logger.info('bridge:start', {
1243
+ pid: process.pid,
1244
+ serverPid: roleResult.state.pid,
1245
+ port: targetPort
1246
+ });
1247
+ if (cliOptions.devMode) {
1248
+ try {
1249
+ process.stderr.write(`[${this.config.name}] Connected to shared server on http://${targetHost}:${targetPort} (pid: ${roleResult.state.pid})\n`);
1250
+ }
1251
+ catch { }
1252
+ }
1253
+ }
1254
+ // Set up clean shutdown listeners
1255
+ let shuttingDown = false;
1256
+ const shutdown = async () => {
1257
+ if (shuttingDown)
1258
+ return;
1259
+ shuttingDown = true;
1260
+ this.logger.info('server:shutdown', { pid: process.pid, isOwner: this.isOwner });
1261
+ if (this.stdioProxyHandle) {
1262
+ try {
1263
+ await this.stdioProxyHandle.close();
1264
+ }
1265
+ catch { }
1266
+ }
1267
+ if (this.isOwner) {
1268
+ if (this.config.registerInCentral) {
1269
+ try {
1270
+ await this.centralRegistry.updateStatus(this.config.name, 'stopped');
1271
+ }
1272
+ catch { }
1273
+ }
1274
+ if (this.httpHandle) {
1275
+ try {
1276
+ await this.httpHandle.close();
1277
+ }
1278
+ catch { }
1279
+ }
1280
+ this.stateManager.clean();
1281
+ this.lockManager.release();
1282
+ }
1283
+ process.exit(0);
1284
+ };
1285
+ process.on('SIGINT', shutdown);
1286
+ process.on('SIGTERM', shutdown);
1287
+ process.on('SIGHUP', shutdown);
1288
+ process.on('exit', () => {
1289
+ if (this.isOwner && !shuttingDown) {
1290
+ if (this.config.registerInCentral) {
1291
+ try {
1292
+ this.centralRegistry.updateStatus(this.config.name, 'stopped');
1293
+ }
1294
+ catch { }
1295
+ }
1296
+ this.stateManager.clean();
1297
+ this.lockManager.release();
1298
+ }
1299
+ });
1300
+ // Start stdio proxy bridge to target local HTTP server
1301
+ const mcpUrl = `http://${targetHost}:${targetPort}/mcp`;
1302
+ this.stdioProxyHandle = await startStdioProxy(mcpUrl, this.logger);
1303
+ // Wait until stdio bridge completes (client closes stdin / disconnects)
1304
+ await this.stdioProxyHandle.done;
1305
+ // After this process's stdio bridge closes:
1306
+ if (this.isOwner) {
1307
+ ownerStdioClosed = true;
1308
+ // If we own the server, check if other sessions are still active
1309
+ if (this.sessions.size === 0) {
1310
+ this.logger.info('All sessions closed, owner shutting down', { pid: process.pid });
1311
+ await shutdown();
1312
+ }
1313
+ else {
1314
+ this.logger.info('Owner stdio closed, keeping HTTP server alive for active sessions', {
1315
+ activeSessions: this.sessions.size
1316
+ });
1317
+ // HTTP server continues running on Node event loop until other sessions finish
1318
+ }
1319
+ }
1320
+ else {
1321
+ // If we are just a bridge process, exit immediately
1322
+ process.exit(0);
1323
+ }
1324
+ }
1325
+ }
1326
+ /**
1327
+ * Creates an MCP server application.
1328
+ */
1329
+ export function createMcpServer(config) {
1330
+ return new McpApp(config);
1331
+ }
1332
+ //# sourceMappingURL=app.js.map