@angular-modernizer/adapter-mcp 0.2.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 (255) hide show
  1. package/README.md +188 -235
  2. package/dist/cli.js +77 -27
  3. package/dist/index.d.ts +11 -3
  4. package/dist/index.js +10 -2
  5. package/dist/mcp-watcher.d.ts +6 -1
  6. package/dist/mcp-watcher.js +14 -10
  7. package/dist/server/limited-stdio-transport.d.ts +68 -0
  8. package/dist/server/limited-stdio-transport.js +115 -0
  9. package/dist/server/mcp-server.d.ts +41 -12
  10. package/dist/server/mcp-server.js +113 -94
  11. package/dist/server/package-version.d.ts +16 -0
  12. package/dist/server/package-version.js +37 -0
  13. package/dist/server/sdk-server.d.ts +70 -0
  14. package/dist/server/sdk-server.js +113 -0
  15. package/dist/server/stdio-guard.d.ts +20 -0
  16. package/dist/server/stdio-guard.js +48 -0
  17. package/dist/server/tool-registry.d.ts +3 -2
  18. package/dist/server/tool-registry.js +5 -5
  19. package/dist/tools/analyze-build-impact.d.ts +346 -14
  20. package/dist/tools/analyze-build-impact.js +315 -31
  21. package/dist/tools/analyze-core-to-shared.d.ts +134 -4
  22. package/dist/tools/analyze-core-to-shared.js +113 -9
  23. package/dist/tools/analyze-parser-performance.d.ts +200 -7
  24. package/dist/tools/analyze-parser-performance.js +108 -47
  25. package/dist/tools/analyze-project.d.ts +267 -5
  26. package/dist/tools/analyze-project.js +196 -8
  27. package/dist/tools/check-incremental-compatibility.d.ts +61 -1
  28. package/dist/tools/check-incremental-compatibility.js +58 -2
  29. package/dist/tools/collect-feedback.d.ts +199 -10
  30. package/dist/tools/collect-feedback.js +171 -99
  31. package/dist/tools/compare-health.d.ts +356 -0
  32. package/dist/tools/compare-health.js +472 -0
  33. package/dist/tools/extract-libraries.d.ts +156 -4
  34. package/dist/tools/extract-libraries.js +115 -10
  35. package/dist/tools/find-angular-symbol.d.ts +98 -9
  36. package/dist/tools/find-angular-symbol.js +104 -12
  37. package/dist/tools/find-component-hosts.d.ts +684 -0
  38. package/dist/tools/find-component-hosts.js +441 -0
  39. package/dist/tools/find-usages.d.ts +99 -4
  40. package/dist/tools/find-usages.js +131 -11
  41. package/dist/tools/get-bootstrap-execution.d.ts +258 -0
  42. package/dist/tools/get-bootstrap-execution.js +324 -0
  43. package/dist/tools/get-call-graph.d.ts +139 -4
  44. package/dist/tools/get-call-graph.js +123 -13
  45. package/dist/tools/get-operation-progress-tool.d.ts +114 -2
  46. package/dist/tools/get-operation-progress-tool.js +114 -7
  47. package/dist/tools/get-operation-progress.d.ts +1 -1
  48. package/dist/tools/get-operation-progress.js +5 -5
  49. package/dist/tools/helpers/analysis-output.d.ts +177 -0
  50. package/dist/tools/helpers/analysis-output.js +165 -0
  51. package/dist/tools/helpers/build-schemas.d.ts +36 -0
  52. package/dist/tools/helpers/build-schemas.js +23 -0
  53. package/dist/tools/helpers/citation-file-source.d.ts +10 -0
  54. package/dist/tools/helpers/citation-file-source.js +82 -0
  55. package/dist/tools/helpers/compact-output.d.ts +61 -0
  56. package/dist/tools/helpers/compact-output.js +83 -0
  57. package/dist/tools/helpers/finding-window.d.ts +43 -0
  58. package/dist/tools/helpers/finding-window.js +64 -0
  59. package/dist/tools/helpers/health-delta.d.ts +86 -0
  60. package/dist/tools/helpers/health-delta.js +239 -0
  61. package/dist/tools/helpers/investigation-schemas.d.ts +93 -0
  62. package/dist/tools/helpers/investigation-schemas.js +48 -0
  63. package/dist/tools/helpers/library-imports.d.ts +57 -0
  64. package/dist/tools/helpers/library-imports.js +151 -0
  65. package/dist/tools/helpers/load-source-files.d.ts +30 -0
  66. package/dist/tools/helpers/load-source-files.js +34 -0
  67. package/dist/tools/helpers/output-contract.d.ts +32 -0
  68. package/dist/tools/helpers/output-contract.js +32 -0
  69. package/dist/tools/helpers/platform-root-resolver.d.ts +55 -25
  70. package/dist/tools/helpers/platform-root-resolver.js +75 -48
  71. package/dist/tools/helpers/process-output.d.ts +19 -0
  72. package/dist/tools/helpers/process-output.js +31 -0
  73. package/dist/tools/helpers/project-cache.d.ts +184 -0
  74. package/dist/tools/helpers/project-cache.js +331 -0
  75. package/dist/tools/helpers/project-decorators.d.ts +14 -0
  76. package/dist/tools/helpers/project-decorators.js +22 -0
  77. package/dist/tools/helpers/rule-matcher.js +5 -0
  78. package/dist/tools/helpers/rule-runner.d.ts +72 -0
  79. package/dist/tools/helpers/rule-runner.js +131 -0
  80. package/dist/tools/helpers/scan-cache.d.ts +22 -0
  81. package/dist/tools/helpers/scan-cache.js +34 -0
  82. package/dist/tools/helpers/scan-plan.d.ts +48 -0
  83. package/dist/tools/helpers/scan-plan.js +166 -0
  84. package/dist/tools/helpers/scope-paths.d.ts +17 -0
  85. package/dist/tools/helpers/scope-paths.js +32 -0
  86. package/dist/tools/helpers/stack-frame-file-index.d.ts +10 -0
  87. package/dist/tools/helpers/stack-frame-file-index.js +71 -0
  88. package/dist/tools/helpers/tool-context.d.ts +60 -0
  89. package/dist/tools/helpers/tool-context.js +82 -0
  90. package/dist/tools/helpers/transform-safety.d.ts +40 -0
  91. package/dist/tools/helpers/transform-safety.js +87 -0
  92. package/dist/tools/helpers/validation-output.d.ts +53 -0
  93. package/dist/tools/helpers/validation-output.js +48 -0
  94. package/dist/tools/inspect-form-group.d.ts +324 -0
  95. package/dist/tools/inspect-form-group.js +279 -0
  96. package/dist/tools/inspect-i18n.d.ts +466 -0
  97. package/dist/tools/inspect-i18n.js +400 -0
  98. package/dist/tools/inspect-template.d.ts +320 -0
  99. package/dist/tools/inspect-template.js +324 -0
  100. package/dist/tools/learn-patterns.d.ts +122 -1
  101. package/dist/tools/learn-patterns.js +97 -2
  102. package/dist/tools/list-imports.d.ts +128 -11
  103. package/dist/tools/list-imports.js +128 -8
  104. package/dist/tools/orchestrate-migration.d.ts +129 -5
  105. package/dist/tools/orchestrate-migration.js +166 -12
  106. package/dist/tools/parse-stack-trace.d.ts +59 -2
  107. package/dist/tools/parse-stack-trace.js +52 -4
  108. package/dist/tools/plan-migration.d.ts +418 -1
  109. package/dist/tools/plan-migration.js +355 -8
  110. package/dist/tools/resolve-type.d.ts +42 -1
  111. package/dist/tools/resolve-type.js +37 -4
  112. package/dist/tools/review-feedback.d.ts +206 -11
  113. package/dist/tools/review-feedback.js +132 -51
  114. package/dist/tools/rollback-changes.d.ts +79 -2
  115. package/dist/tools/rollback-changes.js +66 -14
  116. package/dist/tools/run-angular-cli.d.ts +45 -2
  117. package/dist/tools/run-angular-cli.js +67 -7
  118. package/dist/tools/run-build.d.ts +114 -2
  119. package/dist/tools/run-build.js +117 -8
  120. package/dist/tools/run-schematic.d.ts +70 -2
  121. package/dist/tools/run-schematic.js +104 -10
  122. package/dist/tools/scan-all.d.ts +24 -16
  123. package/dist/tools/scan-all.js +145 -137
  124. package/dist/tools/scan-angular.d.ts +20 -11
  125. package/dist/tools/scan-angular.js +52 -24
  126. package/dist/tools/scan-architecture.d.ts +42 -14
  127. package/dist/tools/scan-architecture.js +206 -163
  128. package/dist/tools/scan-solid.d.ts +20 -11
  129. package/dist/tools/scan-solid.js +52 -24
  130. package/dist/tools/search-codebase.d.ts +85 -1
  131. package/dist/tools/search-codebase.js +61 -4
  132. package/dist/tools/server-status.d.ts +370 -0
  133. package/dist/tools/server-status.js +369 -0
  134. package/dist/tools/suggest-improvements.d.ts +97 -5
  135. package/dist/tools/suggest-improvements.js +80 -44
  136. package/dist/tools/trace-output-flow.d.ts +791 -0
  137. package/dist/tools/trace-output-flow.js +668 -0
  138. package/dist/tools/transform-code-batch.d.ts +3 -0
  139. package/dist/tools/transform-code-batch.js +10 -5
  140. package/dist/tools/transform-code.d.ts +335 -12
  141. package/dist/tools/transform-code.js +649 -608
  142. package/dist/tools/validate-before-transform.d.ts +116 -2
  143. package/dist/tools/validate-before-transform.js +55 -2
  144. package/dist/tools/validate-project-compatibility.d.ts +64 -2
  145. package/dist/tools/validate-project-compatibility.js +67 -4
  146. package/dist/tools/validate-transformation.d.ts +220 -2
  147. package/dist/tools/validate-transformation.js +113 -15
  148. package/dist/tools/verify-citations.d.ts +181 -0
  149. package/dist/tools/verify-citations.js +218 -0
  150. package/dist/types.d.ts +45 -1
  151. package/dist/utils/format-tool-response.d.ts +22 -59
  152. package/dist/utils/format-tool-response.js +25 -134
  153. package/package.json +30 -13
  154. package/dist/cli.d.ts.map +0 -1
  155. package/dist/cli.js.map +0 -1
  156. package/dist/core/project-analyzer.d.ts.map +0 -1
  157. package/dist/core/project-analyzer.js.map +0 -1
  158. package/dist/index.d.ts.map +0 -1
  159. package/dist/index.js.map +0 -1
  160. package/dist/mcp-watcher.d.ts.map +0 -1
  161. package/dist/mcp-watcher.js.map +0 -1
  162. package/dist/server/json-rpc-handler.d.ts +0 -57
  163. package/dist/server/json-rpc-handler.d.ts.map +0 -1
  164. package/dist/server/json-rpc-handler.js +0 -222
  165. package/dist/server/json-rpc-handler.js.map +0 -1
  166. package/dist/server/mcp-server.d.ts.map +0 -1
  167. package/dist/server/mcp-server.js.map +0 -1
  168. package/dist/server/tool-registry.d.ts.map +0 -1
  169. package/dist/server/tool-registry.js.map +0 -1
  170. package/dist/streaming/progress-store.d.ts.map +0 -1
  171. package/dist/streaming/progress-store.js.map +0 -1
  172. package/dist/tools/analyze-build-impact.d.ts.map +0 -1
  173. package/dist/tools/analyze-build-impact.js.map +0 -1
  174. package/dist/tools/analyze-core-to-shared.d.ts.map +0 -1
  175. package/dist/tools/analyze-core-to-shared.js.map +0 -1
  176. package/dist/tools/analyze-parser-performance.d.ts.map +0 -1
  177. package/dist/tools/analyze-parser-performance.js.map +0 -1
  178. package/dist/tools/analyze-project.d.ts.map +0 -1
  179. package/dist/tools/analyze-project.js.map +0 -1
  180. package/dist/tools/check-incremental-compatibility.d.ts.map +0 -1
  181. package/dist/tools/check-incremental-compatibility.js.map +0 -1
  182. package/dist/tools/collect-feedback.d.ts.map +0 -1
  183. package/dist/tools/collect-feedback.js.map +0 -1
  184. package/dist/tools/extract-libraries.d.ts.map +0 -1
  185. package/dist/tools/extract-libraries.js.map +0 -1
  186. package/dist/tools/find-angular-symbol.d.ts.map +0 -1
  187. package/dist/tools/find-angular-symbol.js.map +0 -1
  188. package/dist/tools/find-usages.d.ts.map +0 -1
  189. package/dist/tools/find-usages.js.map +0 -1
  190. package/dist/tools/get-call-graph.d.ts.map +0 -1
  191. package/dist/tools/get-call-graph.js.map +0 -1
  192. package/dist/tools/get-operation-progress-tool.d.ts.map +0 -1
  193. package/dist/tools/get-operation-progress-tool.js.map +0 -1
  194. package/dist/tools/get-operation-progress.d.ts.map +0 -1
  195. package/dist/tools/get-operation-progress.js.map +0 -1
  196. package/dist/tools/helpers/feedback-analyzer.d.ts.map +0 -1
  197. package/dist/tools/helpers/feedback-analyzer.js.map +0 -1
  198. package/dist/tools/helpers/find-ts-config.d.ts.map +0 -1
  199. package/dist/tools/helpers/find-ts-config.js.map +0 -1
  200. package/dist/tools/helpers/platform-root-resolver.d.ts.map +0 -1
  201. package/dist/tools/helpers/platform-root-resolver.js.map +0 -1
  202. package/dist/tools/helpers/rule-matcher.d.ts.map +0 -1
  203. package/dist/tools/helpers/rule-matcher.js.map +0 -1
  204. package/dist/tools/helpers/suggestion-generator.d.ts.map +0 -1
  205. package/dist/tools/helpers/suggestion-generator.js.map +0 -1
  206. package/dist/tools/learn-patterns.d.ts.map +0 -1
  207. package/dist/tools/learn-patterns.js.map +0 -1
  208. package/dist/tools/list-imports.d.ts.map +0 -1
  209. package/dist/tools/list-imports.js.map +0 -1
  210. package/dist/tools/orchestrate-migration.d.ts.map +0 -1
  211. package/dist/tools/orchestrate-migration.js.map +0 -1
  212. package/dist/tools/parse-stack-trace.d.ts.map +0 -1
  213. package/dist/tools/parse-stack-trace.js.map +0 -1
  214. package/dist/tools/plan-migration.d.ts.map +0 -1
  215. package/dist/tools/plan-migration.js.map +0 -1
  216. package/dist/tools/resolve-type.d.ts.map +0 -1
  217. package/dist/tools/resolve-type.js.map +0 -1
  218. package/dist/tools/review-feedback.d.ts.map +0 -1
  219. package/dist/tools/review-feedback.js.map +0 -1
  220. package/dist/tools/rollback-changes.d.ts.map +0 -1
  221. package/dist/tools/rollback-changes.js.map +0 -1
  222. package/dist/tools/run-angular-cli.d.ts.map +0 -1
  223. package/dist/tools/run-angular-cli.js.map +0 -1
  224. package/dist/tools/run-build.d.ts.map +0 -1
  225. package/dist/tools/run-build.js.map +0 -1
  226. package/dist/tools/run-schematic.d.ts.map +0 -1
  227. package/dist/tools/run-schematic.js.map +0 -1
  228. package/dist/tools/scan-all.d.ts.map +0 -1
  229. package/dist/tools/scan-all.js.map +0 -1
  230. package/dist/tools/scan-angular.d.ts.map +0 -1
  231. package/dist/tools/scan-angular.js.map +0 -1
  232. package/dist/tools/scan-architecture.d.ts.map +0 -1
  233. package/dist/tools/scan-architecture.js.map +0 -1
  234. package/dist/tools/scan-solid.d.ts.map +0 -1
  235. package/dist/tools/scan-solid.js.map +0 -1
  236. package/dist/tools/search-codebase.d.ts.map +0 -1
  237. package/dist/tools/search-codebase.js.map +0 -1
  238. package/dist/tools/shared/scan-types.d.ts.map +0 -1
  239. package/dist/tools/shared/scan-types.js.map +0 -1
  240. package/dist/tools/suggest-improvements.d.ts.map +0 -1
  241. package/dist/tools/suggest-improvements.js.map +0 -1
  242. package/dist/tools/transform-code-batch.d.ts.map +0 -1
  243. package/dist/tools/transform-code-batch.js.map +0 -1
  244. package/dist/tools/transform-code.d.ts.map +0 -1
  245. package/dist/tools/transform-code.js.map +0 -1
  246. package/dist/tools/validate-before-transform.d.ts.map +0 -1
  247. package/dist/tools/validate-before-transform.js.map +0 -1
  248. package/dist/tools/validate-project-compatibility.d.ts.map +0 -1
  249. package/dist/tools/validate-project-compatibility.js.map +0 -1
  250. package/dist/tools/validate-transformation.d.ts.map +0 -1
  251. package/dist/tools/validate-transformation.js.map +0 -1
  252. package/dist/types.d.ts.map +0 -1
  253. package/dist/types.js.map +0 -1
  254. package/dist/utils/format-tool-response.d.ts.map +0 -1
  255. package/dist/utils/format-tool-response.js.map +0 -1
