@angular-modernizer/adapter-mcp 0.3.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/README.md +103 -218
  2. package/dist/cli.js +13 -13
  3. package/dist/index.d.ts +4 -3
  4. package/dist/index.js +3 -2
  5. package/dist/mcp-watcher.d.ts +6 -1
  6. package/dist/mcp-watcher.js +11 -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 +12 -14
  10. package/dist/server/mcp-server.js +41 -75
  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/tool-registry.d.ts +3 -2
  16. package/dist/server/tool-registry.js +5 -5
  17. package/dist/tools/analyze-build-impact.d.ts +220 -1
  18. package/dist/tools/analyze-build-impact.js +145 -3
  19. package/dist/tools/analyze-core-to-shared.d.ts +134 -4
  20. package/dist/tools/analyze-core-to-shared.js +113 -9
  21. package/dist/tools/analyze-parser-performance.d.ts +200 -7
  22. package/dist/tools/analyze-parser-performance.js +108 -47
  23. package/dist/tools/analyze-project.d.ts +267 -5
  24. package/dist/tools/analyze-project.js +196 -8
  25. package/dist/tools/check-incremental-compatibility.d.ts +61 -1
  26. package/dist/tools/check-incremental-compatibility.js +58 -2
  27. package/dist/tools/collect-feedback.d.ts +199 -10
  28. package/dist/tools/collect-feedback.js +171 -99
  29. package/dist/tools/compare-health.d.ts +356 -0
  30. package/dist/tools/compare-health.js +472 -0
  31. package/dist/tools/extract-libraries.d.ts +156 -4
  32. package/dist/tools/extract-libraries.js +115 -10
  33. package/dist/tools/find-angular-symbol.d.ts +69 -3
  34. package/dist/tools/find-angular-symbol.js +55 -8
  35. package/dist/tools/find-component-hosts.d.ts +572 -2
  36. package/dist/tools/find-component-hosts.js +207 -6
  37. package/dist/tools/find-usages.d.ts +79 -1
  38. package/dist/tools/find-usages.js +64 -7
  39. package/dist/tools/get-bootstrap-execution.d.ts +151 -1
  40. package/dist/tools/get-bootstrap-execution.js +84 -3
  41. package/dist/tools/get-call-graph.d.ts +111 -1
  42. package/dist/tools/get-call-graph.js +72 -10
  43. package/dist/tools/get-operation-progress-tool.d.ts +114 -2
  44. package/dist/tools/get-operation-progress-tool.js +114 -7
  45. package/dist/tools/get-operation-progress.d.ts +1 -1
  46. package/dist/tools/get-operation-progress.js +5 -5
  47. package/dist/tools/helpers/analysis-output.d.ts +177 -0
  48. package/dist/tools/helpers/analysis-output.js +165 -0
  49. package/dist/tools/helpers/build-schemas.d.ts +36 -0
  50. package/dist/tools/helpers/build-schemas.js +23 -0
  51. package/dist/tools/helpers/citation-file-source.d.ts +10 -0
  52. package/dist/tools/helpers/citation-file-source.js +82 -0
  53. package/dist/tools/helpers/finding-window.d.ts +43 -0
  54. package/dist/tools/helpers/finding-window.js +64 -0
  55. package/dist/tools/helpers/health-delta.d.ts +86 -0
  56. package/dist/tools/helpers/health-delta.js +239 -0
  57. package/dist/tools/helpers/investigation-schemas.d.ts +93 -0
  58. package/dist/tools/helpers/investigation-schemas.js +48 -0
  59. package/dist/tools/helpers/library-imports.d.ts +57 -0
  60. package/dist/tools/helpers/library-imports.js +151 -0
  61. package/dist/tools/helpers/load-source-files.d.ts +30 -0
  62. package/dist/tools/helpers/load-source-files.js +34 -0
  63. package/dist/tools/helpers/output-contract.d.ts +32 -0
  64. package/dist/tools/helpers/output-contract.js +32 -0
  65. package/dist/tools/helpers/platform-root-resolver.d.ts +55 -25
  66. package/dist/tools/helpers/platform-root-resolver.js +75 -48
  67. package/dist/tools/helpers/process-output.d.ts +19 -0
  68. package/dist/tools/helpers/process-output.js +31 -0
  69. package/dist/tools/helpers/project-cache.d.ts +11 -4
  70. package/dist/tools/helpers/project-cache.js +22 -4
  71. package/dist/tools/helpers/project-decorators.d.ts +14 -0
  72. package/dist/tools/helpers/project-decorators.js +22 -0
  73. package/dist/tools/helpers/rule-matcher.js +5 -0
  74. package/dist/tools/helpers/rule-runner.d.ts +9 -4
  75. package/dist/tools/helpers/rule-runner.js +28 -14
  76. package/dist/tools/helpers/scan-cache.d.ts +22 -0
  77. package/dist/tools/helpers/scan-cache.js +34 -0
  78. package/dist/tools/helpers/scan-plan.d.ts +5 -2
  79. package/dist/tools/helpers/scan-plan.js +18 -3
  80. package/dist/tools/helpers/scope-paths.d.ts +17 -0
  81. package/dist/tools/helpers/scope-paths.js +32 -0
  82. package/dist/tools/helpers/tool-context.d.ts +60 -0
  83. package/dist/tools/helpers/tool-context.js +82 -0
  84. package/dist/tools/helpers/transform-safety.d.ts +40 -0
  85. package/dist/tools/helpers/transform-safety.js +87 -0
  86. package/dist/tools/helpers/validation-output.d.ts +53 -0
  87. package/dist/tools/helpers/validation-output.js +48 -0
  88. package/dist/tools/inspect-form-group.d.ts +232 -1
  89. package/dist/tools/inspect-form-group.js +120 -2
  90. package/dist/tools/inspect-i18n.d.ts +382 -1
  91. package/dist/tools/inspect-i18n.js +199 -2
  92. package/dist/tools/inspect-template.d.ts +232 -1
  93. package/dist/tools/inspect-template.js +160 -2
  94. package/dist/tools/learn-patterns.d.ts +122 -1
  95. package/dist/tools/learn-patterns.js +97 -2
  96. package/dist/tools/list-imports.d.ts +111 -10
  97. package/dist/tools/list-imports.js +110 -7
  98. package/dist/tools/orchestrate-migration.d.ts +128 -5
  99. package/dist/tools/orchestrate-migration.js +135 -13
  100. package/dist/tools/parse-stack-trace.d.ts +56 -1
  101. package/dist/tools/parse-stack-trace.js +34 -0
  102. package/dist/tools/plan-migration.d.ts +330 -1
  103. package/dist/tools/plan-migration.js +154 -3
  104. package/dist/tools/resolve-type.d.ts +39 -1
  105. package/dist/tools/resolve-type.js +31 -2
  106. package/dist/tools/review-feedback.d.ts +206 -11
  107. package/dist/tools/review-feedback.js +132 -51
  108. package/dist/tools/rollback-changes.d.ts +79 -2
  109. package/dist/tools/rollback-changes.js +66 -14
  110. package/dist/tools/run-angular-cli.d.ts +45 -2
  111. package/dist/tools/run-angular-cli.js +67 -7
  112. package/dist/tools/run-build.d.ts +114 -2
  113. package/dist/tools/run-build.js +117 -8
  114. package/dist/tools/run-schematic.d.ts +70 -2
  115. package/dist/tools/run-schematic.js +104 -10
  116. package/dist/tools/scan-all.d.ts +19 -11
  117. package/dist/tools/scan-all.js +139 -131
  118. package/dist/tools/scan-angular.d.ts +19 -10
  119. package/dist/tools/scan-angular.js +51 -23
  120. package/dist/tools/scan-architecture.d.ts +17 -10
  121. package/dist/tools/scan-architecture.js +93 -31
  122. package/dist/tools/scan-solid.d.ts +19 -10
  123. package/dist/tools/scan-solid.js +51 -23
  124. package/dist/tools/search-codebase.d.ts +82 -1
  125. package/dist/tools/search-codebase.js +55 -2
  126. package/dist/tools/server-status.d.ts +279 -5
  127. package/dist/tools/server-status.js +179 -5
  128. package/dist/tools/suggest-improvements.d.ts +97 -5
  129. package/dist/tools/suggest-improvements.js +80 -44
  130. package/dist/tools/trace-output-flow.d.ts +682 -2
  131. package/dist/tools/trace-output-flow.js +375 -15
  132. package/dist/tools/transform-code-batch.d.ts +3 -0
  133. package/dist/tools/transform-code-batch.js +10 -5
  134. package/dist/tools/transform-code.d.ts +335 -12
  135. package/dist/tools/transform-code.js +649 -608
  136. package/dist/tools/validate-before-transform.d.ts +116 -2
  137. package/dist/tools/validate-before-transform.js +55 -2
  138. package/dist/tools/validate-project-compatibility.d.ts +64 -2
  139. package/dist/tools/validate-project-compatibility.js +67 -4
  140. package/dist/tools/validate-transformation.d.ts +220 -2
  141. package/dist/tools/validate-transformation.js +113 -15
  142. package/dist/tools/verify-citations.d.ts +181 -0
  143. package/dist/tools/verify-citations.js +218 -0
  144. package/dist/types.d.ts +38 -1
  145. package/dist/utils/format-tool-response.d.ts +22 -59
  146. package/dist/utils/format-tool-response.js +25 -134
  147. package/package.json +30 -13
  148. package/dist/cli.d.ts.map +0 -1
  149. package/dist/cli.js.map +0 -1
  150. package/dist/core/project-analyzer.d.ts.map +0 -1
  151. package/dist/core/project-analyzer.js.map +0 -1
  152. package/dist/index.d.ts.map +0 -1
  153. package/dist/index.js.map +0 -1
  154. package/dist/mcp-watcher.d.ts.map +0 -1
  155. package/dist/mcp-watcher.js.map +0 -1
  156. package/dist/server/json-rpc-handler.d.ts +0 -98
  157. package/dist/server/json-rpc-handler.d.ts.map +0 -1
  158. package/dist/server/json-rpc-handler.js +0 -301
  159. package/dist/server/json-rpc-handler.js.map +0 -1
  160. package/dist/server/mcp-server.d.ts.map +0 -1
  161. package/dist/server/mcp-server.js.map +0 -1
  162. package/dist/server/stdio-guard.d.ts.map +0 -1
  163. package/dist/server/stdio-guard.js.map +0 -1
  164. package/dist/server/tool-registry.d.ts.map +0 -1
  165. package/dist/server/tool-registry.js.map +0 -1
  166. package/dist/streaming/progress-store.d.ts.map +0 -1
  167. package/dist/streaming/progress-store.js.map +0 -1
  168. package/dist/tools/analyze-build-impact.d.ts.map +0 -1
  169. package/dist/tools/analyze-build-impact.js.map +0 -1
  170. package/dist/tools/analyze-core-to-shared.d.ts.map +0 -1
  171. package/dist/tools/analyze-core-to-shared.js.map +0 -1
  172. package/dist/tools/analyze-parser-performance.d.ts.map +0 -1
  173. package/dist/tools/analyze-parser-performance.js.map +0 -1
  174. package/dist/tools/analyze-project.d.ts.map +0 -1
  175. package/dist/tools/analyze-project.js.map +0 -1
  176. package/dist/tools/check-incremental-compatibility.d.ts.map +0 -1
  177. package/dist/tools/check-incremental-compatibility.js.map +0 -1
  178. package/dist/tools/collect-feedback.d.ts.map +0 -1
  179. package/dist/tools/collect-feedback.js.map +0 -1
  180. package/dist/tools/extract-libraries.d.ts.map +0 -1
  181. package/dist/tools/extract-libraries.js.map +0 -1
  182. package/dist/tools/find-angular-symbol.d.ts.map +0 -1
  183. package/dist/tools/find-angular-symbol.js.map +0 -1
  184. package/dist/tools/find-component-hosts.d.ts.map +0 -1
  185. package/dist/tools/find-component-hosts.js.map +0 -1
  186. package/dist/tools/find-usages.d.ts.map +0 -1
  187. package/dist/tools/find-usages.js.map +0 -1
  188. package/dist/tools/get-bootstrap-execution.d.ts.map +0 -1
  189. package/dist/tools/get-bootstrap-execution.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/compact-output.d.ts.map +0 -1
  197. package/dist/tools/helpers/compact-output.js.map +0 -1
  198. package/dist/tools/helpers/feedback-analyzer.d.ts.map +0 -1
  199. package/dist/tools/helpers/feedback-analyzer.js.map +0 -1
  200. package/dist/tools/helpers/find-ts-config.d.ts.map +0 -1
  201. package/dist/tools/helpers/find-ts-config.js.map +0 -1
  202. package/dist/tools/helpers/platform-root-resolver.d.ts.map +0 -1
  203. package/dist/tools/helpers/platform-root-resolver.js.map +0 -1
  204. package/dist/tools/helpers/project-cache.d.ts.map +0 -1
  205. package/dist/tools/helpers/project-cache.js.map +0 -1
  206. package/dist/tools/helpers/rule-matcher.d.ts.map +0 -1
  207. package/dist/tools/helpers/rule-matcher.js.map +0 -1
  208. package/dist/tools/helpers/rule-runner.d.ts.map +0 -1
  209. package/dist/tools/helpers/rule-runner.js.map +0 -1
  210. package/dist/tools/helpers/scan-plan.d.ts.map +0 -1
  211. package/dist/tools/helpers/scan-plan.js.map +0 -1
  212. package/dist/tools/helpers/stack-frame-file-index.d.ts.map +0 -1
  213. package/dist/tools/helpers/stack-frame-file-index.js.map +0 -1
  214. package/dist/tools/helpers/suggestion-generator.d.ts.map +0 -1
  215. package/dist/tools/helpers/suggestion-generator.js.map +0 -1
  216. package/dist/tools/inspect-form-group.d.ts.map +0 -1
  217. package/dist/tools/inspect-form-group.js.map +0 -1
  218. package/dist/tools/inspect-i18n.d.ts.map +0 -1
  219. package/dist/tools/inspect-i18n.js.map +0 -1
  220. package/dist/tools/inspect-template.d.ts.map +0 -1
  221. package/dist/tools/inspect-template.js.map +0 -1
  222. package/dist/tools/learn-patterns.d.ts.map +0 -1
  223. package/dist/tools/learn-patterns.js.map +0 -1
  224. package/dist/tools/list-imports.d.ts.map +0 -1
  225. package/dist/tools/list-imports.js.map +0 -1
  226. package/dist/tools/orchestrate-migration.d.ts.map +0 -1
  227. package/dist/tools/orchestrate-migration.js.map +0 -1
  228. package/dist/tools/parse-stack-trace.d.ts.map +0 -1
  229. package/dist/tools/parse-stack-trace.js.map +0 -1
  230. package/dist/tools/plan-migration.d.ts.map +0 -1
  231. package/dist/tools/plan-migration.js.map +0 -1
  232. package/dist/tools/resolve-type.d.ts.map +0 -1
  233. package/dist/tools/resolve-type.js.map +0 -1
  234. package/dist/tools/review-feedback.d.ts.map +0 -1
  235. package/dist/tools/review-feedback.js.map +0 -1
  236. package/dist/tools/rollback-changes.d.ts.map +0 -1
  237. package/dist/tools/rollback-changes.js.map +0 -1
  238. package/dist/tools/run-angular-cli.d.ts.map +0 -1
  239. package/dist/tools/run-angular-cli.js.map +0 -1
  240. package/dist/tools/run-build.d.ts.map +0 -1
  241. package/dist/tools/run-build.js.map +0 -1
  242. package/dist/tools/run-schematic.d.ts.map +0 -1
  243. package/dist/tools/run-schematic.js.map +0 -1
  244. package/dist/tools/scan-all.d.ts.map +0 -1
  245. package/dist/tools/scan-all.js.map +0 -1
  246. package/dist/tools/scan-angular.d.ts.map +0 -1
  247. package/dist/tools/scan-angular.js.map +0 -1
  248. package/dist/tools/scan-architecture.d.ts.map +0 -1
  249. package/dist/tools/scan-architecture.js.map +0 -1
  250. package/dist/tools/scan-solid.d.ts.map +0 -1
  251. package/dist/tools/scan-solid.js.map +0 -1
  252. package/dist/tools/search-codebase.d.ts.map +0 -1
  253. package/dist/tools/search-codebase.js.map +0 -1
  254. package/dist/tools/server-status.d.ts.map +0 -1
  255. package/dist/tools/server-status.js.map +0 -1
  256. package/dist/tools/shared/scan-types.d.ts.map +0 -1
  257. package/dist/tools/shared/scan-types.js.map +0 -1
  258. package/dist/tools/suggest-improvements.d.ts.map +0 -1
  259. package/dist/tools/suggest-improvements.js.map +0 -1
  260. package/dist/tools/trace-output-flow.d.ts.map +0 -1
  261. package/dist/tools/trace-output-flow.js.map +0 -1
  262. package/dist/tools/transform-code-batch.d.ts.map +0 -1
  263. package/dist/tools/transform-code-batch.js.map +0 -1
  264. package/dist/tools/transform-code.d.ts.map +0 -1
  265. package/dist/tools/transform-code.js.map +0 -1
  266. package/dist/tools/validate-before-transform.d.ts.map +0 -1
  267. package/dist/tools/validate-before-transform.js.map +0 -1
  268. package/dist/tools/validate-project-compatibility.d.ts.map +0 -1
  269. package/dist/tools/validate-project-compatibility.js.map +0 -1
  270. package/dist/tools/validate-transformation.d.ts.map +0 -1
  271. package/dist/tools/validate-transformation.js.map +0 -1
  272. package/dist/types.d.ts.map +0 -1
  273. package/dist/types.js.map +0 -1
  274. package/dist/utils/format-tool-response.d.ts.map +0 -1
  275. package/dist/utils/format-tool-response.js.map +0 -1
