@angular-modernizer/adapter-mcp 0.3.0 → 1.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.
- package/README.md +181 -282
- package/dist/cli.js +21 -13
- package/dist/core/project-analyzer.d.ts +3 -12
- package/dist/core/project-analyzer.js +3 -12
- package/dist/index.d.ts +122 -6
- package/dist/index.js +49 -5
- package/dist/mcp-watcher.d.ts +32 -7
- package/dist/mcp-watcher.js +16 -15
- package/dist/scan-host/scan-host.d.ts +119 -0
- package/dist/scan-host/scan-host.js +376 -0
- package/dist/scan-host/scan-protocol.d.ts +35 -0
- package/dist/scan-host/scan-protocol.js +6 -0
- package/dist/scan-host/scan-worker.d.ts +14 -0
- package/dist/scan-host/scan-worker.js +48 -0
- package/dist/server/limited-stdio-transport.d.ts +75 -0
- package/dist/server/limited-stdio-transport.js +115 -0
- package/dist/server/mcp-server.d.ts +20 -18
- package/dist/server/mcp-server.js +42 -79
- package/dist/server/package-version.d.ts +16 -0
- package/dist/server/package-version.js +37 -0
- package/dist/server/sdk-server.d.ts +71 -0
- package/dist/server/sdk-server.js +113 -0
- package/dist/server/tool-registry.d.ts +6 -9
- package/dist/server/tool-registry.js +6 -12
- package/dist/streaming/progress-store.d.ts +22 -5
- package/dist/streaming/progress-store.js +9 -5
- package/dist/tools/analyze-build-impact.d.ts +276 -35
- package/dist/tools/analyze-build-impact.js +175 -28
- package/dist/tools/analyze-core-to-shared.d.ts +176 -16
- package/dist/tools/analyze-core-to-shared.js +124 -19
- package/dist/tools/analyze-parser-performance.d.ts +209 -15
- package/dist/tools/analyze-parser-performance.js +119 -56
- package/dist/tools/analyze-project.d.ts +349 -17
- package/dist/tools/analyze-project.js +282 -97
- package/dist/tools/check-incremental-compatibility.d.ts +74 -12
- package/dist/tools/check-incremental-compatibility.js +69 -10
- package/dist/tools/collect-feedback.d.ts +225 -21
- package/dist/tools/collect-feedback.js +199 -118
- package/dist/tools/compare-health.d.ts +413 -0
- package/dist/tools/compare-health.js +479 -0
- package/dist/tools/extract-libraries.d.ts +200 -24
- package/dist/tools/extract-libraries.js +131 -27
- package/dist/tools/find-angular-symbol.d.ts +92 -24
- package/dist/tools/find-angular-symbol.js +70 -20
- package/dist/tools/find-component-hosts.d.ts +603 -27
- package/dist/tools/find-component-hosts.js +223 -19
- package/dist/tools/find-usages.d.ts +102 -22
- package/dist/tools/find-usages.js +81 -21
- package/dist/tools/get-bootstrap-execution.d.ts +183 -25
- package/dist/tools/get-bootstrap-execution.js +109 -25
- package/dist/tools/get-call-graph.d.ts +127 -12
- package/dist/tools/get-call-graph.js +84 -19
- package/dist/tools/get-operation-progress-tool.d.ts +126 -8
- package/dist/tools/get-operation-progress-tool.js +124 -12
- package/dist/tools/get-operation-progress.d.ts +27 -1
- package/dist/tools/get-operation-progress.js +5 -5
- package/dist/tools/helpers/analysis-output.d.ts +182 -0
- package/dist/tools/helpers/analysis-output.js +165 -0
- package/dist/tools/helpers/batch-kernel.d.ts +14 -0
- package/dist/tools/helpers/batch-kernel.js +12 -0
- package/dist/tools/helpers/build-schemas.d.ts +36 -0
- package/dist/tools/helpers/build-schemas.js +23 -0
- package/dist/tools/helpers/citation-file-source.d.ts +10 -0
- package/dist/tools/helpers/citation-file-source.js +82 -0
- package/dist/tools/helpers/compact-output.d.ts +2 -1
- package/dist/tools/helpers/compact-output.js +2 -1
- package/dist/tools/helpers/finding-window.d.ts +43 -0
- package/dist/tools/helpers/finding-window.js +64 -0
- package/dist/tools/helpers/health-delta.d.ts +99 -0
- package/dist/tools/helpers/health-delta.js +236 -0
- package/dist/tools/helpers/investigation-schemas.d.ts +93 -0
- package/dist/tools/helpers/investigation-schemas.js +48 -0
- package/dist/tools/helpers/library-imports.d.ts +57 -0
- package/dist/tools/helpers/library-imports.js +151 -0
- package/dist/tools/helpers/load-source-files.d.ts +30 -0
- package/dist/tools/helpers/load-source-files.js +34 -0
- package/dist/tools/helpers/output-contract.d.ts +32 -0
- package/dist/tools/helpers/output-contract.js +32 -0
- package/dist/tools/helpers/platform-root-resolver.d.ts +55 -25
- package/dist/tools/helpers/platform-root-resolver.js +75 -48
- package/dist/tools/helpers/process-output.d.ts +19 -0
- package/dist/tools/helpers/process-output.js +31 -0
- package/dist/tools/helpers/project-cache.d.ts +60 -37
- package/dist/tools/helpers/project-cache.js +54 -37
- package/dist/tools/helpers/project-decorators.d.ts +14 -0
- package/dist/tools/helpers/project-decorators.js +22 -0
- package/dist/tools/helpers/rule-matcher.js +5 -0
- package/dist/tools/helpers/rule-runner.d.ts +25 -13
- package/dist/tools/helpers/rule-runner.js +45 -24
- package/dist/tools/helpers/scan-cache.d.ts +22 -0
- package/dist/tools/helpers/scan-cache.js +34 -0
- package/dist/tools/helpers/scan-engine.d.ts +107 -0
- package/dist/tools/helpers/scan-engine.js +197 -0
- package/dist/tools/helpers/scan-plan.d.ts +5 -2
- package/dist/tools/helpers/scan-plan.js +18 -3
- package/dist/tools/helpers/scope-paths.d.ts +17 -0
- package/dist/tools/helpers/scope-paths.js +32 -0
- package/dist/tools/helpers/suggestion-generator.d.ts +9 -13
- package/dist/tools/helpers/suggestion-generator.js +0 -12
- package/dist/tools/helpers/tool-cache.d.ts +11 -0
- package/dist/tools/helpers/tool-cache.js +15 -0
- package/dist/tools/helpers/tool-context.d.ts +63 -0
- package/dist/tools/helpers/tool-context.js +79 -0
- package/dist/tools/helpers/transform-safety.d.ts +40 -0
- package/dist/tools/helpers/transform-safety.js +87 -0
- package/dist/tools/helpers/validation-output.d.ts +53 -0
- package/dist/tools/helpers/validation-output.js +48 -0
- package/dist/tools/inspect-form-group.d.ts +262 -24
- package/dist/tools/inspect-form-group.js +134 -13
- package/dist/tools/inspect-i18n.d.ts +410 -23
- package/dist/tools/inspect-i18n.js +213 -13
- package/dist/tools/inspect-template.d.ts +260 -22
- package/dist/tools/inspect-template.js +174 -13
- package/dist/tools/learn-patterns.d.ts +210 -13
- package/dist/tools/learn-patterns.js +113 -12
- package/dist/tools/list-imports.d.ts +152 -34
- package/dist/tools/list-imports.js +124 -18
- package/dist/tools/orchestrate-migration.d.ts +159 -14
- package/dist/tools/orchestrate-migration.js +147 -20
- package/dist/tools/parse-stack-trace.d.ts +78 -21
- package/dist/tools/parse-stack-trace.js +44 -7
- package/dist/tools/plan-migration.d.ts +395 -26
- package/dist/tools/plan-migration.js +173 -22
- package/dist/tools/resolve-type.d.ts +57 -9
- package/dist/tools/resolve-type.js +49 -12
- package/dist/tools/review-feedback.d.ts +214 -16
- package/dist/tools/review-feedback.js +142 -57
- package/dist/tools/rollback-changes.d.ts +88 -7
- package/dist/tools/rollback-changes.js +74 -19
- package/dist/tools/run-angular-cli.d.ts +57 -12
- package/dist/tools/run-angular-cli.js +76 -13
- package/dist/tools/run-build.d.ts +127 -13
- package/dist/tools/run-build.js +128 -16
- package/dist/tools/run-schematic.d.ts +82 -12
- package/dist/tools/run-schematic.js +115 -18
- package/dist/tools/scan-all.d.ts +88 -23
- package/dist/tools/scan-all.js +161 -220
- package/dist/tools/scan-angular.d.ts +60 -19
- package/dist/tools/scan-angular.js +100 -141
- package/dist/tools/scan-architecture.d.ts +92 -24
- package/dist/tools/scan-architecture.js +268 -211
- package/dist/tools/scan-solid.d.ts +59 -19
- package/dist/tools/scan-solid.js +98 -139
- package/dist/tools/search-codebase.d.ts +110 -23
- package/dist/tools/search-codebase.js +67 -11
- package/dist/tools/server-status.d.ts +392 -26
- package/dist/tools/server-status.js +260 -27
- package/dist/tools/suggest-improvements.d.ts +105 -10
- package/dist/tools/suggest-improvements.js +91 -51
- package/dist/tools/trace-output-flow.d.ts +713 -26
- package/dist/tools/trace-output-flow.js +396 -33
- package/dist/tools/transform-code-batch.d.ts +3 -0
- package/dist/tools/transform-code-batch.js +10 -5
- package/dist/tools/transform-code.d.ts +402 -18
- package/dist/tools/transform-code.js +708 -649
- package/dist/tools/validate-before-transform.d.ts +136 -7
- package/dist/tools/validate-before-transform.js +65 -9
- package/dist/tools/validate-project-compatibility.d.ts +82 -15
- package/dist/tools/validate-project-compatibility.js +84 -15
- package/dist/tools/validate-transformation.d.ts +243 -8
- package/dist/tools/validate-transformation.js +127 -23
- package/dist/tools/verify-citations.d.ts +202 -0
- package/dist/tools/verify-citations.js +221 -0
- package/dist/types.d.ts +78 -11
- package/dist/types.js +0 -5
- package/dist/utils/format-tool-response.d.ts +22 -59
- package/dist/utils/format-tool-response.js +25 -134
- package/package.json +31 -20
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/core/project-analyzer.d.ts.map +0 -1
- package/dist/core/project-analyzer.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/mcp-watcher.d.ts.map +0 -1
- package/dist/mcp-watcher.js.map +0 -1
- package/dist/server/json-rpc-handler.d.ts +0 -98
- package/dist/server/json-rpc-handler.d.ts.map +0 -1
- package/dist/server/json-rpc-handler.js +0 -301
- package/dist/server/json-rpc-handler.js.map +0 -1
- package/dist/server/mcp-server.d.ts.map +0 -1
- package/dist/server/mcp-server.js.map +0 -1
- package/dist/server/stdio-guard.d.ts.map +0 -1
- package/dist/server/stdio-guard.js.map +0 -1
- package/dist/server/tool-registry.d.ts.map +0 -1
- package/dist/server/tool-registry.js.map +0 -1
- package/dist/streaming/progress-store.d.ts.map +0 -1
- package/dist/streaming/progress-store.js.map +0 -1
- package/dist/tools/analyze-build-impact.d.ts.map +0 -1
- package/dist/tools/analyze-build-impact.js.map +0 -1
- package/dist/tools/analyze-core-to-shared.d.ts.map +0 -1
- package/dist/tools/analyze-core-to-shared.js.map +0 -1
- package/dist/tools/analyze-parser-performance.d.ts.map +0 -1
- package/dist/tools/analyze-parser-performance.js.map +0 -1
- package/dist/tools/analyze-project.d.ts.map +0 -1
- package/dist/tools/analyze-project.js.map +0 -1
- package/dist/tools/check-incremental-compatibility.d.ts.map +0 -1
- package/dist/tools/check-incremental-compatibility.js.map +0 -1
- package/dist/tools/collect-feedback.d.ts.map +0 -1
- package/dist/tools/collect-feedback.js.map +0 -1
- package/dist/tools/extract-libraries.d.ts.map +0 -1
- package/dist/tools/extract-libraries.js.map +0 -1
- package/dist/tools/find-angular-symbol.d.ts.map +0 -1
- package/dist/tools/find-angular-symbol.js.map +0 -1
- package/dist/tools/find-component-hosts.d.ts.map +0 -1
- package/dist/tools/find-component-hosts.js.map +0 -1
- package/dist/tools/find-usages.d.ts.map +0 -1
- package/dist/tools/find-usages.js.map +0 -1
- package/dist/tools/get-bootstrap-execution.d.ts.map +0 -1
- package/dist/tools/get-bootstrap-execution.js.map +0 -1
- package/dist/tools/get-call-graph.d.ts.map +0 -1
- package/dist/tools/get-call-graph.js.map +0 -1
- package/dist/tools/get-operation-progress-tool.d.ts.map +0 -1
- package/dist/tools/get-operation-progress-tool.js.map +0 -1
- package/dist/tools/get-operation-progress.d.ts.map +0 -1
- package/dist/tools/get-operation-progress.js.map +0 -1
- package/dist/tools/helpers/compact-output.d.ts.map +0 -1
- package/dist/tools/helpers/compact-output.js.map +0 -1
- package/dist/tools/helpers/feedback-analyzer.d.ts.map +0 -1
- package/dist/tools/helpers/feedback-analyzer.js.map +0 -1
- package/dist/tools/helpers/find-ts-config.d.ts.map +0 -1
- package/dist/tools/helpers/find-ts-config.js.map +0 -1
- package/dist/tools/helpers/platform-root-resolver.d.ts.map +0 -1
- package/dist/tools/helpers/platform-root-resolver.js.map +0 -1
- package/dist/tools/helpers/project-cache.d.ts.map +0 -1
- package/dist/tools/helpers/project-cache.js.map +0 -1
- package/dist/tools/helpers/rule-matcher.d.ts.map +0 -1
- package/dist/tools/helpers/rule-matcher.js.map +0 -1
- package/dist/tools/helpers/rule-runner.d.ts.map +0 -1
- package/dist/tools/helpers/rule-runner.js.map +0 -1
- package/dist/tools/helpers/scan-plan.d.ts.map +0 -1
- package/dist/tools/helpers/scan-plan.js.map +0 -1
- package/dist/tools/helpers/stack-frame-file-index.d.ts.map +0 -1
- package/dist/tools/helpers/stack-frame-file-index.js.map +0 -1
- package/dist/tools/helpers/suggestion-generator.d.ts.map +0 -1
- package/dist/tools/helpers/suggestion-generator.js.map +0 -1
- package/dist/tools/inspect-form-group.d.ts.map +0 -1
- package/dist/tools/inspect-form-group.js.map +0 -1
- package/dist/tools/inspect-i18n.d.ts.map +0 -1
- package/dist/tools/inspect-i18n.js.map +0 -1
- package/dist/tools/inspect-template.d.ts.map +0 -1
- package/dist/tools/inspect-template.js.map +0 -1
- package/dist/tools/learn-patterns.d.ts.map +0 -1
- package/dist/tools/learn-patterns.js.map +0 -1
- package/dist/tools/list-imports.d.ts.map +0 -1
- package/dist/tools/list-imports.js.map +0 -1
- package/dist/tools/orchestrate-migration.d.ts.map +0 -1
- package/dist/tools/orchestrate-migration.js.map +0 -1
- package/dist/tools/parse-stack-trace.d.ts.map +0 -1
- package/dist/tools/parse-stack-trace.js.map +0 -1
- package/dist/tools/plan-migration.d.ts.map +0 -1
- package/dist/tools/plan-migration.js.map +0 -1
- package/dist/tools/resolve-type.d.ts.map +0 -1
- package/dist/tools/resolve-type.js.map +0 -1
- package/dist/tools/review-feedback.d.ts.map +0 -1
- package/dist/tools/review-feedback.js.map +0 -1
- package/dist/tools/rollback-changes.d.ts.map +0 -1
- package/dist/tools/rollback-changes.js.map +0 -1
- package/dist/tools/run-angular-cli.d.ts.map +0 -1
- package/dist/tools/run-angular-cli.js.map +0 -1
- package/dist/tools/run-build.d.ts.map +0 -1
- package/dist/tools/run-build.js.map +0 -1
- package/dist/tools/run-schematic.d.ts.map +0 -1
- package/dist/tools/run-schematic.js.map +0 -1
- package/dist/tools/scan-all.d.ts.map +0 -1
- package/dist/tools/scan-all.js.map +0 -1
- package/dist/tools/scan-angular.d.ts.map +0 -1
- package/dist/tools/scan-angular.js.map +0 -1
- package/dist/tools/scan-architecture.d.ts.map +0 -1
- package/dist/tools/scan-architecture.js.map +0 -1
- package/dist/tools/scan-solid.d.ts.map +0 -1
- package/dist/tools/scan-solid.js.map +0 -1
- package/dist/tools/search-codebase.d.ts.map +0 -1
- package/dist/tools/search-codebase.js.map +0 -1
- package/dist/tools/server-status.d.ts.map +0 -1
- package/dist/tools/server-status.js.map +0 -1
- package/dist/tools/shared/scan-types.d.ts +0 -200
- package/dist/tools/shared/scan-types.d.ts.map +0 -1
- package/dist/tools/shared/scan-types.js +0 -7
- package/dist/tools/shared/scan-types.js.map +0 -1
- package/dist/tools/suggest-improvements.d.ts.map +0 -1
- package/dist/tools/suggest-improvements.js.map +0 -1
- package/dist/tools/trace-output-flow.d.ts.map +0 -1
- package/dist/tools/trace-output-flow.js.map +0 -1
- package/dist/tools/transform-code-batch.d.ts.map +0 -1
- package/dist/tools/transform-code-batch.js.map +0 -1
- package/dist/tools/transform-code.d.ts.map +0 -1
- package/dist/tools/transform-code.js.map +0 -1
- package/dist/tools/validate-before-transform.d.ts.map +0 -1
- package/dist/tools/validate-before-transform.js.map +0 -1
- package/dist/tools/validate-project-compatibility.d.ts.map +0 -1
- package/dist/tools/validate-project-compatibility.js.map +0 -1
- package/dist/tools/validate-transformation.d.ts.map +0 -1
- package/dist/tools/validate-transformation.js.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js.map +0 -1
- package/dist/utils/format-tool-response.d.ts.map +0 -1
- package/dist/utils/format-tool-response.js.map +0 -1
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @angular-modernizer/adapter-mcp - Scan worker host
|
|
3
|
+
*
|
|
4
|
+
* Runs the analysis part of a scan ({@link runScanEngine}) in a worker
|
|
5
|
+
* thread. The first type query of a scan builds the TypeScript program and
|
|
6
|
+
* type checker synchronously (large app: 2784 program files, 1.6 s in one
|
|
7
|
+
* block); on the main thread the server reads no stdin meanwhile, so a
|
|
8
|
+
* `notifications/cancelled` and every other request wait. In a worker the
|
|
9
|
+
* main thread keeps serving, and a cancel ends the worker with `terminate()`,
|
|
10
|
+
* which stops synchronous JavaScript too, the checker build included.
|
|
11
|
+
*
|
|
12
|
+
* One scan worker serves the scans one after the other, each with a new
|
|
13
|
+
* kernel; further scans wait in a queue (heap). The worker stays alive after
|
|
14
|
+
* a finished scan: a new isolate loads ts-morph, core and api in about 400 ms
|
|
15
|
+
* and runs the TypeScript code unoptimized, which made each scan on a small
|
|
16
|
+
* scope 1.5 to 3 s slower than on the main thread (large app). A cancel, an
|
|
17
|
+
* error or the heap limit ends the worker; the host then starts the next one,
|
|
18
|
+
* which loads the modules while it waits. The worker heap is limited to
|
|
19
|
+
* `--max-heap-mb`; it is not part of the main thread's `heapUsed`, which the
|
|
20
|
+
* project cache checks.
|
|
21
|
+
*/
|
|
22
|
+
import { Worker } from 'node:worker_threads';
|
|
23
|
+
import { runScanEngine, } from '../tools/helpers/scan-engine.js';
|
|
24
|
+
/** Command-line flag and environment variable of the scan worker switch. */
|
|
25
|
+
export const SCAN_WORKER_FLAG = {
|
|
26
|
+
flag: '--scan-worker',
|
|
27
|
+
env: 'ANGULAR_MODERNIZER_SCAN_WORKER',
|
|
28
|
+
};
|
|
29
|
+
const MAX_RUNNING = 1;
|
|
30
|
+
let settings = { enabled: false, maxHeapMb: 0 };
|
|
31
|
+
let standby;
|
|
32
|
+
const running = new Map();
|
|
33
|
+
const waiting = [];
|
|
34
|
+
let active = 0;
|
|
35
|
+
let started = 0;
|
|
36
|
+
let cancelled = 0;
|
|
37
|
+
let failed = 0;
|
|
38
|
+
/**
|
|
39
|
+
* Sets how scans run. The CLI turns the worker on, which also starts the
|
|
40
|
+
* waiting worker; without this call (Jest, library use) scans run in the
|
|
41
|
+
* calling thread.
|
|
42
|
+
*/
|
|
43
|
+
export function configureScanHost(next) {
|
|
44
|
+
settings = { ...settings, ...next };
|
|
45
|
+
stopStandby();
|
|
46
|
+
prepareStandby();
|
|
47
|
+
}
|
|
48
|
+
/** Ends the waiting worker (tests; the server ends with the process). */
|
|
49
|
+
export function stopStandby() {
|
|
50
|
+
if (standby !== undefined) {
|
|
51
|
+
void standby.worker.terminate();
|
|
52
|
+
standby = undefined;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Current settings. */
|
|
56
|
+
export function scanHostSettings() {
|
|
57
|
+
return settings;
|
|
58
|
+
}
|
|
59
|
+
/** State for server-status. */
|
|
60
|
+
export function describeScanHost() {
|
|
61
|
+
return {
|
|
62
|
+
enabled: settings.enabled,
|
|
63
|
+
maxHeapMB: settings.maxHeapMb,
|
|
64
|
+
standby: standby !== undefined && !standby.exited,
|
|
65
|
+
running: [...running.values()],
|
|
66
|
+
queued: waiting.length,
|
|
67
|
+
started,
|
|
68
|
+
cancelled,
|
|
69
|
+
failed,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Reads the scan worker switch from `--scan-worker` (`--scan-worker=0`,
|
|
74
|
+
* `--scan-worker 0`) or `ANGULAR_MODERNIZER_SCAN_WORKER`; the flag wins.
|
|
75
|
+
* Default on; `0`, `false`, `off` switch it off. Other values keep the
|
|
76
|
+
* default with a warning.
|
|
77
|
+
*/
|
|
78
|
+
export function parseScanWorkerSetting(argv, env) {
|
|
79
|
+
const prefix = `${SCAN_WORKER_FLAG.flag}=`;
|
|
80
|
+
const index = argv.findIndex((a) => a === SCAN_WORKER_FLAG.flag || a.startsWith(prefix));
|
|
81
|
+
let value;
|
|
82
|
+
let source = SCAN_WORKER_FLAG.env;
|
|
83
|
+
if (index >= 0) {
|
|
84
|
+
const arg = argv[index] ?? '';
|
|
85
|
+
value = arg === SCAN_WORKER_FLAG.flag ? argv[index + 1] : arg.slice(prefix.length);
|
|
86
|
+
source = SCAN_WORKER_FLAG.flag;
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
value = env[SCAN_WORKER_FLAG.env];
|
|
90
|
+
}
|
|
91
|
+
if (value === undefined) {
|
|
92
|
+
return { enabled: true, warnings: [] };
|
|
93
|
+
}
|
|
94
|
+
const normalized = value.trim().toLowerCase();
|
|
95
|
+
if (['1', 'true', 'on'].includes(normalized)) {
|
|
96
|
+
return { enabled: true, warnings: [] };
|
|
97
|
+
}
|
|
98
|
+
if (['0', 'false', 'off'].includes(normalized)) {
|
|
99
|
+
return { enabled: false, warnings: [] };
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
enabled: true,
|
|
103
|
+
warnings: [`${source}: expected 0 or 1, got "${value}"; scans run in a worker.`],
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Runs a scan in a worker when the host is enabled and there is something to
|
|
108
|
+
* analyze, otherwise in the calling thread. Both report through `sink`; a
|
|
109
|
+
* cancelled worker run resolves with `cancelled: true` and only the files the
|
|
110
|
+
* sink got before the cancel.
|
|
111
|
+
*/
|
|
112
|
+
export async function runScan(spec, sink, options = {}) {
|
|
113
|
+
if (!settings.enabled || spec.files.length === 0) {
|
|
114
|
+
return runScanEngine(spec, sink, { signal: options.signal });
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
return await runScanInWorker(spec, sink, {
|
|
118
|
+
signal: options.signal,
|
|
119
|
+
maxHeapMb: settings.maxHeapMb,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
prepareStandby();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Runs `spec` in a worker. Abort terminates the worker at once and resolves
|
|
128
|
+
* with `cancelled: true`; messages arriving after the abort are dropped. A
|
|
129
|
+
* worker that fails or exits without a result rejects. The call returns once
|
|
130
|
+
* the worker has exited, so the next queued scan never shares the memory
|
|
131
|
+
* with it.
|
|
132
|
+
*/
|
|
133
|
+
export async function runScanInWorker(spec, sink, options = {}) {
|
|
134
|
+
const { signal } = options;
|
|
135
|
+
if (!(await acquire(signal))) {
|
|
136
|
+
return { cancelled: true, ruleIds: [] };
|
|
137
|
+
}
|
|
138
|
+
let released = Promise.resolve();
|
|
139
|
+
try {
|
|
140
|
+
const run = startScan(spec, sink, options);
|
|
141
|
+
released = run.released;
|
|
142
|
+
return await run.result;
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
await released;
|
|
146
|
+
release();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function startScan(spec, sink, options) {
|
|
150
|
+
const { signal } = options;
|
|
151
|
+
const heapLimit = options.maxHeapMb ?? 0;
|
|
152
|
+
const script = workerScript(options.workerUrl);
|
|
153
|
+
const worker = takeWorker(script, heapLimit);
|
|
154
|
+
started++;
|
|
155
|
+
const info = {
|
|
156
|
+
threadId: worker.threadId,
|
|
157
|
+
tool: spec.tool,
|
|
158
|
+
startedAt: new Date().toISOString(),
|
|
159
|
+
files: spec.files.length,
|
|
160
|
+
filesDone: 0,
|
|
161
|
+
};
|
|
162
|
+
running.set(info.threadId, info);
|
|
163
|
+
let markReleased;
|
|
164
|
+
const released = new Promise((resolve) => {
|
|
165
|
+
markReleased = resolve;
|
|
166
|
+
});
|
|
167
|
+
const exited = new Promise((resolve) => {
|
|
168
|
+
worker.once('exit', () => resolve());
|
|
169
|
+
});
|
|
170
|
+
const result = new Promise((resolve, reject) => {
|
|
171
|
+
let ruleIds = [];
|
|
172
|
+
let settled = false;
|
|
173
|
+
/**
|
|
174
|
+
* Ends this scan. A finished scan hands the worker back for the next one;
|
|
175
|
+
* otherwise the worker is terminated and released once it has exited.
|
|
176
|
+
*/
|
|
177
|
+
const finish = (outcome, keepWorker = false) => {
|
|
178
|
+
if (settled) {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
settled = true;
|
|
182
|
+
signal?.removeEventListener('abort', onAbort);
|
|
183
|
+
worker.off('message', onMessage);
|
|
184
|
+
worker.off('error', onError);
|
|
185
|
+
worker.off('exit', onExit);
|
|
186
|
+
running.delete(info.threadId);
|
|
187
|
+
if (keepWorker) {
|
|
188
|
+
keepForNextScan(worker, script, heapLimit);
|
|
189
|
+
markReleased();
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
void worker.terminate();
|
|
193
|
+
void exited.then(markReleased);
|
|
194
|
+
}
|
|
195
|
+
outcome();
|
|
196
|
+
};
|
|
197
|
+
const fail = (error) => {
|
|
198
|
+
if (!settled) {
|
|
199
|
+
failed++;
|
|
200
|
+
}
|
|
201
|
+
finish(() => reject(error));
|
|
202
|
+
};
|
|
203
|
+
const onAbort = () => {
|
|
204
|
+
if (!settled) {
|
|
205
|
+
cancelled++;
|
|
206
|
+
}
|
|
207
|
+
finish(() => resolve({ cancelled: true, ruleIds }));
|
|
208
|
+
};
|
|
209
|
+
const onMessage = (message) => {
|
|
210
|
+
if (settled) {
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
switch (message.type) {
|
|
215
|
+
case 'ready':
|
|
216
|
+
ruleIds = message.ruleIds;
|
|
217
|
+
info.heapUsedMB = toMB(message.heapUsed);
|
|
218
|
+
sink.ready?.(message.ruleIds);
|
|
219
|
+
return;
|
|
220
|
+
case 'file':
|
|
221
|
+
info.filesDone++;
|
|
222
|
+
if (message.heapUsed !== undefined) {
|
|
223
|
+
info.heapUsedMB = toMB(message.heapUsed);
|
|
224
|
+
}
|
|
225
|
+
sink.file(message.event);
|
|
226
|
+
return;
|
|
227
|
+
case 'batch':
|
|
228
|
+
sink.batchDone?.(message.files);
|
|
229
|
+
return;
|
|
230
|
+
case 'done':
|
|
231
|
+
finish(() => resolve(message.result), true);
|
|
232
|
+
return;
|
|
233
|
+
case 'error': {
|
|
234
|
+
const error = new Error(message.message);
|
|
235
|
+
if (message.stack !== undefined) {
|
|
236
|
+
error.stack = message.stack;
|
|
237
|
+
}
|
|
238
|
+
fail(error);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
fail(error instanceof Error ? error : new Error(String(error)));
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
const onError = (error) => {
|
|
248
|
+
fail(error.code === 'ERR_WORKER_OUT_OF_MEMORY'
|
|
249
|
+
? new Error(`Scan worker ran out of memory (heap limit ${heapLimit} MB, --max-heap-mb). ` +
|
|
250
|
+
'Narrow the scope, lower maxFiles, or raise --max-heap-mb.')
|
|
251
|
+
: error);
|
|
252
|
+
};
|
|
253
|
+
const onExit = (code) => {
|
|
254
|
+
fail(new Error(`Scan worker exited with code ${code} before the scan finished`));
|
|
255
|
+
};
|
|
256
|
+
worker.on('message', onMessage);
|
|
257
|
+
worker.on('error', onError);
|
|
258
|
+
worker.on('exit', onExit);
|
|
259
|
+
if (signal?.aborted === true) {
|
|
260
|
+
onAbort();
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
264
|
+
const start = { type: 'start', spec };
|
|
265
|
+
worker.postMessage(start);
|
|
266
|
+
});
|
|
267
|
+
return { result, released };
|
|
268
|
+
}
|
|
269
|
+
/** The waiting worker when it runs the same script and limit, otherwise a new one. */
|
|
270
|
+
function takeWorker(script, maxHeapMb) {
|
|
271
|
+
const candidate = standby;
|
|
272
|
+
if (candidate !== undefined &&
|
|
273
|
+
!candidate.exited &&
|
|
274
|
+
candidate.script === scriptKey(script) &&
|
|
275
|
+
candidate.maxHeapMb === maxHeapMb) {
|
|
276
|
+
standby = undefined;
|
|
277
|
+
candidate.worker.ref();
|
|
278
|
+
return candidate.worker;
|
|
279
|
+
}
|
|
280
|
+
return spawnWorker(script, maxHeapMb);
|
|
281
|
+
}
|
|
282
|
+
/** Starts a waiting worker for the default script unless one waits already or the host is off. */
|
|
283
|
+
function prepareStandby() {
|
|
284
|
+
if (!settings.enabled || (standby !== undefined && !standby.exited)) {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
const script = workerScript(undefined);
|
|
288
|
+
keepForNextScan(spawnWorker(script, settings.maxHeapMb), script, settings.maxHeapMb);
|
|
289
|
+
}
|
|
290
|
+
/** Parks `worker` as the waiting worker; an older waiting worker ends. */
|
|
291
|
+
function keepForNextScan(worker, script, maxHeapMb) {
|
|
292
|
+
if (standby !== undefined && standby.worker !== worker) {
|
|
293
|
+
void standby.worker.terminate();
|
|
294
|
+
}
|
|
295
|
+
const entry = { worker, script: scriptKey(script), maxHeapMb, exited: false };
|
|
296
|
+
worker.once('exit', () => {
|
|
297
|
+
entry.exited = true;
|
|
298
|
+
if (standby === entry) {
|
|
299
|
+
standby = undefined;
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
// A waiting worker must not keep the process alive
|
|
303
|
+
worker.unref();
|
|
304
|
+
standby = entry;
|
|
305
|
+
}
|
|
306
|
+
function spawnWorker(script, maxHeapMb) {
|
|
307
|
+
const worker = new Worker(script.script, {
|
|
308
|
+
...(script.eval === true ? { eval: true } : {}),
|
|
309
|
+
// Worker stdout would land on the parent's stdout, the JSON-RPC channel
|
|
310
|
+
stdout: true,
|
|
311
|
+
stderr: false,
|
|
312
|
+
...(maxHeapMb > 0 ? { resourceLimits: { maxOldGenerationSizeMb: maxHeapMb } } : {}),
|
|
313
|
+
});
|
|
314
|
+
worker.stdout.pipe(process.stderr, { end: false });
|
|
315
|
+
return worker;
|
|
316
|
+
}
|
|
317
|
+
/** Waits for a free slot; `false` when the signal aborts first. */
|
|
318
|
+
function acquire(signal) {
|
|
319
|
+
if (signal?.aborted === true) {
|
|
320
|
+
return Promise.resolve(false);
|
|
321
|
+
}
|
|
322
|
+
if (active < MAX_RUNNING) {
|
|
323
|
+
active++;
|
|
324
|
+
return Promise.resolve(true);
|
|
325
|
+
}
|
|
326
|
+
return new Promise((resolve) => {
|
|
327
|
+
const entry = {
|
|
328
|
+
start: () => {
|
|
329
|
+
signal?.removeEventListener('abort', onAbort);
|
|
330
|
+
active++;
|
|
331
|
+
resolve(true);
|
|
332
|
+
},
|
|
333
|
+
};
|
|
334
|
+
const onAbort = () => {
|
|
335
|
+
const index = waiting.indexOf(entry);
|
|
336
|
+
if (index >= 0) {
|
|
337
|
+
waiting.splice(index, 1);
|
|
338
|
+
}
|
|
339
|
+
resolve(false);
|
|
340
|
+
};
|
|
341
|
+
waiting.push(entry);
|
|
342
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
function release() {
|
|
346
|
+
active--;
|
|
347
|
+
waiting.shift()?.start();
|
|
348
|
+
}
|
|
349
|
+
function workerScript(workerUrl) {
|
|
350
|
+
return workerUrl === undefined ? defaultWorkerScript() : { script: workerUrl };
|
|
351
|
+
}
|
|
352
|
+
function scriptKey(script) {
|
|
353
|
+
return script.script instanceof URL ? script.script.href : script.script;
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* The worker script next to this module. From source (tsx, the stdio
|
|
357
|
+
* integration tests) the worker gets a bootstrap that registers tsx first:
|
|
358
|
+
* tsx's `--import` loader, which the worker inherits, does not register its
|
|
359
|
+
* hooks in worker threads, so `.js` imports of `.ts` files would not resolve.
|
|
360
|
+
*/
|
|
361
|
+
function defaultWorkerScript() {
|
|
362
|
+
if (!import.meta.url.endsWith('.ts')) {
|
|
363
|
+
return { script: new URL('./scan-worker.js', import.meta.url) };
|
|
364
|
+
}
|
|
365
|
+
const tsxApi = import.meta.resolve('tsx/esm/api');
|
|
366
|
+
const entry = new URL('./scan-worker.ts', import.meta.url).href;
|
|
367
|
+
return {
|
|
368
|
+
script: `import(${JSON.stringify(tsxApi)})` +
|
|
369
|
+
`.then((api) => { api.register(); return import(${JSON.stringify(entry)}); });`,
|
|
370
|
+
eval: true,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
function toMB(bytes) {
|
|
374
|
+
return Math.round(bytes / (1024 * 1024));
|
|
375
|
+
}
|
|
376
|
+
//# sourceMappingURL=scan-host.js.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @angular-modernizer/adapter-mcp - Messages between scan host and scan worker
|
|
3
|
+
*/
|
|
4
|
+
import type { ScanEngineResult, ScanFileEvent, ScanSpec } from '../tools/helpers/scan-engine.js';
|
|
5
|
+
/**
|
|
6
|
+
* Message from the host to a scan worker. A worker starts without its scan
|
|
7
|
+
* (standby) and runs the one `start` it gets.
|
|
8
|
+
*/
|
|
9
|
+
export interface ScanHostMessage {
|
|
10
|
+
type: 'start';
|
|
11
|
+
spec: ScanSpec;
|
|
12
|
+
}
|
|
13
|
+
/** Messages from a scan worker to the host. */
|
|
14
|
+
export type ScanWorkerMessage = {
|
|
15
|
+
type: 'ready';
|
|
16
|
+
ruleIds: string[];
|
|
17
|
+
heapUsed: number;
|
|
18
|
+
} | {
|
|
19
|
+
type: 'file';
|
|
20
|
+
event: ScanFileEvent;
|
|
21
|
+
heapUsed?: number;
|
|
22
|
+
} | {
|
|
23
|
+
type: 'batch';
|
|
24
|
+
files: number;
|
|
25
|
+
} | {
|
|
26
|
+
type: 'done';
|
|
27
|
+
result: ScanEngineResult;
|
|
28
|
+
} | {
|
|
29
|
+
type: 'error';
|
|
30
|
+
message: string;
|
|
31
|
+
stack?: string;
|
|
32
|
+
};
|
|
33
|
+
/** A worker reports its heap with every n-th file. */
|
|
34
|
+
export declare const HEAP_REPORT_EVERY = 20;
|
|
35
|
+
//# sourceMappingURL=scan-protocol.d.ts.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @angular-modernizer/adapter-mcp - Scan worker entry
|
|
3
|
+
*
|
|
4
|
+
* Loads the scan engine (ts-morph, core, api) on start, then runs one scan
|
|
5
|
+
* per `start` message from the host (`scan-host.ts`), one after the other,
|
|
6
|
+
* each with its own kernel, and posts each analyzed file. The worker stays
|
|
7
|
+
* alive between scans so its code stays optimized; the host ends it on a
|
|
8
|
+
* cancel, an error or the heap limit. Findings go through a JSON round
|
|
9
|
+
* trip before they are posted: the scan cache stores them as JSON anyway, and
|
|
10
|
+
* a function or class instance in `metadata` would otherwise make
|
|
11
|
+
* `postMessage` throw a `DataCloneError`.
|
|
12
|
+
*/
|
|
13
|
+
export {};
|
|
14
|
+
//# sourceMappingURL=scan-worker.d.ts.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @angular-modernizer/adapter-mcp - Scan worker entry
|
|
3
|
+
*
|
|
4
|
+
* Loads the scan engine (ts-morph, core, api) on start, then runs one scan
|
|
5
|
+
* per `start` message from the host (`scan-host.ts`), one after the other,
|
|
6
|
+
* each with its own kernel, and posts each analyzed file. The worker stays
|
|
7
|
+
* alive between scans so its code stays optimized; the host ends it on a
|
|
8
|
+
* cancel, an error or the heap limit. Findings go through a JSON round
|
|
9
|
+
* trip before they are posted: the scan cache stores them as JSON anyway, and
|
|
10
|
+
* a function or class instance in `metadata` would otherwise make
|
|
11
|
+
* `postMessage` throw a `DataCloneError`.
|
|
12
|
+
*/
|
|
13
|
+
import { parentPort } from 'node:worker_threads';
|
|
14
|
+
import { routeConsoleToStderr } from '../server/stdio-guard.js';
|
|
15
|
+
import { runScanEngine } from '../tools/helpers/scan-engine.js';
|
|
16
|
+
import { HEAP_REPORT_EVERY, } from './scan-protocol.js';
|
|
17
|
+
// The host pipes the worker's stdout to stderr as well; this keeps console
|
|
18
|
+
// output off stdout even before that pipe is attached.
|
|
19
|
+
routeConsoleToStderr();
|
|
20
|
+
const port = parentPort;
|
|
21
|
+
if (port === null) {
|
|
22
|
+
throw new Error('scan-worker must run as a worker thread');
|
|
23
|
+
}
|
|
24
|
+
const post = (message) => port.postMessage(message);
|
|
25
|
+
port.on('message', (message) => {
|
|
26
|
+
let files = 0;
|
|
27
|
+
runScanEngine(message.spec, {
|
|
28
|
+
ready: (ruleIds) => post({ type: 'ready', ruleIds, heapUsed: process.memoryUsage().heapUsed }),
|
|
29
|
+
file: (event) => {
|
|
30
|
+
files++;
|
|
31
|
+
post({
|
|
32
|
+
type: 'file',
|
|
33
|
+
event: JSON.parse(JSON.stringify(event)),
|
|
34
|
+
...(files % HEAP_REPORT_EVERY === 0 ? { heapUsed: process.memoryUsage().heapUsed } : {}),
|
|
35
|
+
});
|
|
36
|
+
},
|
|
37
|
+
batchDone: (count) => post({ type: 'batch', files: count }),
|
|
38
|
+
}).then((result) => {
|
|
39
|
+
post({ type: 'done', result });
|
|
40
|
+
// The scan's project is garbage now; with --expose-gc free it before the next scan
|
|
41
|
+
globalThis.gc?.();
|
|
42
|
+
}, (error) => post({
|
|
43
|
+
type: 'error',
|
|
44
|
+
message: error instanceof Error ? error.message : String(error),
|
|
45
|
+
...(error instanceof Error && error.stack !== undefined ? { stack: error.stack } : {}),
|
|
46
|
+
}));
|
|
47
|
+
});
|
|
48
|
+
//# sourceMappingURL=scan-worker.js.map
|
|
@@ -0,0 +1,75 @@
|
|
|
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
|
+
/** JSON-RPC id of the response. */
|
|
24
|
+
id: string | number | null;
|
|
25
|
+
/** Tool behind a tools/call response. */
|
|
26
|
+
tool?: string;
|
|
27
|
+
/** Size of the response as produced, before any oversize replacement. */
|
|
28
|
+
bytes: number;
|
|
29
|
+
/** The response exceeded the limit and was replaced by an error. */
|
|
30
|
+
replaced: boolean;
|
|
31
|
+
/** When the response was sent (ISO 8601). */
|
|
32
|
+
at: string;
|
|
33
|
+
}
|
|
34
|
+
/** Response sizes since the server started, for `server-status`. */
|
|
35
|
+
export interface ResponseStats {
|
|
36
|
+
/** Number of responses sent. */
|
|
37
|
+
count: number;
|
|
38
|
+
/** Sum of all response sizes in bytes. */
|
|
39
|
+
totalBytes: number;
|
|
40
|
+
/** Number of responses over the limit that were replaced by an error. */
|
|
41
|
+
oversized: number;
|
|
42
|
+
/** The most recent response. */
|
|
43
|
+
last?: ResponseRecord;
|
|
44
|
+
/** The largest response so far. */
|
|
45
|
+
largest?: ResponseRecord;
|
|
46
|
+
}
|
|
47
|
+
export interface LimitedStdioTransportOptions {
|
|
48
|
+
/** @default MAX_RESPONSE_BYTES */
|
|
49
|
+
maxResponseBytes?: number;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* `StdioServerTransport` that measures each response in `send()`. The tool
|
|
53
|
+
* behind a request id is reported by the `tools/call` handler through
|
|
54
|
+
* `trackToolCall`, so the oversize error and the statistics can name it.
|
|
55
|
+
*/
|
|
56
|
+
export declare class LimitedStdioTransport extends StdioServerTransport {
|
|
57
|
+
private readonly maxResponseBytes;
|
|
58
|
+
/** Tool name per pending tools/call request id. */
|
|
59
|
+
private readonly toolCalls;
|
|
60
|
+
private readonly responseStats;
|
|
61
|
+
constructor(stdin?: Readable, stdout?: Writable, options?: LimitedStdioTransportOptions);
|
|
62
|
+
/** Names the tool that answers request `id`. */
|
|
63
|
+
trackToolCall(id: RequestId, tool: string): void;
|
|
64
|
+
/** Sizes of the responses sent so far (copies, safe to hand out). */
|
|
65
|
+
getResponseStats(): ResponseStats;
|
|
66
|
+
send(message: JSONRPCMessage): Promise<void>;
|
|
67
|
+
/**
|
|
68
|
+
* Returns `message` when it serializes within the limit, otherwise a small
|
|
69
|
+
* replacement with the same id: an `isError` result for a tool call, a
|
|
70
|
+
* JSON-RPC error for anything else.
|
|
71
|
+
*/
|
|
72
|
+
private withinLimit;
|
|
73
|
+
private recordResponse;
|
|
74
|
+
}
|
|
75
|
+
//# 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
|