@@ -1,44 +1,52 @@
1
1
  /**
2
2
  * @angular-modernizer/adapter-mcp - MCP Server
3
3
  *
4
- * Main MCP server implementation that coordinates tool registry,
5
- * JSON-RPC handling, and stdio communication.
4
+ * Owns the stdio server lifecycle. The protocol is served by the MCP SDK
5
+ * (`serveStdio`, both eras) over a size-limited stdio transport; the tools
6
+ * come from the tool registry.
6
7
  */
8
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
7
9
  import { ToolRegistry } from './tool-registry.js';
8
- import { JsonRpcHandler } from './json-rpc-handler.js';
9
- import { startMCPWatcher, stopMCPWatcher, getMCPWatcher, } from '../mcp-watcher.js';
10
+ import { createServerFactory } from './sdk-server.js';
11
+ import { LimitedStdioTransport } from './limited-stdio-transport.js';
12
+ import { isDebugEnabled, startMCPWatcher, stopMCPWatcher, getMCPWatcher, } from '../mcp-watcher.js';
10
13
  /**
11
- * Write debug message to MCP log file via watcher
14
+ * Write debug message to the MCP log file; only with the debug watcher on.
12
15
  */
13
16
  function debugLog(message) {
14
- const watcher = getMCPWatcher();
15
- if (watcher) {
16
- watcher.log('DEBUG', message);
17
- }
18
- else {
19
- console.error(`[DEBUG] ${message}`);
20
- }
17
+ getMCPWatcher()?.log('DEBUG', message);
21
18
  }