@@ -2,7 +2,8 @@
2
2
  * @angular-modernizer/adapter-mcp - MCP Watcher
3
3
  *
4
4
  * Writes periodic status updates to mcp-server.log to help debug
5
- * hanging operations like analyze-project.
5
+ * hanging operations like analyze-project. The server starts it only when
6
+ * `ANGULAR_MODERNIZER_DEBUG` is set.
6
7
  */
7
8
  export interface WatcherState {
8
9
  startTime: Date;
@@ -103,6 +104,10 @@ declare class MCPWatcher {
103
104
  */
104
105
  private formatDuration;
105
106
  }
107
+ /** Environment variable that switches on the debug log and the watcher. */
108
+ export declare const DEBUG_ENV = "ANGULAR_MODERNIZER_DEBUG";
109
+ /** True when `ANGULAR_MODERNIZER_DEBUG` is set to anything but '', '0' or 'false'. */
110
+ export declare function isDebugEnabled(env?: NodeJS.ProcessEnv): boolean;
106
111
  /**
107
112
  * Initialize and start the MCP watcher
108
113
  */
@@ -2,7 +2,8 @@
2
2
  * @angular-modernizer/adapter-mcp - MCP Watcher
3
3
  *
4
4
  * Writes periodic status updates to mcp-server.log to help debug
5
- * hanging operations like analyze-project.
5
+ * hanging operations like analyze-project. The server starts it only when
6
+ * `ANGULAR_MODERNIZER_DEBUG` is set.
6
7
  */
7
8
  import { appendFileSync, writeFileSync } from 'node:fs';
8
9
  import { resolve } from 'node:path';
@@ -62,16 +63,9 @@ Platform: ${process.platform}
62
63
  }, this.intervalMs);
63
64
  // Diagnostics must never keep the process alive after stdin closes
64
65
  this.heartbeatInterval.unref();
65
- // Ensure cleanup on exit
66
+ // Ensure cleanup on exit. Signals end the process through the server's
67
+ // shutdown(), which stops the watcher; a handler here would exit first.
66
68
  process.on('beforeExit', () => this.stop());
67
- process.on('SIGINT', () => {
68
- this.stop();
69
- process.exit(0);
70
- });
71
- process.on('SIGTERM', () => {
72
- this.stop();
73
- process.exit(0);
74
- });
75
69
  }
76
70
  /**
77
71
  * Stop the heartbeat loop
@@ -350,6 +344,13 @@ Platform: ${process.platform}
350
344
  return `${(ms / 3600000).toFixed(1)}h`;
351
345
  }
352
346
  }
347
+ /** Environment variable that switches on the debug log and the watcher. */
348
+ export const DEBUG_ENV = 'ANGULAR_MODERNIZER_DEBUG';
349
+ /** True when `ANGULAR_MODERNIZER_DEBUG` is set to anything but '', '0' or 'false'. */
350
+ export function isDebugEnabled(env = process.env) {
351
+ const value = env[DEBUG_ENV]?.trim().toLowerCase();
352
+ return value !== undefined && value !== '' && value !== '0' && value !== 'false';
353
+ }
353
354
  // Singleton instance