19
+ /** Longest wait for stdout/stderr to flush before a shutdown exits anyway. */
20
+ const SHUTDOWN_FLUSH_TIMEOUT_MS = 1000;
22
21
  /**
23
22
  * Main MCP server class that handles the complete MCP protocol lifecycle.
23
+ *
24
+ * @remarks
25
+ * The stdio server ends when the client goes away: stdin `end`, `close` or
26
+ * `error`, a failing stdout (EPIPE), SIGINT, SIGTERM, SIGHUP, or its parent
27
+ * process disappearing. The last check covers clients that die while another
28
+ * process still holds the stdin pipe open, so EOF never arrives.
24
29
  */
25
30
  export class MCPServer {
26
31
  registry;
27
- handler;
28
32
  config;
33
+ protocol = {};
34
+ transport;
35
+ handle;
29
36
  running = false;
30
- /** Accumulates incomplete JSON-RPC lines across stdin data events (BUG-6). */
31
- inputBuffer = '';
37
+ shuttingDown = false;
38
+ parentWatch;
39
+ startedAt;
32
40
  constructor(config = {}) {
33
41
  this.config = {
34
42
  timeout: 30000, // 30 seconds default
35
43
  maxConcurrentTools: 5,
36
44
  logLevel: 'info',
37
45
  enableMetrics: false,
46
+ parentCheckIntervalMs: 2000,
38
47
  ...config,
39
48
  };
40
49
  this.registry = new ToolRegistry();
41
- this.handler = new JsonRpcHandler(this.registry);
42
50
  }
43
51
  /**
44
52
  * Register an MCP tool with the server.
@@ -55,44 +63,33 @@ export class MCPServer {
55
63
  throw new Error('MCP server is already running');
56
64
  }
57
65
  this.running = true;
66
+ this.startedAt = new Date();
58
67
  this.log('info', 'MCP server starting...');
59
- // Start MCP Watcher for debugging (3 second heartbeat, health check on port 9999)
60
- startMCPWatcher('./mcp-server.log', 3000, 9999);
61
- this.log('info', 'MCP Watcher started (heartbeat: 3s, health check: http://localhost:9999)');
62
- debugLog('MCP start() called, setting up stdio handlers');
63
- // Set up stdio handlers
64
- process.stdin.setEncoding('utf8');
65
- debugLog('MCP stdin encoding set to utf8');
66
- process.stdin.on('data', (chunk) => {
67
- debugLog(`MCP stdin data event - chunk length: ${chunk.length}, first 200 chars: ${chunk.substring(0, 200)}`);
68
- this.handleInput(chunk).catch((error) => {
69
- this.log('error', 'Error handling input:', error);
70
- });
71
- });
72
- debugLog('MCP stdin data handler registered');
73
- process.stdin.on('end', () => {
74
- this.log('info', 'MCP server shutting down (stdin closed)');
75
- stopMCPWatcher();
76
- this.running = false;
77
- // Flush streams and exit to prevent hanging clients
78
- process.stdout.write('', () => {
79
- process.stderr.write('', () => {
80
- process.exit(0);
81
- });
82
- });
83
- });
84
- process.on('SIGINT', () => {
85
- this.log('info', 'MCP server shutting down (SIGINT)');
86
- stopMCPWatcher();
87
- this.running = false;
88
- process.exit(0);
89
- });
90
- process.on('SIGTERM', () => {
91
- this.log('info', 'MCP server shutting down (SIGTERM)');
92
- stopMCPWatcher();
93
- this.running = false;
94
- process.exit(0);
68
+ // Debug log ./mcp-server.log and the health check on :9999 write into the
69
+ // client's working directory and open a port; opt-in only
70
+ if (isDebugEnabled()) {
71
+ startMCPWatcher('./mcp-server.log', 3000, 9999);
72
+ this.log('info', 'MCP Watcher started (heartbeat: 3s, health check: http://localhost:9999)');
73
+ }
74
+ const transport = new LimitedStdioTransport();
75
+ this.transport = transport;
76
+ this.handle = serveStdio(createServerFactory(this.registry, {
77
+ onToolCall: (id, tool) => transport.trackToolCall(id, tool),
78
+ protocol: this.protocol,
79
+ }), {
80
+ transport,
81
+ onerror: (error) => this.log('error', 'MCP protocol error:', error.message),
95
82
  });
83
+ debugLog('MCP serveStdio started');
84
+ process.stdin.on('end', () => this.shutdown('stdin ended'));
85
+ process.stdin.on('close', () => this.shutdown('stdin closed'));
86
+ process.stdin.on('error', (error) => this.shutdown(`stdin error: ${error.message}`));
87
+ // Writing to a pipe whose reader is gone fails with EPIPE
88
+ process.stdout.on('error', (error) => this.shutdown(`stdout error: ${error.message}`));
89
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
90
+ process.on(signal, () => this.shutdown(signal));
91
+ }
92
+ this.watchParent();
96
93
  this.log('info', `MCP server started with ${this.registry.getStats().totalTools} tools`);
97
94
  debugLog('MCP Server fully initialized, waiting for stdin input');
98
95
  }
@@ -100,6 +97,10 @@ export class MCPServer {
100
97
  * Stop the MCP server.
101
98
  */
102
99
  stop() {
100
+ this.stopParentWatch();
101
+ this.handle?.close().catch(() => {
102
+ // Already closed
103
+ });
103
104
  stopMCPWatcher();
104
105
  this.running = false;
105
106
  this.log('info', 'MCP server stopped');
@@ -120,55 +121,73 @@ export class MCPServer {
120
121
  };
121
122
  }
122
123
  /**
123
- * Get all registered tools as a map.
124
+ * Runtime figures for `server-status`: start time, tool count, response sizes.
124
125
  */
125
- getToolsMap() {
126
- return this.registry.getAllToolsMap();
126
+ getRuntimeStats() {
127
+ return {
128
+ startedAt: (this.startedAt ?? new Date()).toISOString(),
129
+ toolCount: this.registry.getStats().totalTools,
130
+ responses: this.transport?.getResponseStats() ?? {
131
+ count: 0,
132
+ totalBytes: 0,
133
+ oversized: 0,
134
+ },
135
+ protocol: { ...this.protocol },
136
+ };
127
137
  }
128
138
  /**
129
- * Handle incoming data from stdin.
130
- * Accumulates chunks in a buffer and processes only complete newline-terminated
131
- * JSON-RPC lines. The remainder of an incomplete line is carried forward to the
132
- * next data event (BUG-6).
139
+ * Ends the process once: closes the SDK connection (requests in flight are
140
+ * aborted, not answered), stops the watcher, flushes stdout/stderr and
141
+ * exits. A dead pipe must not block the exit, so the flush is capped.
133
142
  */
134
- async handleInput(chunk) {
135
- this.inputBuffer += chunk;
136
- // Split on newlines; the last element is either empty (complete line) or an
137
- // incomplete fragment that must be held back until more data arrives.
138
- const lines = this.inputBuffer.split('\n');
139
- // Keep the trailing incomplete fragment in the buffer.
140
- this.inputBuffer = lines.pop() ?? '';
141
- for (const line of lines) {
142
- if (line.trim()) {
143
- try {
144
- debugLog(`MCP handleInput: Received line (first 150 chars): ${line.trim().substring(0, 150)}`);
145
- const response = await this.handler.processMessage(line.trim());
146
- debugLog(`MCP handleInput: processMessage returned ${response ? `response with id=${response.id}` : 'NULL'}`);
147
- if (response) {
148
- debugLog(`MCP handleInput: Calling sendResponse with id=${response.id}`);
149
- await this.handler.sendResponse(response);
150
- }
151
- else {
152
- debugLog('MCP handleInput: No response to send (processMessage returned null)');
153
- }
154
- }
155
- catch (error) {
156
- this.log('error', 'Error processing message:', error);
157
- // Send error response
158
- const errorResponse = {
159
- jsonrpc: '2.0',
160
- id: null,
161
- error: {
162
- code: -32603,
163
- message: 'Internal error',
164
- data: error instanceof Error ? error.message : String(error),
165
- },
166
- };
167
- await this.handler.sendResponse(errorResponse);
168
- }
143
+ shutdown(reason) {
144
+ if (this.shuttingDown) {
145
+ return;
146
+ }
147
+ this.shuttingDown = true;
148
+ this.log('info', `MCP server shutting down (${reason})`);
149
+ this.stopParentWatch();
150
+ this.handle?.close().catch(() => {
151
+ // The transport may already be gone (EPIPE, stdin closed)
152
+ });
153
+ stopMCPWatcher();
154
+ this.running = false;
155
+ setTimeout(() => process.exit(0), SHUTDOWN_FLUSH_TIMEOUT_MS).unref();
156
+ process.stdout.write('', () => {
157
+ process.stderr.write('', () => {
158
+ process.exit(0);
159
+ });
160
+ });
161
+ }
162
+ /**
163
+ * Shuts down when the process gets re-parented, i.e. the client that
164
+ * started it is gone. The timer does not keep the process alive.
165
+ */
166
+ watchParent() {
167
+ const interval = this.config.parentCheckIntervalMs ?? 0;
168
+ if (interval <= 0) {
169
+ return;
170
+ }
171
+ const parent = process.ppid;
172
+ this.parentWatch = setInterval(() => {
173
+ if (process.ppid !== parent) {
174
+ this.shutdown(`parent process ${parent} exited`);
169
175
  }
176
+ }, interval);
177
+ this.parentWatch.unref();
178
+ }
179
+ stopParentWatch() {
180
+ if (this.parentWatch !== undefined) {
181
+ clearInterval(this.parentWatch);
182
+ this.parentWatch = undefined;
170
183
  }
171
184
  }
185
+ /**
186
+ * Get all registered tools as a map.
187
+ */
188
+ getToolsMap() {
189
+ return this.registry.getAllToolsMap();
190
+ }
172
191
  /**
173
192
  * Log a message based on configured log level.
174
193
  */
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - Package version
3
+ *
4
+ * The version the server reports in `initialize` and `server-status`, read
5
+ * from this package's package.json so it cannot drift from the release.
6
+ */
7
+ /**
8
+ * Walks up from `startDir` to the package.json named `PACKAGE_NAME` and
9
+ * returns its version. The walk covers both `dist/server/` at runtime and
10
+ * `src/` under Jest, where `import.meta.url` is mocked to `src/index.ts`.
11
+ * Returns `'0.0.0'` when no matching package.json is found.
12
+ */
13
+ export declare function readPackageVersion(startDir: string): string;
14
+ /** Version of `@angular-modernizer/adapter-mcp`, resolved once at load. */
15
+ export declare const PACKAGE_VERSION: string;
16
+ //# sourceMappingURL=package-version.d.ts.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - Package version
3
+ *
4
+ * The version the server reports in `initialize` and `server-status`, read
5
+ * from this package's package.json so it cannot drift from the release.
6
+ */
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ const PACKAGE_NAME = '@angular-modernizer/adapter-mcp';
11
+ /**
12
+ * Walks up from `startDir` to the package.json named `PACKAGE_NAME` and
13
+ * returns its version. The walk covers both `dist/server/` at runtime and
14
+ * `src/` under Jest, where `import.meta.url` is mocked to `src/index.ts`.
15
+ * Returns `'0.0.0'` when no matching package.json is found.
16
+ */
17
+ export function readPackageVersion(startDir) {
18
+ let dir = startDir;
19
+ for (;;) {
20
+ const candidate = join(dir, 'package.json');
21
+ if (existsSync(candidate)) {
22
+ const manifest = JSON.parse(readFileSync(candidate, 'utf8'));
23
+ if (manifest.name === PACKAGE_NAME &&
24
+ typeof manifest.version === 'string') {
25
+ return manifest.version;
26
+ }
27
+ }
28
+ const parent = dirname(dir);
29
+ if (parent === dir) {
30
+ return '0.0.0';
31
+ }
32
+ dir = parent;
33
+ }
34
+ }
35
+ /** Version of `@angular-modernizer/adapter-mcp`, resolved once at load. */
36
+ export const PACKAGE_VERSION = readPackageVersion(dirname(fileURLToPath(import.meta.url)));
37
+ //# sourceMappingURL=package-version.js.map
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - SDK server factory
3
+ *
4
+ * Builds the `McpServer` instances `serveStdio` asks for: one per connection
5
+ * (plus a discarded probe for `server/discover`). Every registered `MCPTool`
6
+ * is exposed through `registerTool` with its JSON Schemas as they are; the
7
+ * arguments are validated against the input schema (Ajv, JSON Schema 2020-12)
8
+ * before the tool runs, so invalid arguments come back as an `isError` result
9
+ * without reaching the tool. A tool with an `outputSchema` has its
10
+ * `structuredContent` validated the same way; the SDK replaces a result that
11
+ * does not match with an `isError` result (results that already report
12
+ * `isError` are not checked). The response format is the one of
13
+ * `ToolRegistry.executeTool`.
14
+ *
15
+ * Every call gets the request's abort signal (`notifications/cancelled`; the
16
+ * SDK sends no response for an aborted request) and, when the client sent a
17
+ * `progressToken`, a throttled `progress` that sends `notifications/progress`.
18
+ */
19
+ import { type McpServerFactory, type RequestId, type jsonSchemaValidator } from '@modelcontextprotocol/server';
20
+ import { type ToolRegistry } from './tool-registry.js';
21
+ import { type ToolContext } from '../types.js';
22
+ /** Protocol era of a connection: 2025 handshake or 2026-07-28 envelope. */
23
+ export type ProtocolEra = 'legacy' | 'modern';
24
+ /** What the client negotiated, as far as it is known. */
25
+ export interface ProtocolInfo {
26
+ era?: ProtocolEra;
27
+ /** Protocol revision the last request was served with. */
28
+ version?: string;
29
+ }
30
+ export interface SdkServerHooks {
31
+ /** Called with the request id when a tool call starts. */
32
+ onToolCall?: (id: RequestId, tool: string) => void;
33
+ /** Updated on `initialize` and on every tool call. */
34
+ protocol?: ProtocolInfo;
35
+ }
36
+ /**
37
+ * Validates tool arguments. One instance for all connections: Ajv caches the
38
+ * compiled schema per schema object, so every input schema compiles once.
39
+ * Defaults of the SDK: `strict: false`, `allErrors: true`, formats registered.
40
+ */
41
+ export declare const INPUT_VALIDATOR: jsonSchemaValidator;
42
+ /**
43
+ * Validates `structuredContent` against the output schema, same settings as
44
+ * the input validator. Output schemas leave objects open, so a new result
45
+ * field never fails; a missing required field or a wrong type does.
46
+ */
47
+ export declare const OUTPUT_VALIDATOR: jsonSchemaValidator;
48
+ /**
49
+ * Factory for `serveStdio`: registers every tool of `registry` on a fresh
50
+ * `McpServer` for the era the SDK asks for.
51
+ */
52
+ export declare function createServerFactory(registry: ToolRegistry, hooks?: SdkServerHooks): McpServerFactory;
53
+ /** The parts of the SDK request context a tool call needs. */
54
+ interface RequestContext {
55
+ signal: AbortSignal;
56
+ _meta?: {
57
+ progressToken?: string | number;
58
+ };
59
+ notify: (notification: {
60
+ method: 'notifications/progress';
61
+ params: Record<string, unknown>;
62
+ }) => Promise<void>;
63
+ }
64
+ /**
65
+ * Tool context of one request: its abort signal and, only with a
66
+ * `progressToken`, a throttled sender of `notifications/progress`.
67
+ */
68
+ export declare function toolContext(req: RequestContext): ToolContext;
69
+ export {};
70
+ //# sourceMappingURL=sdk-server.d.ts.map
@@ -0,0 +1,113 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - SDK server factory
3
+ *
4
+ * Builds the `McpServer` instances `serveStdio` asks for: one per connection
5
+ * (plus a discarded probe for `server/discover`). Every registered `MCPTool`
6
+ * is exposed through `registerTool` with its JSON Schemas as they are; the
7
+ * arguments are validated against the input schema (Ajv, JSON Schema 2020-12)
8
+ * before the tool runs, so invalid arguments come back as an `isError` result
9
+ * without reaching the tool. A tool with an `outputSchema` has its
10
+ * `structuredContent` validated the same way; the SDK replaces a result that
11
+ * does not match with an `isError` result (results that already report
12
+ * `isError` are not checked). The response format is the one of
13
+ * `ToolRegistry.executeTool`.
14
+ *
15
+ * Every call gets the request's abort signal (`notifications/cancelled`; the
16
+ * SDK sends no response for an aborted request) and, when the client sent a
17
+ * `progressToken`, a throttled `progress` that sends `notifications/progress`.
18
+ */
19
+ import { McpServer, fromJsonSchema, } from '@modelcontextprotocol/server';
20
+ import { AjvJsonSchemaValidator } from '@modelcontextprotocol/server/validators/ajv';
21
+ import { PACKAGE_VERSION } from './package-version.js';
22
+ import { throttleProgress } from '../tools/helpers/tool-context.js';
23
+ /**
24
+ * Validates tool arguments. One instance for all connections: Ajv caches the
25
+ * compiled schema per schema object, so every input schema compiles once.
26
+ * Defaults of the SDK: `strict: false`, `allErrors: true`, formats registered.
27
+ */
28
+ export const INPUT_VALIDATOR = new AjvJsonSchemaValidator();
29
+ /**
30
+ * Validates `structuredContent` against the output schema, same settings as
31
+ * the input validator. Output schemas leave objects open, so a new result
32
+ * field never fails; a missing required field or a wrong type does.
33
+ */
34
+ export const OUTPUT_VALIDATOR = new AjvJsonSchemaValidator();
35
+ /**
36
+ * Factory for `serveStdio`: registers every tool of `registry` on a fresh
37
+ * `McpServer` for the era the SDK asks for.
38
+ */
39
+ export function createServerFactory(registry, hooks = {}) {
40
+ return ({ era }) => {
41
+ const mcp = new McpServer({ name: 'angular-modernizer', version: PACKAGE_VERSION });
42
+ const noteProtocol = () => {
43
+ if (hooks.protocol !== undefined) {
44
+ hooks.protocol.era = era;
45
+ hooks.protocol.version = mcp.server.getNegotiatedProtocolVersion();
46
+ }
47
+ };
48
+ mcp.server.oninitialized = () => {
49
+ noteProtocol();
50
+ console.error('[MCP] Server initialized and ready');
51
+ };
52
+ for (const tool of registry.getAllTools()) {
53
+ mcp.registerTool(tool.name, {
54
+ ...(tool.title === undefined ? {} : { title: tool.title }),
55
+ description: tool.description,
56
+ inputSchema: fromJsonSchema(tool.inputSchema, INPUT_VALIDATOR),
57
+ ...(tool.outputSchema === undefined
58
+ ? {}
59
+ : {
60
+ outputSchema: fromJsonSchema(tool.outputSchema, OUTPUT_VALIDATOR),
61
+ }),
62
+ ...(tool.annotations === undefined ? {} : { annotations: tool.annotations }),
63
+ }, async (args, ctx) => {
64
+ hooks.onToolCall?.(ctx.mcpReq.id, tool.name);
65
+ noteProtocol();
66
+ try {
67
+ return (await registry.executeTool(tool.name, (args ?? {}), toolContext(ctx.mcpReq)));
68
+ }
69
+ catch (error) {
70
+ const message = error instanceof Error ? error.message : 'Tool execution failed';
71
+ return {
72
+ content: [{ type: 'text', text: `Tool execution error: ${message}` }],
73
+ isError: true,
74
+ };
75
+ }
76
+ });
77
+ }
78
+ return mcp;
79
+ };
80
+ }
81
+ /**
82
+ * Tool context of one request: its abort signal and, only with a
83
+ * `progressToken`, a throttled sender of `notifications/progress`.
84
+ */
85
+ export function toolContext(req) {
86
+ const token = req._meta?.progressToken;
87
+ if (token === undefined) {
88
+ return { signal: req.signal };
89
+ }
90
+ let lastProgress = -1;
91
+ const progress = throttleProgress((value, total, message) => {
92
+ // The spec requires a growing value; a tool that restarts a phase must not go back.
93
+ if (value <= lastProgress || req.signal.aborted) {
94
+ return;
95
+ }
96
+ lastProgress = value;
97
+ req
98
+ .notify({
99
+ method: 'notifications/progress',
100
+ params: {
101
+ progressToken: token,
102
+ progress: value,
103
+ ...(total === undefined ? {} : { total }),
104
+ ...(message === undefined ? {} : { message }),
105
+ },
106
+ })
107
+ .catch((error) => {
108
+ console.error('[MCP] Progress notification failed:', error);
109
+ });
110
+ });
111
+ return { signal: req.signal, progress };
112
+ }
113
+ //# sourceMappingURL=sdk-server.js.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - stdio guard
3
+ *
4
+ * On the stdio transport, stdout carries JSON-RPC messages only. Kernel,
5
+ * plugins and tools log through `console.log`/`info`/`debug` in many places;
6
+ * each such line on stdout makes Claude Code log "Ignoring non-JSON line" and
7
+ * can corrupt a response. Instead of fixing every call site, the CLI routes
8
+ * all stdout-bound console methods to stderr once, before the server starts.
9
+ */
10
+ import { type Writable } from 'node:stream';
11
+ /**
12
+ * Rebinds the stdout-bound methods of `target` to a console that writes to
13
+ * `stream` only. Mutates `target` in place, so modules holding a reference to
14
+ * the global `console` object are covered too.
15
+ *
16
+ * @param target - Console to patch. Defaults to the global console.
17
+ * @param stream - Destination for all console output. Defaults to stderr.
18
+ */
19
+ export declare function routeConsoleToStderr(target?: Console, stream?: Writable): void;
20
+ //# sourceMappingURL=stdio-guard.d.ts.map
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - stdio guard
3
+ *
4
+ * On the stdio transport, stdout carries JSON-RPC messages only. Kernel,
5
+ * plugins and tools log through `console.log`/`info`/`debug` in many places;
6
+ * each such line on stdout makes Claude Code log "Ignoring non-JSON line" and
7
+ * can corrupt a response. Instead of fixing every call site, the CLI routes
8
+ * all stdout-bound console methods to stderr once, before the server starts.
9
+ */
10
+ import { Console } from 'node:console';
11
+ /**
12
+ * Console methods rebound to the stderr console. `error`, `warn` and `trace`
13
+ * already write to stderr; they are rebound too so `group` indentation stays
14
+ * consistent across all methods.
15
+ */
16
+ const CONSOLE_METHODS = [
17
+ 'log',
18
+ 'info',
19
+ 'debug',
20
+ 'dir',
21
+ 'dirxml',
22
+ 'table',
23
+ 'count',
24
+ 'countReset',
25
+ 'group',
26
+ 'groupCollapsed',
27
+ 'groupEnd',
28
+ 'time',
29
+ 'timeEnd',
30
+ 'timeLog',
31
+ 'error',
32
+ 'warn',
33
+ 'trace',
34
+ ];
35
+ /**
36
+ * Rebinds the stdout-bound methods of `target` to a console that writes to
37
+ * `stream` only. Mutates `target` in place, so modules holding a reference to
38
+ * the global `console` object are covered too.
39
+ *
40
+ * @param target - Console to patch. Defaults to the global console.
41
+ * @param stream - Destination for all console output. Defaults to stderr.
42
+ */
43
+ export function routeConsoleToStderr(target = console, stream = process.stderr) {
44
+ const stderrConsole = new Console({ stdout: stream, stderr: stream });
45
+ const methods = Object.fromEntries(CONSOLE_METHODS.map((name) => [name, stderrConsole[name]]));
46
+ Object.assign(target, methods);
47
+ }
48
+ //# sourceMappingURL=stdio-guard.js.map
@@ -4,7 +4,7 @@
4
4
  * Central registry for MCP tools. Manages tool registration,
5
5
  * discovery, and execution coordination.
6
6
  */
7
- import { type MCPTool } from '../types.js';
7
+ import { type MCPTool, type ToolContext } from '../types.js';
8
8
  /**
9
9
  * Registry for MCP tools with registration and discovery capabilities.
10
10
  */
@@ -47,10 +47,11 @@ export declare class ToolRegistry {
47
47
  * Execute a tool by name with given arguments.
48
48
  * @param name - Tool name
49
49
  * @param args - Tool arguments
50
+ * @param ctx - Cancellation and progress of the request
50
51
  * @returns Tool execution result in MCP format
51
52
  * @throws Error if tool not found
52
53
  */
53
- executeTool(name: string, args: Record<string, unknown>): Promise<unknown>;
54
+ executeTool(name: string, args: Record<string, unknown>, ctx?: ToolContext): Promise<unknown>;
54
55
  /**
55
56
  * Unregister a tool.
56
57
  * @param name - Tool name
@@ -4,7 +4,7 @@
4
4
  * Central registry for MCP tools. Manages tool registration,
5
5
  * discovery, and execution coordination.
6
6
  */
7
- import { formatToolResponse } from '../utils/format-tool-response.js';
7
+ import { formatStructuredToolResponse } from '../utils/format-tool-response.js';
8
8
  /**
9
9
  * Registry for MCP tools with registration and discovery capabilities.
10
10
  */
@@ -62,17 +62,17 @@ export class ToolRegistry {
62
62
  * Execute a tool by name with given arguments.
63
63
  * @param name - Tool name
64
64
  * @param args - Tool arguments
65
+ * @param ctx - Cancellation and progress of the request
65
66
  * @returns Tool execution result in MCP format
66
67
  * @throws Error if tool not found
67
68
  */
68
- async executeTool(name, args) {
69
+ async executeTool(name, args, ctx) {
69
70
  const tool = this.getTool(name);
70
71
  if (!tool) {
71
72
  throw new Error(`Unknown tool: ${name}`);
72
73
  }
73
- const result = await tool.execute(args);
74
- // Format response according to MCP spec with human-readable summary
75
- return formatToolResponse(name, result);
74
+ const result = (await tool.execute(args, ctx));
75
+ return formatStructuredToolResponse(result);
76
76
  }
77
77
  /**
78
78
  * Unregister a tool.