354
355
  let watcherInstance = null;
355
356
  /**
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - Size-limited stdio transport
3
+ *
4
+ * The SDK stdio transport with an emergency brake: every outgoing response is
5
+ * measured, a `tools/call` result over the limit is replaced by a small
6
+ * `isError` result, and the sizes are kept for `server-status`.
7
+ */
8
+ import { type Readable, type Writable } from 'node:stream';
9
+ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
10
+ import { type JSONRPCMessage, type RequestId } from '@modelcontextprotocol/server';
11
+ /**
12
+ * Largest serialized response written to stdout, in bytes.
13
+ *
14
+ * Claude Code drops the stdio connection when a server writes more than 16 MB
15
+ * without a JSON-RPC message boundary ("wrote >16MB to stdout without a
16
+ * JSON-RPC message boundary"), which takes every tool of this server offline
17
+ * until a manual reconnect. 4 MB keeps a wide margin below that limit.
18
+ * Larger responses are replaced by a small error that names the tool.
19
+ */
20
+ export declare const MAX_RESPONSE_BYTES: number;
21
+ /** One response sent on stdout. */
22
+ export interface ResponseRecord {
23
+ id: string | number | null;
24
+ /** Tool behind a tools/call response. */
25
+ tool?: string;
26
+ /** Size of the response as produced, before any oversize replacement. */
27
+ bytes: number;
28
+ /** The response exceeded the limit and was replaced by an error. */
29
+ replaced: boolean;
30
+ at: string;
31
+ }
32
+ /** Response sizes since the server started, for `server-status`. */
33
+ export interface ResponseStats {
34
+ count: number;
35
+ totalBytes: number;
36
+ oversized: number;
37
+ last?: ResponseRecord;
38
+ largest?: ResponseRecord;
39
+ }
40
+ export interface LimitedStdioTransportOptions {
41
+ /** @default MAX_RESPONSE_BYTES */
42
+ maxResponseBytes?: number;
43
+ }
44
+ /**
45
+ * `StdioServerTransport` that measures each response in `send()`. The tool
46
+ * behind a request id is reported by the `tools/call` handler through
47
+ * `trackToolCall`, so the oversize error and the statistics can name it.
48
+ */
49
+ export declare class LimitedStdioTransport extends StdioServerTransport {
50
+ private readonly maxResponseBytes;
51
+ /** Tool name per pending tools/call request id. */
52
+ private readonly toolCalls;
53
+ private readonly responseStats;
54
+ constructor(stdin?: Readable, stdout?: Writable, options?: LimitedStdioTransportOptions);
55
+ /** Names the tool that answers request `id`. */
56
+ trackToolCall(id: RequestId, tool: string): void;
57
+ /** Sizes of the responses sent so far (copies, safe to hand out). */
58
+ getResponseStats(): ResponseStats;
59
+ send(message: JSONRPCMessage): Promise<void>;
60
+ /**
61
+ * Returns `message` when it serializes within the limit, otherwise a small
62
+ * replacement with the same id: an `isError` result for a tool call, a
63
+ * JSON-RPC error for anything else.
64
+ */
65
+ private withinLimit;
66
+ private recordResponse;
67
+ }
68
+ //# sourceMappingURL=limited-stdio-transport.d.ts.map
@@ -0,0 +1,115 @@
1
+ /**
2
+ * @angular-modernizer/adapter-mcp - Size-limited stdio transport
3
+ *
4
+ * The SDK stdio transport with an emergency brake: every outgoing response is
5
+ * measured, a `tools/call` result over the limit is replaced by a small
6
+ * `isError` result, and the sizes are kept for `server-status`.
7
+ */
8
+ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
9
+ /**
10
+ * Largest serialized response written to stdout, in bytes.
11
+ *
12
+ * Claude Code drops the stdio connection when a server writes more than 16 MB
13
+ * without a JSON-RPC message boundary ("wrote >16MB to stdout without a
14
+ * JSON-RPC message boundary"), which takes every tool of this server offline
15
+ * until a manual reconnect. 4 MB keeps a wide margin below that limit.
16
+ * Larger responses are replaced by a small error that names the tool.
17
+ */
18
+ export const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
19
+ function isResponse(message) {
20
+ return 'id' in message && ('result' in message || 'error' in message);
21
+ }
22
+ /**
23
+ * `StdioServerTransport` that measures each response in `send()`. The tool
24
+ * behind a request id is reported by the `tools/call` handler through
25
+ * `trackToolCall`, so the oversize error and the statistics can name it.
26
+ */
27
+ export class LimitedStdioTransport extends StdioServerTransport {
28
+ maxResponseBytes;
29
+ /** Tool name per pending tools/call request id. */
30
+ toolCalls = new Map();
31
+ responseStats = { count: 0, totalBytes: 0, oversized: 0 };
32
+ constructor(stdin, stdout, options = {}) {
33
+ super(stdin, stdout);
34
+ this.maxResponseBytes = options.maxResponseBytes ?? MAX_RESPONSE_BYTES;
35
+ }
36
+ /** Names the tool that answers request `id`. */
37
+ trackToolCall(id, tool) {
38
+ this.toolCalls.set(id, tool);
39
+ }
40
+ /** Sizes of the responses sent so far (copies, safe to hand out). */
41
+ getResponseStats() {
42
+ return { ...this.responseStats };
43
+ }
44
+ send(message) {
45
+ if (!isResponse(message)) {
46
+ return super.send(message);
47
+ }
48
+ const tool = this.toolCalls.get(message.id);
49
+ this.toolCalls.delete(message.id);
50
+ return super.send(this.withinLimit(message, tool));
51
+ }
52
+ /**
53
+ * Returns `message` when it serializes within the limit, otherwise a small
54
+ * replacement with the same id: an `isError` result for a tool call, a
55
+ * JSON-RPC error for anything else.
56
+ */
57
+ withinLimit(message, tool) {
58
+ let bytes;
59
+ try {
60
+ bytes = Buffer.byteLength(JSON.stringify(message) + '\n', 'utf8');
61
+ if (bytes <= this.maxResponseBytes) {
62
+ this.recordResponse(message.id, tool, bytes, false);
63
+ return message;
64
+ }
65
+ }
66
+ catch (error) {
67
+ if (!(error instanceof RangeError)) {
68
+ throw error;
69
+ }
70
+ bytes = Number.POSITIVE_INFINITY;
71
+ }
72
+ this.recordResponse(message.id, tool, bytes, true);
73
+ const size = Number.isFinite(bytes)
74
+ ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
75
+ : 'too large to serialize';
76
+ const limit = `${this.maxResponseBytes / (1024 * 1024)} MB`;
77
+ const text = `Response of tool '${tool ?? 'unknown'}' is ${size}, over the ${limit} limit, and was dropped ` +
78
+ 'to keep the MCP connection alive. Narrow the request: use summaryOnly or a lower maxNodes ' +
79
+ 'where the tool supports it, or a smaller scope, depth or maxResults.';
80
+ if (tool === undefined) {
81
+ return { jsonrpc: '2.0', id: message.id, error: { code: -32603, message: text } };
82
+ }
83
+ // The 2026-07-28 era adds resultType and _meta to every result; the
84
+ // replacement keeps them so it stays a valid result in that era
85
+ const { resultType, _meta } = message.result ?? {};
86
+ return {
87
+ jsonrpc: '2.0',
88
+ id: message.id,
89
+ result: {
90
+ content: [{ type: 'text', text }],
91
+ isError: true,
92
+ ...(resultType === undefined ? {} : { resultType }),
93
+ ...(_meta === undefined ? {} : { _meta }),
94
+ },
95
+ };
96
+ }
97
+ recordResponse(id, tool, bytes, replaced) {
98
+ const record = {
99
+ id,
100
+ ...(tool === undefined ? {} : { tool }),
101
+ bytes,
102
+ replaced,
103
+ at: new Date().toISOString(),
104
+ };
105
+ const stats = this.responseStats;
106
+ stats.count++;
107
+ stats.totalBytes += Number.isFinite(bytes) ? bytes : 0;
108
+ stats.oversized += replaced ? 1 : 0;
109
+ stats.last = record;
110
+ if (stats.largest === undefined || bytes > stats.largest.bytes) {
111
+ stats.largest = record;
112
+ }
113
+ }
114
+ }
115
+ //# sourceMappingURL=limited-stdio-transport.js.map
@@ -1,16 +1,20 @@
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 { type ProtocolInfo } from './sdk-server.js';
9
+ import { type ResponseStats } from './limited-stdio-transport.js';
7
10
  import { type MCPTool, type MCPServerConfig } from '../types.js';
8
- import { type ResponseStats } from './json-rpc-handler.js';
9
11
  /** Runtime figures for the `server-status` tool. */
10
12
  export interface ServerRuntimeStats {
11
13
  startedAt: string;
12
14
  toolCount: number;
13
15
  responses: ResponseStats;
16
+ /** Era and protocol revision of the connection, once a client spoke. */
17
+ protocol: ProtocolInfo;
14
18
  }
15
19
  /**
16
20
  * Main MCP server class that handles the complete MCP protocol lifecycle.
@@ -23,11 +27,11 @@ export interface ServerRuntimeStats {
23
27
  */
24
28
  export declare class MCPServer {
25
29
  private readonly registry;
26
- private readonly handler;
27
30
  private readonly config;
31
+ private readonly protocol;
32
+ private transport;
33
+ private handle;
28
34
  private running;
29
- /** Accumulates incomplete JSON-RPC lines across stdin data events (BUG-6). */
30
- private inputBuffer;
31
35
  private shuttingDown;
32
36
  private parentWatch;
33
37
  private startedAt;
@@ -64,7 +68,8 @@ export declare class MCPServer {
64
68
  */
65
69
  getRuntimeStats(): ServerRuntimeStats;
66
70
  /**
67
- * Ends the process once: stops the watcher, flushes stdout/stderr and
71
+ * Ends the process once: closes the SDK connection (requests in flight are
72
+ * aborted, not answered), stops the watcher, flushes stdout/stderr and
68
73
  * exits. A dead pipe must not block the exit, so the flush is capped.
69
74
  */
70
75
  private shutdown;
@@ -78,13 +83,6 @@ export declare class MCPServer {
78
83
  * Get all registered tools as a map.
79
84
  */
80
85
  getToolsMap(): Map<string, MCPTool>;
81
- /**
82
- * Handle incoming data from stdin.
83
- * Accumulates chunks in a buffer and processes only complete newline-terminated
84
- * JSON-RPC lines. The remainder of an incomplete line is carried forward to the
85
- * next data event (BUG-6).
86
- */
87
- private handleInput;
88
86
  /**
89
87
  * Log a message based on configured log level.
90
88
  */
@@ -1,23 +1,20 @@
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
  }
22
19
  /** Longest wait for stdout/stderr to flush before a shutdown exits anyway. */
23
20
  const SHUTDOWN_FLUSH_TIMEOUT_MS = 1000;
@@ -32,11 +29,11 @@ const SHUTDOWN_FLUSH_TIMEOUT_MS = 1000;
32
29
  */
33
30
  export class MCPServer {
34
31
  registry;
35
- handler;
36
32
  config;
33
+ protocol = {};
34
+ transport;
35
+ handle;
37
36
  running = false;
38
- /** Accumulates incomplete JSON-RPC lines across stdin data events (BUG-6). */
39
- inputBuffer = '';
40
37
  shuttingDown = false;
41
38
  parentWatch;
42
39
  startedAt;
@@ -50,7 +47,6 @@ export class MCPServer {
50
47
  ...config,
51
48
  };
52
49
  this.registry = new ToolRegistry();
53
- this.handler = new JsonRpcHandler(this.registry);
54
50
  }
55
51
  /**
56
52
  * Register an MCP tool with the server.
@@ -69,20 +65,22 @@ export class MCPServer {
69
65
  this.running = true;
70
66
  this.startedAt = new Date();
71
67
  this.log('info', 'MCP server starting...');
72
- // Start MCP Watcher for debugging (3 second heartbeat, health check on port 9999)
73
- startMCPWatcher('./mcp-server.log', 3000, 9999);
74
- this.log('info', 'MCP Watcher started (heartbeat: 3s, health check: http://localhost:9999)');
75
- debugLog('MCP start() called, setting up stdio handlers');
76
- // Set up stdio handlers
77
- process.stdin.setEncoding('utf8');
78
- debugLog('MCP stdin encoding set to utf8');
79
- process.stdin.on('data', (chunk) => {
80
- debugLog(`MCP stdin data event - chunk length: ${chunk.length}, first 200 chars: ${chunk.substring(0, 200)}`);
81
- this.handleInput(chunk).catch((error) => {
82
- this.log('error', 'Error handling input:', error);
83
- });
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),
84
82
  });
85
- debugLog('MCP stdin data handler registered');
83
+ debugLog('MCP serveStdio started');
86
84
  process.stdin.on('end', () => this.shutdown('stdin ended'));
87
85
  process.stdin.on('close', () => this.shutdown('stdin closed'));
88
86
  process.stdin.on('error', (error) => this.shutdown(`stdin error: ${error.message}`));
@@ -100,6 +98,9 @@ export class MCPServer {
100
98
  */
101
99
  stop() {
102
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');
@@ -126,11 +127,17 @@ export class MCPServer {
126
127
  return {
127
128
  startedAt: (this.startedAt ?? new Date()).toISOString(),
128
129
  toolCount: this.registry.getStats().totalTools,
129
- responses: this.handler.getResponseStats(),
130
+ responses: this.transport?.getResponseStats() ?? {
131
+ count: 0,
132
+ totalBytes: 0,
133
+ oversized: 0,
134
+ },
135
+ protocol: { ...this.protocol },
130
136
  };
131
137
  }
132
138
  /**
133
- * Ends the process once: stops the watcher, flushes stdout/stderr and
139
+ * Ends the process once: closes the SDK connection (requests in flight are
140
+ * aborted, not answered), stops the watcher, flushes stdout/stderr and
134
141
  * exits. A dead pipe must not block the exit, so the flush is capped.
135
142
  */
136
143
  shutdown(reason) {
@@ -140,6 +147,9 @@ export class MCPServer {
140
147
  this.shuttingDown = true;
141
148
  this.log('info', `MCP server shutting down (${reason})`);
142
149
  this.stopParentWatch();
150
+ this.handle?.close().catch(() => {
151
+ // The transport may already be gone (EPIPE, stdin closed)
152
+ });
143
153
  stopMCPWatcher();
144
154
  this.running = false;
145
155
  setTimeout(() => process.exit(0), SHUTDOWN_FLUSH_TIMEOUT_MS).unref();
@@ -178,50 +188,6 @@ export class MCPServer {
178
188
  getToolsMap() {
179
189
  return this.registry.getAllToolsMap();
180
190
  }
181
- /**
182
- * Handle incoming data from stdin.
183
- * Accumulates chunks in a buffer and processes only complete newline-terminated
184
- * JSON-RPC lines. The remainder of an incomplete line is carried forward to the
185
- * next data event (BUG-6).
186
- */
187
- async handleInput(chunk) {
188
- this.inputBuffer += chunk;
189
- // Split on newlines; the last element is either empty (complete line) or an
190
- // incomplete fragment that must be held back until more data arrives.
191
- const lines = this.inputBuffer.split('\n');
192
- // Keep the trailing incomplete fragment in the buffer.
193
- this.inputBuffer = lines.pop() ?? '';
194
- for (const line of lines) {
195
- if (line.trim()) {
196
- try {
197
- debugLog(`MCP handleInput: Received line (first 150 chars): ${line.trim().substring(0, 150)}`);
198
- const response = await this.handler.processMessage(line.trim());
199
- debugLog(`MCP handleInput: processMessage returned ${response ? `response with id=${response.id}` : 'NULL'}`);
200
- if (response) {
201
- debugLog(`MCP handleInput: Calling sendResponse with id=${response.id}`);
202
- await this.handler.sendResponse(response);
203
- }
204
- else {
205
- debugLog('MCP handleInput: No response to send (processMessage returned null)');
206
- }
207
- }
208
- catch (error) {
209
- this.log('error', 'Error processing message:', error);
210
- // Send error response
211
- const errorResponse = {
212
- jsonrpc: '2.0',
213
- id: null,
214
- error: {
215
- code: -32603,
216
- message: 'Internal error',
217
- data: error instanceof Error ? error.message : String(error),
218
- },
219
- };
220
- await this.handler.sendResponse(errorResponse);
221
- }
222
- }
223
- }
224
- }
225
191
  /**
226
192
  * Log a message based on configured log level.
227
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