vibecode-anything 0.3.0 → 0.4.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 (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
@@ -0,0 +1,1736 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { VibecodeError } from "./errors.js";
5
+ import { splitCommand } from "./exec.js";
6
+ import { isSensitiveHeader, isSensitiveQueryParam } from "../ingestors/trace.js";
7
+ const DEFAULT_BASE_URL = "http://127.0.0.1:8080";
8
+ const DEFAULT_SERVER_NAME = "vibecode-mcp-server";
9
+ const GENERATED_SERVER_VERSION = "0.1.0";
10
+ const MAX_SCHEMA_DEPTH = 12;
11
+ const MAX_BODY_DEPTH = 16;
12
+ const MAX_SCHEMA_PROPERTIES = 128;
13
+ const MAX_TOOL_NAME_LEN = 64;
14
+ const MAX_SERVER_NAME_LEN = 64;
15
+ const MAX_CLI_BASE_ARGS = 64;
16
+ const VALID_FORMATS = new Set(["node-mjs", "ts"]);
17
+ const SUPPORTED_HTTP_METHODS = new Set([
18
+ "GET",
19
+ "POST",
20
+ "PUT",
21
+ "PATCH",
22
+ "DELETE",
23
+ "HEAD",
24
+ "OPTIONS"
25
+ ]);
26
+ const BODY_HTTP_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
27
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
28
+ const HEADER_NAME_TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
29
+ const SAFE_PATH_PARAM_RE = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
30
+ const SENSITIVE_HEADER_RE = /(?:authorization|proxy[_-]?authorization|cookie|set[_-]?cookie|api[_-]?key|apikey|auth[_-]?token|access[_-]?token|session[_-]?token|csrf|xsrf|secret|token|passwd|password|passphrase|credential|bearer)/i;
31
+ const SENSITIVE_QUERY_RE = /(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|secret|client[_-]?secret|password|passwd|passphrase|auth|jwt|session[_-]?id|session|sig|signature|private[_-]?key|authorization|cookie|csrf|xsrf|credential|credentials|bearer)/i;
32
+ const SECRET_FIELD_NAME_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|authorization|cookie|session[_-]?id|jwt|credentials?|bearer|csrf|xsrf)/i;
33
+ const SENSITIVE_CLI_FLAG_RE = /^--?(?:token|api[_-]?key|apikey|password|passwd|passphrase|secret|client[_-]?secret|auth[_-]?token|access[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?token|session[_-]?id|csrf[_-]?token|xsrf[_-]?token|csrf|xsrf|cookie|authorization|bearer|private[_-]?key|credential|credentials)(?:=.*)?$/i;
34
+ const AUTH_SCHEME_VALUE_RE = /^\s*(?:bearer|basic|token|digest|apikey)\s+\S+/i;
35
+ const VAULT_PATH_RE = /(?:~|[A-Za-z]:)?[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
36
+ const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>]+/g;
37
+ const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s"'`<>]+)@/g;
38
+ const INLINE_BEARER_TOKEN_RE = /\b(Bearer)\s+[^\s"'`<>]+/gi;
39
+ const INLINE_BASIC_TOKEN_RE = /\b([bB][aA][sS][iI][cC])\s+(?=[A-Za-z0-9._~+/=-]*(?:[0-9._~+/=-]|[A-Z]))[A-Za-z0-9._~+/=-]{4,}/g;
40
+ const INLINE_SCHEME_TOKEN_RE = /\b([tT][oO][kK][eE][nN]|[aA][pP][iI][kK][eE][yY])\s+(?=[A-Za-z0-9._~+/=:-]*(?:[0-9._~+/=:-]|[A-Z]))[A-Za-z0-9._~+/=:-]{4,}/g;
41
+ const INLINE_DIGEST_TOKEN_RE = /\b(Digest)\s+(?:[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*"))*|[A-Za-z0-9._~+/:-]{6,})/gi;
42
+ const INLINE_SENSITIVE_HEADER_RE = /\b(?:(Cookie|Set-Cookie)\s*[:=]\s*[^\s,\r\n;]+(?:\s*;\s*[A-Za-z0-9_.-]+=[^\s,\r\n;]+)*|(Authorization|Proxy-Authorization|X-API-Key|X-Auth-Token|X-Access-Token|X-Session-Token|X-Secret|X-CSRF-Token|X-XSRF-Token|CSRF-Token|XSRF-Token)\s*[:=]\s*(?:(?:Bearer|Basic|Token|ApiKey|Digest)\s+(?:\[REDACTED\]|[^\s,;]+)|[^\s,;]+))/gi;
43
+ const INLINE_SENSITIVE_QUERY_RE = /([?&])([^=&\s#]+)=([^&\s#]+)/g;
44
+ const INLINE_SENSITIVE_ENV_RE = /\b([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;`"']+)/g;
45
+ const ANSI = {
46
+ reset: "\x1b[0m",
47
+ bold: "\x1b[1m",
48
+ dim: "\x1b[2m",
49
+ green: "\x1b[32m",
50
+ yellow: "\x1b[33m",
51
+ cyan: "\x1b[36m"
52
+ };
53
+ function isRecord(value) {
54
+ return value !== null && typeof value === "object" && !Array.isArray(value);
55
+ }
56
+ function isForbiddenKey(key) {
57
+ return FORBIDDEN_KEYS.has(key);
58
+ }
59
+ function isSensitiveHeaderName(name) {
60
+ const trimmed = String(name).trim();
61
+ return isSensitiveHeader(trimmed) || SENSITIVE_HEADER_RE.test(trimmed);
62
+ }
63
+ function isSensitiveQueryName(name) {
64
+ const trimmed = String(name).trim();
65
+ return (isSensitiveQueryParam(trimmed) ||
66
+ SENSITIVE_QUERY_RE.test(trimmed) ||
67
+ isSensitiveHeaderName(trimmed));
68
+ }
69
+ function isSecretFieldName(name) {
70
+ const trimmed = String(name).trim();
71
+ return (SECRET_FIELD_NAME_RE.test(trimmed) ||
72
+ isSensitiveHeaderName(trimmed) ||
73
+ isSensitiveQueryName(trimmed));
74
+ }
75
+ function isAuthSchemeValue(value) {
76
+ return AUTH_SCHEME_VALUE_RE.test(value);
77
+ }
78
+ function redactVaultPaths(text) {
79
+ return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT_PATH]");
80
+ }
81
+ function sanitizeUrlInText(rawUrl) {
82
+ const withoutVault = redactVaultPaths(rawUrl);
83
+ const withoutAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
84
+ try {
85
+ const parsed = new URL(withoutAuth);
86
+ parsed.username = "";
87
+ parsed.password = "";
88
+ parsed.hash = "";
89
+ const safeParams = new URLSearchParams();
90
+ for (const [k, v] of parsed.searchParams.entries()) {
91
+ const trimmedKey = k.trim();
92
+ if (!trimmedKey || isForbiddenKey(trimmedKey) || isSensitiveQueryName(trimmedKey))
93
+ continue;
94
+ if (isAuthSchemeValue(v) || /\.vibecode-vault/i.test(v))
95
+ continue;
96
+ safeParams.append(k, redactVaultPaths(v));
97
+ }
98
+ const serialized = safeParams.toString();
99
+ parsed.search = serialized ? `?${serialized}` : "";
100
+ return parsed.toString();
101
+ }
102
+ catch {
103
+ const hashIdx = withoutAuth.indexOf("#");
104
+ const noHash = hashIdx >= 0 ? withoutAuth.slice(0, hashIdx) : withoutAuth;
105
+ return noHash.replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, key) => isSensitiveQueryName(key) ? `${sep}${key}=[REDACTED]` : match);
106
+ }
107
+ }
108
+ function sanitizeText(raw) {
109
+ const noNul = raw.replace(/\0/g, "");
110
+ const noVault = redactVaultPaths(noNul);
111
+ const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
112
+ const noBasicAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
113
+ const noSensQuery = noBasicAuth.replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, key) => isSensitiveQueryName(key) ? `${sep}${key}=[REDACTED]` : match);
114
+ const noBearer = noSensQuery.replace(INLINE_BEARER_TOKEN_RE, "$1 [REDACTED]");
115
+ const noBasic = noBearer.replace(INLINE_BASIC_TOKEN_RE, "$1 [REDACTED]");
116
+ const noScheme = noBasic.replace(INLINE_SCHEME_TOKEN_RE, "$1 [REDACTED]");
117
+ const noDigest = noScheme.replace(INLINE_DIGEST_TOKEN_RE, "$1 [REDACTED]");
118
+ const noSensHeader = noDigest.replace(INLINE_SENSITIVE_HEADER_RE, (_m, cookieHdr, otherHdr) => `${cookieHdr || otherHdr}: [REDACTED]`);
119
+ return noSensHeader.replace(INLINE_SENSITIVE_ENV_RE, (match, key) => isSecretFieldName(key) ? `${key}=[REDACTED]` : match);
120
+ }
121
+ function sanitizeSingleLineText(raw, maxLen = 200) {
122
+ const cleaned = sanitizeText(raw)
123
+ .replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
124
+ .replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
125
+ .replace(/\*\//g, "* /")
126
+ .replace(/\$\{/g, "$ {")
127
+ .replace(/\s+/g, " ")
128
+ .trim();
129
+ if (cleaned.length <= maxLen)
130
+ return cleaned;
131
+ return `${cleaned.slice(0, Math.max(1, maxLen - 3))}...`;
132
+ }
133
+ function sanitizeBaseUrl(raw) {
134
+ const cleaned = raw.replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "").trim();
135
+ if (!cleaned || /\.vibecode-vault/i.test(cleaned))
136
+ return null;
137
+ const withoutAuth = redactVaultPaths(cleaned).replace(URL_BASIC_AUTH_RE, "$1");
138
+ try {
139
+ const parsed = new URL(withoutAuth);
140
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
141
+ return null;
142
+ parsed.username = "";
143
+ parsed.password = "";
144
+ parsed.search = "";
145
+ parsed.hash = "";
146
+ const cleanPath = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/+$/, "");
147
+ return `${parsed.origin}${cleanPath}`;
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ }
153
+ function resolveBaseUrl(contract, options) {
154
+ if (typeof options.baseUrl === "string" && options.baseUrl.trim()) {
155
+ const sanitized = sanitizeBaseUrl(options.baseUrl);
156
+ if (sanitized)
157
+ return sanitized;
158
+ }
159
+ if (isRecord(contract.target) && Array.isArray(contract.target.sources)) {
160
+ for (const src of contract.target.sources) {
161
+ if (!isRecord(src))
162
+ continue;
163
+ if (typeof src.ref === "string" && /^https?:\/\//i.test(src.ref.trim())) {
164
+ const sanitized = sanitizeBaseUrl(src.ref);
165
+ if (sanitized)
166
+ return sanitized;
167
+ }
168
+ if (isRecord(src.meta) &&
169
+ typeof src.meta.baseUrl === "string" &&
170
+ /^https?:\/\//i.test(src.meta.baseUrl.trim())) {
171
+ const sanitized = sanitizeBaseUrl(src.meta.baseUrl);
172
+ if (sanitized)
173
+ return sanitized;
174
+ }
175
+ }
176
+ }
177
+ return DEFAULT_BASE_URL;
178
+ }
179
+ function sanitizeServerName(raw) {
180
+ if (typeof raw !== "string" || !raw.trim())
181
+ return DEFAULT_SERVER_NAME;
182
+ const cleaned = sanitizeSingleLineText(raw, MAX_SERVER_NAME_LEN)
183
+ .toLowerCase()
184
+ .replace(/[^a-z0-9._-]+/g, "-")
185
+ .replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, "")
186
+ .slice(0, MAX_SERVER_NAME_LEN);
187
+ if (!cleaned || isForbiddenKey(cleaned))
188
+ return DEFAULT_SERVER_NAME;
189
+ return cleaned;
190
+ }
191
+ function splitToAsciiWords(raw) {
192
+ const cleaned = sanitizeText(raw)
193
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
194
+ .replace(/[^A-Za-z0-9]+/g, " ")
195
+ .trim();
196
+ if (!cleaned)
197
+ return [];
198
+ return cleaned
199
+ .split(/\s+/)
200
+ .map((w) => w.toLowerCase().replace(/[^a-z0-9]/g, ""))
201
+ .filter((w) => w.length > 0);
202
+ }
203
+ function allocateToolName(tokens, fallback, used) {
204
+ const joined = tokens
205
+ .join("_")
206
+ .toLowerCase()
207
+ .replace(/[^a-z0-9_-]+/g, "_")
208
+ .replace(/_+/g, "_")
209
+ .replace(/^[_-]+|[_-]+$/g, "");
210
+ let base = joined || fallback;
211
+ if (!/^[a-z0-9]/.test(base)) {
212
+ base = `${fallback}_${base}`.replace(/_+/g, "_");
213
+ }
214
+ if (isForbiddenKey(base)) {
215
+ base = `${fallback}_tool`;
216
+ }
217
+ base = base.slice(0, MAX_TOOL_NAME_LEN).replace(/[_-]+$/, "") || fallback;
218
+ let candidate = base;
219
+ let seq = 2;
220
+ while (used.has(candidate) || isForbiddenKey(candidate)) {
221
+ const suffix = `_${seq}`;
222
+ const maxPrefix = MAX_TOOL_NAME_LEN - suffix.length;
223
+ const prefix = base.slice(0, maxPrefix).replace(/[_-]+$/, "") || fallback;
224
+ candidate = `${prefix}${suffix}`;
225
+ seq += 1;
226
+ }
227
+ used.add(candidate);
228
+ return candidate;
229
+ }
230
+ function sanitizePathname(rawPathname) {
231
+ const noHash = rawPathname.split("#")[0] ?? "";
232
+ const noControl = sanitizeText(noHash)
233
+ .replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "")
234
+ .trim();
235
+ if (!noControl)
236
+ return "/";
237
+ const encodedSpaces = noControl.replace(/\s+/g, "%20");
238
+ const rawSegments = encodedSpaces.split("/");
239
+ const stack = [];
240
+ for (const seg of rawSegments) {
241
+ if (!seg || seg === ".")
242
+ continue;
243
+ if (seg === "..") {
244
+ if (stack.length > 0)
245
+ stack.pop();
246
+ continue;
247
+ }
248
+ stack.push(seg);
249
+ }
250
+ return stack.length === 0 ? "/" : `/${stack.join("/")}`;
251
+ }
252
+ function splitRelativePathAndQuery(raw) {
253
+ const hashIdx = raw.indexOf("#");
254
+ const withoutHash = hashIdx >= 0 ? raw.slice(0, hashIdx) : raw;
255
+ const qIdx = withoutHash.indexOf("?");
256
+ const rawPathPart = qIdx >= 0 ? withoutHash.slice(0, qIdx) : withoutHash;
257
+ const rawQueryPart = qIdx >= 0 ? withoutHash.slice(qIdx + 1) : "";
258
+ const inlineQuery = [];
259
+ if (rawQueryPart) {
260
+ const params = new URLSearchParams(rawQueryPart);
261
+ for (const [k, v] of params.entries()) {
262
+ inlineQuery.push([k, v]);
263
+ }
264
+ }
265
+ return {
266
+ pathname: sanitizePathname(rawPathPart),
267
+ inlineQuery
268
+ };
269
+ }
270
+ function parsePathAndInlineQuery(rawPath) {
271
+ if (typeof rawPath !== "string") {
272
+ return { pathname: "/", inlineQuery: [] };
273
+ }
274
+ const cleaned = rawPath.replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "").trim();
275
+ if (!cleaned) {
276
+ return { pathname: "/", inlineQuery: [] };
277
+ }
278
+ if (/^https?:\/\//i.test(cleaned)) {
279
+ const withoutAuth = redactVaultPaths(cleaned).replace(URL_BASIC_AUTH_RE, "$1");
280
+ try {
281
+ const parsed = new URL(withoutAuth);
282
+ const inlineQuery = [];
283
+ for (const [k, v] of parsed.searchParams.entries()) {
284
+ inlineQuery.push([k, v]);
285
+ }
286
+ return {
287
+ pathname: sanitizePathname(parsed.pathname || "/"),
288
+ inlineQuery
289
+ };
290
+ }
291
+ catch {
292
+ const stripped = withoutAuth.replace(/^https?:\/\/[^/?#]*/i, "") || "/";
293
+ return splitRelativePathAndQuery(stripped);
294
+ }
295
+ }
296
+ return splitRelativePathAndQuery(cleaned);
297
+ }
298
+ function extractPathParams(pathname) {
299
+ const found = new Set();
300
+ const segments = pathname.split("/");
301
+ for (const segment of segments) {
302
+ let candidate = null;
303
+ if (segment.startsWith("{") && segment.endsWith("}") && segment.length > 2) {
304
+ candidate = segment.slice(1, -1);
305
+ }
306
+ else if (segment.startsWith(":") && segment.length > 1) {
307
+ candidate = segment.slice(1);
308
+ }
309
+ if (candidate &&
310
+ SAFE_PATH_PARAM_RE.test(candidate) &&
311
+ !isForbiddenKey(candidate) &&
312
+ !isSecretFieldName(candidate)) {
313
+ found.add(candidate);
314
+ }
315
+ }
316
+ return [...found];
317
+ }
318
+ function sanitizeQueryEntries(inlineQuery, structuredQuery) {
319
+ const merged = new Map();
320
+ const consider = (rawKey, rawVal) => {
321
+ const cleanKey = rawKey.replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "").trim();
322
+ if (!cleanKey || isForbiddenKey(cleanKey))
323
+ return;
324
+ if (isSensitiveQueryName(cleanKey) || /\.vibecode-vault/i.test(cleanKey))
325
+ return;
326
+ if (/\.vibecode-vault/i.test(rawVal) || isAuthSchemeValue(rawVal))
327
+ return;
328
+ const cleanVal = sanitizeText(rawVal).replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "");
329
+ if (isAuthSchemeValue(cleanVal))
330
+ return;
331
+ merged.set(cleanKey, cleanVal);
332
+ };
333
+ for (const [k, v] of inlineQuery) {
334
+ consider(k, v);
335
+ }
336
+ if (isRecord(structuredQuery)) {
337
+ for (const key of Object.keys(structuredQuery)) {
338
+ if (isForbiddenKey(key))
339
+ continue;
340
+ const val = structuredQuery[key];
341
+ if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
342
+ if (typeof val === "number" && !Number.isFinite(val))
343
+ continue;
344
+ consider(key, String(val));
345
+ }
346
+ }
347
+ }
348
+ return [...merged.entries()];
349
+ }
350
+ function sanitizeHeaders(rawHeaders) {
351
+ if (!isRecord(rawHeaders))
352
+ return [];
353
+ const byLower = new Map();
354
+ for (const rawKey of Object.keys(rawHeaders)) {
355
+ if (isForbiddenKey(rawKey))
356
+ continue;
357
+ const cleanKey = rawKey.replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "").trim();
358
+ if (!cleanKey || !HEADER_NAME_TOKEN_RE.test(cleanKey))
359
+ continue;
360
+ if (isSensitiveHeaderName(cleanKey) || /\.vibecode-vault/i.test(cleanKey))
361
+ continue;
362
+ const rawVal = rawHeaders[rawKey];
363
+ if (rawVal === undefined || rawVal === null)
364
+ continue;
365
+ const singleLineVal = String(rawVal)
366
+ .replace(/\0/g, "")
367
+ .replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
368
+ .trim();
369
+ if (!singleLineVal || singleLineVal === "[REDACTED]")
370
+ continue;
371
+ if (isAuthSchemeValue(singleLineVal) || /\.vibecode-vault/i.test(singleLineVal))
372
+ continue;
373
+ const cleanVal = sanitizeText(singleLineVal)
374
+ .replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, " ")
375
+ .trim();
376
+ if (!cleanVal)
377
+ continue;
378
+ byLower.set(cleanKey.toLowerCase(), [cleanKey, cleanVal]);
379
+ }
380
+ return [...byLower.values()];
381
+ }
382
+ function extractExpectedStatuses(rawStatus) {
383
+ const valid = new Set();
384
+ const isValid = (n) => typeof n === "number" && Number.isInteger(n) && n >= 100 && n <= 599;
385
+ if (isValid(rawStatus)) {
386
+ valid.add(rawStatus);
387
+ }
388
+ else if (Array.isArray(rawStatus)) {
389
+ for (const item of rawStatus) {
390
+ if (isValid(item))
391
+ valid.add(item);
392
+ }
393
+ }
394
+ return [...valid];
395
+ }
396
+ function extractExpectedExitCodes(rawExitCode) {
397
+ const valid = new Set();
398
+ const isValid = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0 && n <= 255;
399
+ if (isValid(rawExitCode)) {
400
+ valid.add(rawExitCode);
401
+ }
402
+ else if (Array.isArray(rawExitCode)) {
403
+ for (const item of rawExitCode) {
404
+ if (isValid(item))
405
+ valid.add(item);
406
+ }
407
+ }
408
+ return [...valid];
409
+ }
410
+ function sanitizeJsonValue(value, depth = 0, seen = new Set()) {
411
+ if (value === null || value === undefined)
412
+ return value;
413
+ if (typeof value === "boolean")
414
+ return value;
415
+ if (typeof value === "number")
416
+ return Number.isFinite(value) ? value : null;
417
+ if (typeof value === "string")
418
+ return sanitizeText(value);
419
+ if (depth >= MAX_BODY_DEPTH)
420
+ return null;
421
+ if (typeof value !== "object")
422
+ return undefined;
423
+ if (seen.has(value))
424
+ return null;
425
+ seen.add(value);
426
+ try {
427
+ if (Array.isArray(value)) {
428
+ return value.map((item) => sanitizeJsonValue(item, depth + 1, seen));
429
+ }
430
+ const out = Object.create(null);
431
+ for (const key of Object.keys(value)) {
432
+ if (isForbiddenKey(key))
433
+ continue;
434
+ const rawVal = value[key];
435
+ if (rawVal === undefined || typeof rawVal === "function" || typeof rawVal === "symbol") {
436
+ continue;
437
+ }
438
+ if (isSecretFieldName(key)) {
439
+ out[key] = typeof rawVal === "object" && rawVal !== null
440
+ ? sanitizeJsonValue(rawVal, depth + 1, seen)
441
+ : "[REDACTED]";
442
+ }
443
+ else {
444
+ out[key] = sanitizeJsonValue(rawVal, depth + 1, seen);
445
+ }
446
+ }
447
+ return out;
448
+ }
449
+ finally {
450
+ seen.delete(value);
451
+ }
452
+ }
453
+ function sanitizeSchemaNode(schema, inSecretField = false, depth = 0, seen = new Set()) {
454
+ if (!isRecord(schema))
455
+ return undefined;
456
+ if (depth >= MAX_SCHEMA_DEPTH)
457
+ return {};
458
+ if (seen.has(schema))
459
+ return {};
460
+ seen.add(schema);
461
+ try {
462
+ const out = {};
463
+ let propCount = 0;
464
+ for (const key of Object.keys(schema)) {
465
+ if (isForbiddenKey(key))
466
+ continue;
467
+ // Never retain example/examples/default values in generated MCP schemas.
468
+ if (key === "example" || key === "examples" || key === "default")
469
+ continue;
470
+ if (inSecretField && (key === "const" || key === "enum"))
471
+ continue;
472
+ const val = schema[key];
473
+ if (val === undefined)
474
+ continue;
475
+ if (key === "type") {
476
+ if (typeof val === "string") {
477
+ out.type = val;
478
+ }
479
+ else if (Array.isArray(val)) {
480
+ const types = val.filter((t) => typeof t === "string");
481
+ if (types.length > 0)
482
+ out.type = types;
483
+ }
484
+ }
485
+ else if (key === "description" && typeof val === "string") {
486
+ const cleanDesc = sanitizeSingleLineText(val, 160);
487
+ if (cleanDesc)
488
+ out.description = cleanDesc;
489
+ }
490
+ else if (key === "nullable" && typeof val === "boolean") {
491
+ out.nullable = val;
492
+ }
493
+ else if (key === "format" && typeof val === "string") {
494
+ out.format = sanitizeSingleLineText(val, 64);
495
+ }
496
+ else if (key === "required" && Array.isArray(val)) {
497
+ const reqs = val.filter((item) => typeof item === "string" &&
498
+ !isForbiddenKey(item) &&
499
+ !/\.vibecode-vault/i.test(item));
500
+ if (reqs.length > 0)
501
+ out.required = [...new Set(reqs)];
502
+ }
503
+ else if (key === "properties" && isRecord(val)) {
504
+ const props = {};
505
+ for (const propKey of Object.keys(val)) {
506
+ if (isForbiddenKey(propKey))
507
+ continue;
508
+ if (propCount >= MAX_SCHEMA_PROPERTIES)
509
+ break;
510
+ const cleanPropKey = redactVaultPaths(propKey).replace(/[\r\n\0\u2028\u2029]+/g, "");
511
+ if (!cleanPropKey || isForbiddenKey(cleanPropKey))
512
+ continue;
513
+ propCount += 1;
514
+ const sanitizedProp = sanitizeSchemaNode(val[propKey], inSecretField || isSecretFieldName(propKey) || isSecretFieldName(cleanPropKey), depth + 1, seen);
515
+ props[cleanPropKey] = sanitizedProp ?? {};
516
+ }
517
+ out.properties = props;
518
+ }
519
+ else if (key === "additionalProperties") {
520
+ if (typeof val === "boolean") {
521
+ out.additionalProperties = val;
522
+ }
523
+ else if (isRecord(val)) {
524
+ out.additionalProperties = sanitizeSchemaNode(val, inSecretField, depth + 1, seen) ?? {};
525
+ }
526
+ }
527
+ else if (key === "items") {
528
+ if (Array.isArray(val)) {
529
+ out.items = val
530
+ .map((item) => sanitizeSchemaNode(item, inSecretField, depth + 1, seen) ?? {})
531
+ .slice(0, 32);
532
+ }
533
+ else if (isRecord(val)) {
534
+ out.items = sanitizeSchemaNode(val, inSecretField, depth + 1, seen) ?? {};
535
+ }
536
+ }
537
+ else if (key === "allOf" || key === "anyOf" || key === "oneOf") {
538
+ if (Array.isArray(val)) {
539
+ const branches = val
540
+ .map((item) => sanitizeSchemaNode(item, inSecretField, depth + 1, seen))
541
+ .filter((item) => item !== undefined);
542
+ if (branches.length > 0)
543
+ out[key] = branches;
544
+ }
545
+ }
546
+ else if (key === "const") {
547
+ out.const = sanitizeJsonValue(val, depth + 1, seen);
548
+ }
549
+ else if (key === "enum" && Array.isArray(val)) {
550
+ out.enum = val.map((item) => sanitizeJsonValue(item, depth + 1, seen));
551
+ }
552
+ else if ((key === "minimum" || key === "maximum" || key === "minLength" || key === "maxLength" || key === "minItems" || key === "maxItems") &&
553
+ typeof val === "number" &&
554
+ Number.isFinite(val)) {
555
+ out[key] = val;
556
+ }
557
+ }
558
+ return out;
559
+ }
560
+ finally {
561
+ seen.delete(schema);
562
+ }
563
+ }
564
+ function inferSchemaFromValue(value, depth = 0, seen = new Set()) {
565
+ if (depth >= MAX_SCHEMA_DEPTH)
566
+ return {};
567
+ if (value === null)
568
+ return { type: "null" };
569
+ if (typeof value === "boolean")
570
+ return { type: "boolean" };
571
+ if (typeof value === "number") {
572
+ return { type: Number.isInteger(value) ? "integer" : "number" };
573
+ }
574
+ if (typeof value === "string")
575
+ return { type: "string" };
576
+ if (typeof value !== "object")
577
+ return {};
578
+ if (seen.has(value))
579
+ return {};
580
+ seen.add(value);
581
+ try {
582
+ if (Array.isArray(value)) {
583
+ if (value.length === 0)
584
+ return { type: "array", items: {} };
585
+ return { type: "array", items: inferSchemaFromValue(value[0], depth + 1, seen) };
586
+ }
587
+ const obj = value;
588
+ const properties = {};
589
+ const required = [];
590
+ let count = 0;
591
+ for (const key of Object.keys(obj)) {
592
+ if (isForbiddenKey(key))
593
+ continue;
594
+ if (count >= MAX_SCHEMA_PROPERTIES)
595
+ break;
596
+ const cleanKey = redactVaultPaths(key).replace(/[\r\n\0\u2028\u2029]+/g, "");
597
+ if (!cleanKey || isForbiddenKey(cleanKey))
598
+ continue;
599
+ count += 1;
600
+ const val = obj[key];
601
+ properties[cleanKey] = inferSchemaFromValue(val, depth + 1, seen);
602
+ if (val !== undefined && val !== null) {
603
+ required.push(cleanKey);
604
+ }
605
+ }
606
+ return {
607
+ type: "object",
608
+ properties,
609
+ ...(required.length > 0 ? { required } : {})
610
+ };
611
+ }
612
+ finally {
613
+ seen.delete(value);
614
+ }
615
+ }
616
+ function buildHttpInputSchema(pathParams, defaultQuery, hasBody, requestBodySchema) {
617
+ const properties = {};
618
+ const required = [];
619
+ if (pathParams.length > 0) {
620
+ const pathProps = {};
621
+ for (const p of pathParams) {
622
+ pathProps[p] = { type: "string", description: `Path parameter "${p}".` };
623
+ }
624
+ properties.path = {
625
+ type: "object",
626
+ description: "Required URL path parameters.",
627
+ properties: pathProps,
628
+ required: [...pathParams],
629
+ additionalProperties: false
630
+ };
631
+ required.push("path");
632
+ }
633
+ const queryProps = {};
634
+ for (const [k] of defaultQuery) {
635
+ queryProps[k] = { type: "string" };
636
+ }
637
+ properties.query = {
638
+ type: "object",
639
+ description: "Optional query string parameters.",
640
+ ...(Object.keys(queryProps).length > 0 ? { properties: queryProps } : {}),
641
+ additionalProperties: { type: "string" }
642
+ };
643
+ if (hasBody) {
644
+ properties.body =
645
+ requestBodySchema && Object.keys(requestBodySchema).length > 0
646
+ ? requestBodySchema
647
+ : { type: "object", description: "Optional JSON request body." };
648
+ }
649
+ properties.headers = {
650
+ type: "object",
651
+ description: "Optional extra HTTP headers (sensitive auth should use MCP_AUTH_HEADER).",
652
+ additionalProperties: { type: "string" }
653
+ };
654
+ return {
655
+ type: "object",
656
+ properties,
657
+ ...(required.length > 0 ? { required } : {}),
658
+ additionalProperties: false
659
+ };
660
+ }
661
+ function buildCliInputSchema() {
662
+ return {
663
+ type: "object",
664
+ properties: {
665
+ args: {
666
+ type: "array",
667
+ description: "Optional extra CLI arguments appended after the command template.",
668
+ items: { type: "string" },
669
+ maxItems: 64
670
+ },
671
+ flags: {
672
+ type: "object",
673
+ description: "Optional CLI flags converted to --key value (or --key for true).",
674
+ additionalProperties: {
675
+ oneOf: [{ type: "string" }, { type: "boolean" }]
676
+ }
677
+ },
678
+ stdin: {
679
+ type: "string",
680
+ description: "Optional UTF-8 standard input payload."
681
+ }
682
+ },
683
+ additionalProperties: false
684
+ };
685
+ }
686
+ function deriveHttpToolTokens(method, pathname, id) {
687
+ const methodWord = method.toLowerCase();
688
+ const pathWords = splitToAsciiWords(pathname);
689
+ if (pathWords.length > 0) {
690
+ return [methodWord, ...pathWords];
691
+ }
692
+ const idWords = splitToAsciiWords(id).filter((w) => w !== "inv" && w !== "http");
693
+ if (idWords.length > 0) {
694
+ return idWords[0] === methodWord ? idWords : [methodWord, ...idWords];
695
+ }
696
+ return [methodWord, "root"];
697
+ }
698
+ function deriveCliToolTokens(id, invariantArgs) {
699
+ const idWords = splitToAsciiWords(id).filter((w) => w !== "inv");
700
+ if (idWords.length > 0) {
701
+ return idWords[0] === "cli" ? idWords : ["cli", ...idWords];
702
+ }
703
+ const argWords = splitToAsciiWords(invariantArgs.slice(0, 3).join(" "));
704
+ if (argWords.length > 0) {
705
+ return ["cli", ...argWords];
706
+ }
707
+ return ["cli", "run"];
708
+ }
709
+ function normalizeHttpInvariant(inv, usedToolNames) {
710
+ const input = isRecord(inv.input) ? inv.input : {};
711
+ const expected = isRecord(inv.expected) ? inv.expected : {};
712
+ const methodRaw = typeof input.method === "string" && input.method.replace(/[\r\n\0]+/g, "").trim()
713
+ ? input.method.replace(/[\r\n\0]+/g, "").trim().toUpperCase()
714
+ : "GET";
715
+ if (!SUPPORTED_HTTP_METHODS.has(methodRaw)) {
716
+ return null;
717
+ }
718
+ const rawPath = typeof input.path === "string"
719
+ ? input.path
720
+ : typeof input.urlPath === "string"
721
+ ? input.urlPath
722
+ : undefined;
723
+ const { pathname, inlineQuery } = parsePathAndInlineQuery(rawPath);
724
+ const pathParams = extractPathParams(pathname);
725
+ const defaultQuery = sanitizeQueryEntries(inlineQuery, input.query);
726
+ const defaultHeaders = sanitizeHeaders(input.headers);
727
+ let hasBody = false;
728
+ let requestBodySchema;
729
+ if (BODY_HTTP_METHODS.has(methodRaw)) {
730
+ if (input.body !== undefined && input.body !== null) {
731
+ hasBody = true;
732
+ if (typeof input.body === "string") {
733
+ const trimmed = input.body.trim();
734
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
735
+ try {
736
+ const parsed = JSON.parse(trimmed);
737
+ requestBodySchema = sanitizeSchemaNode(inferSchemaFromValue(sanitizeJsonValue(parsed)));
738
+ }
739
+ catch {
740
+ requestBodySchema = { type: "string" };
741
+ }
742
+ }
743
+ else {
744
+ requestBodySchema = { type: "string" };
745
+ }
746
+ }
747
+ else {
748
+ requestBodySchema = sanitizeSchemaNode(inferSchemaFromValue(sanitizeJsonValue(input.body)));
749
+ }
750
+ }
751
+ else if (methodRaw === "POST" || methodRaw === "PUT" || methodRaw === "PATCH") {
752
+ hasBody = true;
753
+ }
754
+ }
755
+ const expectedStatuses = extractExpectedStatuses(expected.status);
756
+ const invariantId = typeof inv.id === "string" && inv.id.trim()
757
+ ? sanitizeSingleLineText(inv.id.trim(), 80)
758
+ : "http";
759
+ const rawDesc = typeof inv.description === "string" && inv.description.trim()
760
+ ? sanitizeSingleLineText(inv.description.trim(), 180)
761
+ : `${methodRaw} ${pathname}`;
762
+ const description = rawDesc || `${methodRaw} ${pathname}`;
763
+ const name = allocateToolName(deriveHttpToolTokens(methodRaw, pathname, invariantId), "http_tool", usedToolNames);
764
+ const inputSchema = buildHttpInputSchema(pathParams, defaultQuery, hasBody, requestBodySchema);
765
+ return {
766
+ kind: "http",
767
+ name,
768
+ invariantId,
769
+ description,
770
+ method: methodRaw,
771
+ pathname,
772
+ pathParams,
773
+ defaultQuery,
774
+ defaultHeaders,
775
+ hasBody,
776
+ expectedStatuses,
777
+ inputSchema
778
+ };
779
+ }
780
+ function isSensitiveCliValue(raw) {
781
+ if (/\.vibecode-vault/i.test(raw) || isAuthSchemeValue(raw))
782
+ return true;
783
+ const kvMatch = raw.match(/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)\s*[:=]/);
784
+ if (kvMatch && kvMatch[1] && (isSensitiveHeaderName(kvMatch[1]) || isSensitiveQueryName(kvMatch[1]))) {
785
+ return true;
786
+ }
787
+ return false;
788
+ }
789
+ function sanitizeCliArgList(rawArgs) {
790
+ const out = [];
791
+ for (let i = 0; i < rawArgs.length; i++) {
792
+ const raw = rawArgs[i];
793
+ if (typeof raw !== "string")
794
+ continue;
795
+ const noControl = raw.replace(/[\r\n\0\u2028\u2029]+/g, "");
796
+ if (!noControl)
797
+ continue;
798
+ if (isSensitiveCliValue(noControl))
799
+ continue;
800
+ const flagName = noControl.split("=")[0]?.replace(/^-{1,2}/, "") ?? "";
801
+ if (SENSITIVE_CLI_FLAG_RE.test(noControl) ||
802
+ (noControl.startsWith("-") && flagName.length > 0 && isSecretFieldName(flagName))) {
803
+ if (!noControl.includes("=")) {
804
+ i += 1;
805
+ }
806
+ continue;
807
+ }
808
+ if ((noControl === "-H" || noControl === "--header") && i + 1 < rawArgs.length) {
809
+ const nextRaw = String(rawArgs[i + 1] ?? "").replace(/[\r\n\0\u2028\u2029]+/g, "");
810
+ if (isSensitiveCliValue(nextRaw)) {
811
+ i += 1;
812
+ continue;
813
+ }
814
+ }
815
+ const sanitized = sanitizeText(noControl);
816
+ if (!sanitized || isSensitiveCliValue(sanitized))
817
+ continue;
818
+ out.push(sanitized);
819
+ if (out.length >= MAX_CLI_BASE_ARGS)
820
+ break;
821
+ }
822
+ return out;
823
+ }
824
+ function resolveCliCommandTokens(inv, contract) {
825
+ const input = isRecord(inv.input) ? inv.input : {};
826
+ if (typeof input.command === "string" && input.command.trim()) {
827
+ const tokens = splitCommand(input.command.trim());
828
+ if (tokens.length > 0)
829
+ return tokens;
830
+ }
831
+ else if (Array.isArray(input.command)) {
832
+ const tokens = input.command.filter((t) => typeof t === "string" && t.trim().length > 0);
833
+ if (tokens.length > 0)
834
+ return tokens;
835
+ }
836
+ const sources = isRecord(contract.target) && Array.isArray(contract.target.sources)
837
+ ? contract.target.sources
838
+ : [];
839
+ const extractFromSource = (src) => {
840
+ if (!isRecord(src))
841
+ return null;
842
+ if (isRecord(src.meta) && typeof src.meta.command === "string" && src.meta.command.trim()) {
843
+ const tokens = splitCommand(src.meta.command.trim());
844
+ if (tokens.length > 0)
845
+ return tokens;
846
+ }
847
+ if (typeof src.ref === "string" && src.ref.trim() && !/^https?:\/\//i.test(src.ref.trim())) {
848
+ const kind = typeof src.kind === "string" ? src.kind.toLowerCase() : "";
849
+ if (kind === "cli" || kind === "script" || kind === "command" || kind === "") {
850
+ const tokens = splitCommand(src.ref.trim());
851
+ if (tokens.length > 0)
852
+ return tokens;
853
+ }
854
+ }
855
+ return null;
856
+ };
857
+ if (typeof inv.sourceId === "string" && inv.sourceId.trim()) {
858
+ const matched = sources.find((s) => isRecord(s) && s.id === inv.sourceId);
859
+ const tokens = extractFromSource(matched);
860
+ if (tokens)
861
+ return tokens;
862
+ }
863
+ for (const src of sources) {
864
+ const tokens = extractFromSource(src);
865
+ if (tokens)
866
+ return tokens;
867
+ }
868
+ return null;
869
+ }
870
+ function normalizeCliInvariant(inv, contract, usedToolNames) {
871
+ const cmdTokens = resolveCliCommandTokens(inv, contract);
872
+ if (!cmdTokens || cmdTokens.length === 0) {
873
+ return null;
874
+ }
875
+ const rawExecutable = cmdTokens[0] ?? "";
876
+ const cleanExecutable = rawExecutable.replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "").trim();
877
+ if (!cleanExecutable ||
878
+ /\.vibecode-vault/i.test(cleanExecutable) ||
879
+ isAuthSchemeValue(cleanExecutable)) {
880
+ return null;
881
+ }
882
+ const sourceBaseArgs = sanitizeCliArgList(cmdTokens.slice(1));
883
+ const input = isRecord(inv.input) ? inv.input : {};
884
+ const expected = isRecord(inv.expected) ? inv.expected : {};
885
+ const rawInvArgs = Array.isArray(input.args)
886
+ ? input.args.filter((a) => typeof a === "string")
887
+ : [];
888
+ const invariantArgs = sanitizeCliArgList(rawInvArgs);
889
+ const baseArgs = [...sourceBaseArgs, ...invariantArgs].slice(0, MAX_CLI_BASE_ARGS);
890
+ const invariantId = typeof inv.id === "string" && inv.id.trim()
891
+ ? sanitizeSingleLineText(inv.id.trim(), 80)
892
+ : "cli";
893
+ const rawDesc = typeof inv.description === "string" && inv.description.trim()
894
+ ? sanitizeSingleLineText(inv.description.trim(), 180)
895
+ : `Run CLI command (${invariantId})`;
896
+ const description = rawDesc || `Run CLI command (${invariantId})`;
897
+ const name = allocateToolName(deriveCliToolTokens(invariantId, invariantArgs), "cli_tool", usedToolNames);
898
+ return {
899
+ kind: "cli",
900
+ name,
901
+ invariantId,
902
+ description,
903
+ executable: cleanExecutable,
904
+ baseArgs,
905
+ expectedExitCodes: extractExpectedExitCodes(expected.exitCode),
906
+ inputSchema: buildCliInputSchema()
907
+ };
908
+ }
909
+ function jsString(raw) {
910
+ return JSON.stringify(raw)
911
+ .replace(/\u2028/g, "\\u2028")
912
+ .replace(/\u2029/g, "\\u2029")
913
+ .replace(/\$\{/g, "\\u0024{")
914
+ .replace(/<\//g, "<\\/");
915
+ }
916
+ function jsJsonLiteral(value, indent = 2) {
917
+ const serialized = JSON.stringify(value, null, indent) ?? "null";
918
+ return serialized
919
+ .replace(/\u2028/g, "\\u2028")
920
+ .replace(/\u2029/g, "\\u2029")
921
+ .replace(/\$\{/g, "\\u0024{")
922
+ .replace(/<\//g, "<\\/");
923
+ }
924
+ function suggestedFilenameFor(format) {
925
+ return format === "ts" ? "mcp-server.ts" : "mcp-server.mjs";
926
+ }
927
+ function emitMcpServerCode(params) {
928
+ const { format, title, serverName, baseUrl, tools, skippedIds, includeSkippedComments } = params;
929
+ const isTs = format === "ts";
930
+ const hasHttpTools = tools.some((t) => t.kind === "http");
931
+ const hasCliTools = tools.some((t) => t.kind === "cli");
932
+ const lines = [];
933
+ lines.push("#!/usr/bin/env node");
934
+ lines.push("// Generated by vibecode-anything — Standalone zero-dependency stdio MCP server.");
935
+ lines.push(`// Title: ${sanitizeSingleLineText(title, 120)}`);
936
+ lines.push(`// Server: ${serverName} (${format})`);
937
+ lines.push(`// Default HTTP Base URL: ${baseUrl}`);
938
+ lines.push("// Runtime env: MCP_TARGET_URL (override HTTP base URL), MCP_AUTH_HEADER (optional runtime auth header).");
939
+ if (includeSkippedComments && skippedIds.length > 0) {
940
+ lines.push(`// Skipped non-exported invariants (${skippedIds.length}):`);
941
+ for (const id of skippedIds) {
942
+ lines.push(`// - ${sanitizeSingleLineText(id, 100)}`);
943
+ }
944
+ }
945
+ lines.push("");
946
+ lines.push('import readline from "node:readline";');
947
+ if (hasCliTools) {
948
+ lines.push('import { spawnSync } from "node:child_process";');
949
+ }
950
+ lines.push("");
951
+ if (isTs) {
952
+ lines.push("interface JsonRpcError {");
953
+ lines.push(" code: number;");
954
+ lines.push(" message: string;");
955
+ lines.push(" data?: unknown;");
956
+ lines.push("}");
957
+ lines.push("");
958
+ lines.push("interface JsonRpcResponse {");
959
+ lines.push(' jsonrpc: "2.0";');
960
+ lines.push(" id: string | number | null;");
961
+ lines.push(" result?: unknown;");
962
+ lines.push(" error?: JsonRpcError;");
963
+ lines.push("}");
964
+ lines.push("");
965
+ lines.push("interface PublicToolDef {");
966
+ lines.push(" name: string;");
967
+ lines.push(" description: string;");
968
+ lines.push(" inputSchema: Record<string, unknown>;");
969
+ lines.push("}");
970
+ lines.push("");
971
+ lines.push("interface HttpToolSpec extends PublicToolDef {");
972
+ lines.push(' kind: "http";');
973
+ lines.push(" method: string;");
974
+ lines.push(" pathname: string;");
975
+ lines.push(" pathParams: readonly string[];");
976
+ lines.push(" defaultQuery: ReadonlyArray<readonly [string, string]>;");
977
+ lines.push(" defaultHeaders: ReadonlyArray<readonly [string, string]>;");
978
+ lines.push(" hasBody: boolean;");
979
+ lines.push(" expectedStatuses: readonly number[];");
980
+ lines.push("}");
981
+ lines.push("");
982
+ lines.push("interface CliToolSpec extends PublicToolDef {");
983
+ lines.push(' kind: "cli";');
984
+ lines.push(" executable: string;");
985
+ lines.push(" baseArgs: readonly string[];");
986
+ lines.push(" expectedExitCodes: readonly number[];");
987
+ lines.push("}");
988
+ lines.push("");
989
+ lines.push("type ToolSpec = HttpToolSpec | CliToolSpec;");
990
+ lines.push("");
991
+ lines.push("interface McpToolCallResult {");
992
+ lines.push(' content: Array<{ type: "text"; text: string }>;');
993
+ lines.push(" isError?: boolean;");
994
+ lines.push("}");
995
+ lines.push("");
996
+ }
997
+ lines.push(`const SERVER_NAME = ${jsString(serverName)};`);
998
+ lines.push(`const SERVER_VERSION = ${jsString(GENERATED_SERVER_VERSION)};`);
999
+ lines.push(`const DEFAULT_BASE_URL = ${jsString(baseUrl)};`);
1000
+ lines.push('const SUPPORTED_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];');
1001
+ lines.push("");
1002
+ lines.push("const PARSE_ERROR = -32700;");
1003
+ lines.push("const INVALID_REQUEST = -32600;");
1004
+ lines.push("const METHOD_NOT_FOUND = -32601;");
1005
+ lines.push("const INVALID_PARAMS = -32602;");
1006
+ lines.push("const INTERNAL_ERROR = -32603;");
1007
+ lines.push("");
1008
+ lines.push('const FORBIDDEN_KEYS = new Set<string>(["__proto__", "constructor", "prototype"]);'.replace(isTs ? "" : "<string>", ""));
1009
+ lines.push("const MAX_ARG_DEPTH = 16;");
1010
+ if (hasHttpTools) {
1011
+ lines.push("const HTTP_TIMEOUT_MS = 15000;");
1012
+ lines.push("const MAX_HTTP_BODY_BYTES = 1024 * 1024;");
1013
+ lines.push("const HEADER_NAME_RE = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;");
1014
+ }
1015
+ if (hasCliTools) {
1016
+ lines.push("const CLI_TIMEOUT_MS = 15000;");
1017
+ lines.push("const MAX_CLI_ARGS = 64;");
1018
+ lines.push("const MAX_CLI_ARG_LEN = 4096;");
1019
+ lines.push("const MAX_CLI_STDIN_BYTES = 256 * 1024;");
1020
+ lines.push("const MAX_CLI_BUFFER = 4 * 1024 * 1024;");
1021
+ lines.push("const SAFE_FLAG_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;");
1022
+ }
1023
+ lines.push("");
1024
+ const serializedTools = tools.map((tool) => {
1025
+ if (tool.kind === "http") {
1026
+ return {
1027
+ kind: "http",
1028
+ name: tool.name,
1029
+ description: tool.description,
1030
+ inputSchema: tool.inputSchema,
1031
+ method: tool.method,
1032
+ pathname: tool.pathname,
1033
+ pathParams: tool.pathParams,
1034
+ defaultQuery: tool.defaultQuery,
1035
+ defaultHeaders: tool.defaultHeaders,
1036
+ hasBody: tool.hasBody,
1037
+ expectedStatuses: tool.expectedStatuses
1038
+ };
1039
+ }
1040
+ return {
1041
+ kind: "cli",
1042
+ name: tool.name,
1043
+ description: tool.description,
1044
+ inputSchema: tool.inputSchema,
1045
+ executable: tool.executable,
1046
+ baseArgs: tool.baseArgs,
1047
+ expectedExitCodes: tool.expectedExitCodes
1048
+ };
1049
+ });
1050
+ if (isTs) {
1051
+ lines.push(`const TOOLS: readonly ToolSpec[] = ${jsJsonLiteral(serializedTools, 2)};`);
1052
+ lines.push("");
1053
+ lines.push("const PUBLIC_TOOLS: readonly PublicToolDef[] = TOOLS.map((tool) => ({");
1054
+ lines.push(" name: tool.name,");
1055
+ lines.push(" description: tool.description,");
1056
+ lines.push(" inputSchema: tool.inputSchema");
1057
+ lines.push("}));");
1058
+ lines.push("");
1059
+ lines.push("const TOOL_MAP = new Map<string, ToolSpec>(TOOLS.map((tool) => [tool.name, tool]));");
1060
+ }
1061
+ else {
1062
+ lines.push(`const TOOLS = ${jsJsonLiteral(serializedTools, 2)};`);
1063
+ lines.push("");
1064
+ lines.push("const PUBLIC_TOOLS = TOOLS.map((tool) => ({");
1065
+ lines.push(" name: tool.name,");
1066
+ lines.push(" description: tool.description,");
1067
+ lines.push(" inputSchema: tool.inputSchema");
1068
+ lines.push("}));");
1069
+ lines.push("");
1070
+ lines.push("const TOOL_MAP = new Map(TOOLS.map((tool) => [tool.name, tool]));");
1071
+ }
1072
+ lines.push("");
1073
+ // Utility helpers
1074
+ lines.push(isTs
1075
+ ? "function isPlainObject(value: unknown): value is Record<string, unknown> {"
1076
+ : "function isPlainObject(value) {");
1077
+ lines.push(' return value !== null && typeof value === "object" && !Array.isArray(value);');
1078
+ lines.push("}");
1079
+ lines.push("");
1080
+ lines.push(isTs
1081
+ ? "function hasOwn(obj: Record<string, unknown>, key: string): boolean {"
1082
+ : "function hasOwn(obj, key) {");
1083
+ lines.push(" return Object.prototype.hasOwnProperty.call(obj, key);");
1084
+ lines.push("}");
1085
+ lines.push("");
1086
+ lines.push(isTs
1087
+ ? "function findForbiddenKey(value: unknown, depth = 0): string | null {"
1088
+ : "function findForbiddenKey(value, depth = 0) {");
1089
+ lines.push(' if (depth > MAX_ARG_DEPTH) return "max_depth_exceeded";');
1090
+ lines.push(' if (value === null || typeof value !== "object") return null;');
1091
+ lines.push(" if (Array.isArray(value)) {");
1092
+ lines.push(" for (const item of value) {");
1093
+ lines.push(" const bad = findForbiddenKey(item, depth + 1);");
1094
+ lines.push(" if (bad) return bad;");
1095
+ lines.push(" }");
1096
+ lines.push(" return null;");
1097
+ lines.push(" }");
1098
+ lines.push(" const rec = value" + (isTs ? " as Record<string, unknown>" : "") + ";");
1099
+ lines.push(" for (const key of Object.getOwnPropertyNames(rec)) {");
1100
+ lines.push(" if (FORBIDDEN_KEYS.has(key)) return key;");
1101
+ lines.push(" const bad = findForbiddenKey(rec[key], depth + 1);");
1102
+ lines.push(" if (bad) return bad;");
1103
+ lines.push(" }");
1104
+ lines.push(" return null;");
1105
+ lines.push("}");
1106
+ lines.push("");
1107
+ lines.push(isTs
1108
+ ? "function toErrorMessage(err: unknown): string {"
1109
+ : "function toErrorMessage(err) {");
1110
+ lines.push(' if (err instanceof Error) return err.message;');
1111
+ lines.push(' return typeof err === "string" ? err : String(err);');
1112
+ lines.push("}");
1113
+ lines.push("");
1114
+ lines.push(isTs
1115
+ ? "function makeTextResult(payload: unknown, isError = false): McpToolCallResult {"
1116
+ : "function makeTextResult(payload, isError = false) {");
1117
+ lines.push(' const text = typeof payload === "string" ? payload : JSON.stringify(payload, null, 2);');
1118
+ lines.push(" return {");
1119
+ lines.push(' content: [{ type: "text", text }],');
1120
+ lines.push(" ...(isError ? { isError: true } : {})");
1121
+ lines.push(" };");
1122
+ lines.push("}");
1123
+ lines.push("");
1124
+ if (hasHttpTools) {
1125
+ lines.push(isTs
1126
+ ? "function resolveTargetBaseUrl(): string {"
1127
+ : "function resolveTargetBaseUrl() {");
1128
+ lines.push(' const raw = (process.env.MCP_TARGET_URL || DEFAULT_BASE_URL).trim();');
1129
+ lines.push(" let parsed" + (isTs ? ": URL" : "") + ";");
1130
+ lines.push(" try {");
1131
+ lines.push(" parsed = new URL(raw);");
1132
+ lines.push(" } catch {");
1133
+ lines.push(' throw new Error("Invalid MCP_TARGET_URL: must be an absolute http(s) URL.");');
1134
+ lines.push(" }");
1135
+ lines.push(' if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {');
1136
+ lines.push(' throw new Error("Invalid MCP_TARGET_URL protocol: only http: and https: are allowed.");');
1137
+ lines.push(" }");
1138
+ lines.push(' const cleanPath = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\\/+$/, "");');
1139
+ lines.push(" return parsed.origin + cleanPath;");
1140
+ lines.push("}");
1141
+ lines.push("");
1142
+ lines.push(isTs
1143
+ ? "function deleteHeaderCaseInsensitive(headers: Record<string, string>, targetName: string): void {"
1144
+ : "function deleteHeaderCaseInsensitive(headers, targetName) {");
1145
+ lines.push(" const lower = targetName.toLowerCase();");
1146
+ lines.push(" for (const existing of Object.keys(headers)) {");
1147
+ lines.push(" if (existing.toLowerCase() === lower) {");
1148
+ lines.push(" delete headers[existing];");
1149
+ lines.push(" }");
1150
+ lines.push(" }");
1151
+ lines.push("}");
1152
+ lines.push("");
1153
+ lines.push(isTs
1154
+ ? "function applyAuthHeader(headers: Record<string, string>): void {"
1155
+ : "function applyAuthHeader(headers) {");
1156
+ lines.push(' const rawAuth = process.env.MCP_AUTH_HEADER;');
1157
+ lines.push(' if (typeof rawAuth !== "string" || !rawAuth.trim()) return;');
1158
+ lines.push(" if (/[\\r\\n\\0]/.test(rawAuth)) {");
1159
+ lines.push(' throw new Error("Invalid MCP_AUTH_HEADER: control characters are not allowed.");');
1160
+ lines.push(" }");
1161
+ lines.push(" const trimmed = rawAuth.trim();");
1162
+ lines.push(' const colonIdx = trimmed.indexOf(":");');
1163
+ lines.push(" if (colonIdx >= 0) {");
1164
+ lines.push(" const headerName = trimmed.slice(0, colonIdx).trim();");
1165
+ lines.push(" const headerValue = trimmed.slice(colonIdx + 1).trim();");
1166
+ lines.push(" if (!HEADER_NAME_RE.test(headerName) || FORBIDDEN_KEYS.has(headerName) || FORBIDDEN_KEYS.has(headerName.toLowerCase()) || headerValue.length === 0) {");
1167
+ lines.push(' throw new Error("Invalid MCP_AUTH_HEADER: forbidden or malformed header name/value.");');
1168
+ lines.push(" }");
1169
+ lines.push(" deleteHeaderCaseInsensitive(headers, headerName);");
1170
+ lines.push(" headers[headerName] = headerValue;");
1171
+ lines.push(" return;");
1172
+ lines.push(" }");
1173
+ lines.push(' deleteHeaderCaseInsensitive(headers, "Authorization");');
1174
+ lines.push(' headers["Authorization"] = trimmed;');
1175
+ lines.push("}");
1176
+ lines.push("");
1177
+ lines.push(isTs
1178
+ ? "async function executeHttpTool(tool: HttpToolSpec, args: Record<string, unknown>): Promise<McpToolCallResult> {"
1179
+ : "async function executeHttpTool(tool, args) {");
1180
+ lines.push(" const baseUrl = resolveTargetBaseUrl();");
1181
+ lines.push(" const baseParsed = new URL(baseUrl);");
1182
+ lines.push(' const basePrefix = baseParsed.pathname === "/" ? "/" : baseParsed.pathname.replace(/\\/+$/, "") + "/";');
1183
+ lines.push(" let resolvedPath = tool.pathname;");
1184
+ lines.push(" if (tool.pathParams.length > 0) {");
1185
+ lines.push(" const rawPathArgs = args.path;");
1186
+ lines.push(" if (!isPlainObject(rawPathArgs)) {");
1187
+ lines.push(' throw new Error("Missing required path parameters object.");');
1188
+ lines.push(" }");
1189
+ lines.push(" const paramValues" + (isTs ? ": Record<string, string>" : "") + " = Object.create(null)" + (isTs ? " as Record<string, string>" : "") + ";");
1190
+ lines.push(" for (const paramName of tool.pathParams) {");
1191
+ lines.push(" if (!hasOwn(rawPathArgs, paramName)) {");
1192
+ lines.push(' throw new Error("Missing required path parameter: " + paramName);');
1193
+ lines.push(" }");
1194
+ lines.push(" const rawVal = rawPathArgs[paramName];");
1195
+ lines.push(' if (typeof rawVal !== "string" && typeof rawVal !== "number") {');
1196
+ lines.push(' throw new Error("Path parameter must be a string or number: " + paramName);');
1197
+ lines.push(" }");
1198
+ lines.push(" const strVal = String(rawVal);");
1199
+ lines.push(' if (!strVal || strVal === "." || strVal === ".." || /[\\r\\n\\0]/.test(strVal)) {');
1200
+ lines.push(' throw new Error("Invalid path parameter value: " + paramName);');
1201
+ lines.push(" }");
1202
+ lines.push(" paramValues[paramName] = encodeURIComponent(strVal);");
1203
+ lines.push(" }");
1204
+ lines.push(' resolvedPath = tool.pathname.split("/").map((seg) => {');
1205
+ lines.push(' if (seg.startsWith("{") && seg.endsWith("}")) {');
1206
+ lines.push(" const key = seg.slice(1, -1);");
1207
+ lines.push(" if (hasOwn(paramValues, key)) return paramValues[key];");
1208
+ lines.push(' } else if (seg.startsWith(":")) {');
1209
+ lines.push(" const key = seg.slice(1);");
1210
+ lines.push(" if (hasOwn(paramValues, key)) return paramValues[key];");
1211
+ lines.push(" }");
1212
+ lines.push(" return seg;");
1213
+ lines.push(' }).join("/");');
1214
+ lines.push(" }");
1215
+ lines.push("");
1216
+ lines.push(" const url = new URL(baseUrl + resolvedPath);");
1217
+ lines.push(' const baseExact = basePrefix === "/" ? "/" : basePrefix.slice(0, -1);');
1218
+ lines.push(' if (url.origin !== baseParsed.origin || (basePrefix !== "/" && url.pathname !== baseExact && !url.pathname.startsWith(basePrefix))) {');
1219
+ lines.push(' throw new Error("Resolved request URL escapes configured MCP_TARGET_URL base path.");');
1220
+ lines.push(" }");
1221
+ lines.push(" for (const [k, v] of tool.defaultQuery) {");
1222
+ lines.push(" url.searchParams.set(k, v);");
1223
+ lines.push(" }");
1224
+ lines.push(" if (args.query !== undefined) {");
1225
+ lines.push(" if (!isPlainObject(args.query)) {");
1226
+ lines.push(' throw new Error("query must be a plain object.");');
1227
+ lines.push(" }");
1228
+ lines.push(" for (const key of Object.keys(args.query)) {");
1229
+ lines.push(" if (FORBIDDEN_KEYS.has(key)) continue;");
1230
+ lines.push(" const val = args.query[key];");
1231
+ lines.push(" if (val === undefined || val === null) continue;");
1232
+ lines.push(' if (typeof val !== "string" && typeof val !== "number" && typeof val !== "boolean") {');
1233
+ lines.push(' throw new Error("Query parameter must be scalar: " + key);');
1234
+ lines.push(" }");
1235
+ lines.push(" url.searchParams.set(key, String(val));");
1236
+ lines.push(" }");
1237
+ lines.push(" }");
1238
+ lines.push("");
1239
+ lines.push(" const headers" + (isTs ? ": Record<string, string>" : "") + " = Object.create(null)" + (isTs ? " as Record<string, string>" : "") + ";");
1240
+ lines.push(" for (const [k, v] of tool.defaultHeaders) {");
1241
+ lines.push(" headers[k] = v;");
1242
+ lines.push(" }");
1243
+ lines.push(" if (args.headers !== undefined) {");
1244
+ lines.push(" if (!isPlainObject(args.headers)) {");
1245
+ lines.push(' throw new Error("headers must be a plain object.");');
1246
+ lines.push(" }");
1247
+ lines.push(" for (const key of Object.keys(args.headers)) {");
1248
+ lines.push(" if (FORBIDDEN_KEYS.has(key) || !HEADER_NAME_RE.test(key)) {");
1249
+ lines.push(' throw new Error("Invalid HTTP header name: " + key);');
1250
+ lines.push(" }");
1251
+ lines.push(" const val = args.headers[key];");
1252
+ lines.push(' if (typeof val !== "string" || /[\\r\\n\\0]/.test(val)) {');
1253
+ lines.push(' throw new Error("Invalid HTTP header value for: " + key);');
1254
+ lines.push(" }");
1255
+ lines.push(" deleteHeaderCaseInsensitive(headers, key);");
1256
+ lines.push(" headers[key] = val;");
1257
+ lines.push(" }");
1258
+ lines.push(" }");
1259
+ lines.push(" applyAuthHeader(headers);");
1260
+ lines.push("");
1261
+ lines.push(" let requestBody" + (isTs ? ": string | undefined" : "") + ";");
1262
+ lines.push(" if (tool.hasBody && args.body !== undefined) {");
1263
+ lines.push(' if (typeof args.body === "string") {');
1264
+ lines.push(" requestBody = args.body;");
1265
+ lines.push(" } else {");
1266
+ lines.push(" requestBody = JSON.stringify(args.body);");
1267
+ lines.push(' const hasContentType = Object.keys(headers).some((k) => k.toLowerCase() === "content-type");');
1268
+ lines.push(' if (!hasContentType) headers["Content-Type"] = "application/json";');
1269
+ lines.push(" }");
1270
+ lines.push(" }");
1271
+ lines.push("");
1272
+ lines.push(" const res = await fetch(url.toString(), {");
1273
+ lines.push(" method: tool.method,");
1274
+ lines.push(" headers,");
1275
+ lines.push(" ...(requestBody !== undefined ? { body: requestBody } : {}),");
1276
+ lines.push(" signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)");
1277
+ lines.push(" });");
1278
+ lines.push(' const contentType = res.headers.get("content-type") || "";');
1279
+ lines.push(" const rawText = await res.text();");
1280
+ lines.push(" const truncated = rawText.length > MAX_HTTP_BODY_BYTES;");
1281
+ lines.push(" const textBody = truncated ? rawText.slice(0, MAX_HTTP_BODY_BYTES) : rawText;");
1282
+ lines.push(" let parsedBody" + (isTs ? ": unknown" : "") + " = textBody;");
1283
+ lines.push(' if (!truncated && (contentType.toLowerCase().includes("json") || /^\\s*[{\\[]/.test(textBody))) {');
1284
+ lines.push(" try {");
1285
+ lines.push(" parsedBody = JSON.parse(textBody);");
1286
+ lines.push(" } catch {");
1287
+ lines.push(" parsedBody = textBody;");
1288
+ lines.push(" }");
1289
+ lines.push(" }");
1290
+ lines.push(" const expectedOk = tool.expectedStatuses.length > 0 ? tool.expectedStatuses.includes(res.status) : res.ok;");
1291
+ lines.push(" return makeTextResult(");
1292
+ lines.push(" {");
1293
+ lines.push(" ok: expectedOk,");
1294
+ lines.push(" status: res.status,");
1295
+ lines.push(" statusText: res.statusText,");
1296
+ lines.push(" url: url.toString(),");
1297
+ lines.push(" contentType,");
1298
+ lines.push(" ...(truncated ? { truncated: true } : {}),");
1299
+ lines.push(" body: parsedBody");
1300
+ lines.push(" },");
1301
+ lines.push(" !expectedOk");
1302
+ lines.push(" );");
1303
+ lines.push("}");
1304
+ lines.push("");
1305
+ }
1306
+ if (hasCliTools) {
1307
+ lines.push(isTs
1308
+ ? "function executeCliTool(tool: CliToolSpec, args: Record<string, unknown>): McpToolCallResult {"
1309
+ : "function executeCliTool(tool, args) {");
1310
+ lines.push(" const userArgs" + (isTs ? ": string[]" : "") + " = [];");
1311
+ lines.push(" if (args.args !== undefined) {");
1312
+ lines.push(" if (!Array.isArray(args.args)) {");
1313
+ lines.push(' throw new Error("args must be an array of strings.");');
1314
+ lines.push(" }");
1315
+ lines.push(" if (args.args.length > MAX_CLI_ARGS) {");
1316
+ lines.push(' throw new Error("Too many CLI arguments (max " + MAX_CLI_ARGS + ").");');
1317
+ lines.push(" }");
1318
+ lines.push(" for (const item of args.args) {");
1319
+ lines.push(' if (typeof item !== "string") throw new Error("Every CLI argument must be a string.");');
1320
+ lines.push(' if (item.includes("\\0")) throw new Error("CLI argument cannot contain NUL bytes.");');
1321
+ lines.push(' if (item.length > MAX_CLI_ARG_LEN) throw new Error("CLI argument exceeds max length.");');
1322
+ lines.push(" userArgs.push(item);");
1323
+ lines.push(" }");
1324
+ lines.push(" }");
1325
+ lines.push(" if (args.flags !== undefined) {");
1326
+ lines.push(" if (!isPlainObject(args.flags)) {");
1327
+ lines.push(' throw new Error("flags must be a plain object.");');
1328
+ lines.push(" }");
1329
+ lines.push(" for (const key of Object.keys(args.flags)) {");
1330
+ lines.push(" if (FORBIDDEN_KEYS.has(key) || !SAFE_FLAG_NAME_RE.test(key)) {");
1331
+ lines.push(' throw new Error("Invalid CLI flag name: " + key);');
1332
+ lines.push(" }");
1333
+ lines.push(" const val = args.flags[key];");
1334
+ lines.push(" if (val === false || val === undefined) continue;");
1335
+ lines.push(' const flagToken = key.length === 1 ? "-" + key : "--" + key;');
1336
+ lines.push(" if (val === true) {");
1337
+ lines.push(" userArgs.push(flagToken);");
1338
+ lines.push(' } else if (typeof val === "string") {');
1339
+ lines.push(' if (val.includes("\\0") || val.length > MAX_CLI_ARG_LEN) throw new Error("Invalid CLI flag value: " + key);');
1340
+ lines.push(" userArgs.push(flagToken, val);");
1341
+ lines.push(" } else {");
1342
+ lines.push(' throw new Error("CLI flag value must be string or boolean: " + key);');
1343
+ lines.push(" }");
1344
+ lines.push(" if (userArgs.length > MAX_CLI_ARGS) {");
1345
+ lines.push(' throw new Error("Too many CLI arguments (max " + MAX_CLI_ARGS + ").");');
1346
+ lines.push(" }");
1347
+ lines.push(" }");
1348
+ lines.push(" }");
1349
+ lines.push("");
1350
+ lines.push(" let stdinPayload" + (isTs ? ": string | undefined" : "") + ";");
1351
+ lines.push(" if (args.stdin !== undefined) {");
1352
+ lines.push(' if (typeof args.stdin !== "string") throw new Error("stdin must be a string.");');
1353
+ lines.push(" if (Buffer.byteLength(args.stdin, \"utf8\") > MAX_CLI_STDIN_BYTES) {");
1354
+ lines.push(' throw new Error("stdin exceeds maximum allowed size.");');
1355
+ lines.push(" }");
1356
+ lines.push(" stdinPayload = args.stdin;");
1357
+ lines.push(" }");
1358
+ lines.push("");
1359
+ lines.push(" const argList = [...tool.baseArgs, ...userArgs];");
1360
+ lines.push(" const res = spawnSync(tool.executable, argList, {");
1361
+ lines.push(" shell: false,");
1362
+ lines.push(' encoding: "utf8",');
1363
+ lines.push(" timeout: CLI_TIMEOUT_MS,");
1364
+ lines.push(" windowsHide: true,");
1365
+ lines.push(" maxBuffer: MAX_CLI_BUFFER,");
1366
+ lines.push(" ...(stdinPayload !== undefined ? { input: stdinPayload } : {})");
1367
+ lines.push(" });");
1368
+ if (isTs) {
1369
+ lines.push(' const errCode = res.error && "code" in res.error && typeof (res.error as NodeJS.ErrnoException).code === "string" ? (res.error as NodeJS.ErrnoException).code : undefined;');
1370
+ }
1371
+ else {
1372
+ lines.push(' const errCode = res.error && typeof res.error.code === "string" ? res.error.code : undefined;');
1373
+ }
1374
+ lines.push(' const timedOut = errCode === "ETIMEDOUT";');
1375
+ lines.push(" const exitCode = typeof res.status === \"number\" ? res.status : null;");
1376
+ lines.push(" const expectedOk =");
1377
+ lines.push(" !res.error &&");
1378
+ lines.push(" (tool.expectedExitCodes.length > 0");
1379
+ lines.push(" ? exitCode !== null && tool.expectedExitCodes.includes(exitCode)");
1380
+ lines.push(" : exitCode === 0);");
1381
+ lines.push(" return makeTextResult(");
1382
+ lines.push(" {");
1383
+ lines.push(" ok: expectedOk,");
1384
+ lines.push(" exitCode,");
1385
+ lines.push(' stdout: typeof res.stdout === "string" ? res.stdout : "",');
1386
+ lines.push(' stderr: typeof res.stderr === "string" ? res.stderr : "",');
1387
+ lines.push(" signal: res.signal ?? null,");
1388
+ lines.push(" timedOut,");
1389
+ lines.push(" ...(res.error ? { error: res.error.message } : {})");
1390
+ lines.push(" },");
1391
+ lines.push(" !expectedOk");
1392
+ lines.push(" );");
1393
+ lines.push("}");
1394
+ lines.push("");
1395
+ }
1396
+ // Dispatch handleSingle & handleMessage
1397
+ lines.push(isTs
1398
+ ? "async function handleSingle(msg: unknown): Promise<JsonRpcResponse | null> {"
1399
+ : "async function handleSingle(msg) {");
1400
+ lines.push(" const rec = isPlainObject(msg) ? msg : null;");
1401
+ lines.push(' const rawId = rec && hasOwn(rec, "id") ? rec.id : undefined;');
1402
+ lines.push(" const hasId = rawId !== undefined;");
1403
+ lines.push(' const validId = rawId === undefined || rawId === null || typeof rawId === "string" || (typeof rawId === "number" && Number.isFinite(rawId));');
1404
+ lines.push(" const errorId" +
1405
+ (isTs ? ": string | number | null" : "") +
1406
+ ' = validId && rawId !== undefined ? (rawId' +
1407
+ (isTs ? " as string | number | null" : "") +
1408
+ ") : null;");
1409
+ lines.push(isTs
1410
+ ? " const fail = (code: number, message: string): JsonRpcResponse | null =>"
1411
+ : " const fail = (code, message) =>");
1412
+ lines.push(' hasId ? { jsonrpc: "2.0", id: errorId, error: { code, message } } : null;');
1413
+ lines.push(isTs
1414
+ ? " const reply = (result: unknown): JsonRpcResponse | null =>"
1415
+ : " const reply = (result) =>");
1416
+ lines.push(' hasId ? { jsonrpc: "2.0", id: errorId, result } : null;');
1417
+ lines.push("");
1418
+ lines.push(" if (!validId) {");
1419
+ lines.push(' return { jsonrpc: "2.0", id: null, error: { code: INVALID_REQUEST, message: "Invalid Request: id must be a string, number, or null" } };');
1420
+ lines.push(" }");
1421
+ lines.push(' if (!rec || typeof rec.method !== "string" || rec.method.length === 0) {');
1422
+ lines.push(' return { jsonrpc: "2.0", id: errorId, error: { code: INVALID_REQUEST, message: "Invalid Request: expected a JSON-RPC 2.0 object with a method" } };');
1423
+ lines.push(" }");
1424
+ lines.push(' if (rec.jsonrpc !== undefined && rec.jsonrpc !== "2.0") {');
1425
+ lines.push(' return { jsonrpc: "2.0", id: errorId, error: { code: INVALID_REQUEST, message: \'Invalid Request: jsonrpc must be "2.0"\' } };');
1426
+ lines.push(" }");
1427
+ lines.push(" const badRequestKey = findForbiddenKey(rec);");
1428
+ lines.push(" if (badRequestKey) {");
1429
+ lines.push(' return fail(INVALID_PARAMS, "Forbidden key in JSON-RPC request: " + badRequestKey);');
1430
+ lines.push(" }");
1431
+ lines.push("");
1432
+ lines.push(" switch (rec.method) {");
1433
+ lines.push(' case "initialize": {');
1434
+ lines.push(" const params = isPlainObject(rec.params) ? rec.params : null;");
1435
+ lines.push(' const requested = params && typeof params.protocolVersion === "string" ? params.protocolVersion : null;');
1436
+ lines.push(" const protocolVersion = requested && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)");
1437
+ lines.push(" ? requested");
1438
+ lines.push(" : SUPPORTED_PROTOCOL_VERSIONS[0];");
1439
+ lines.push(" return reply({");
1440
+ lines.push(" protocolVersion,");
1441
+ lines.push(" capabilities: {");
1442
+ lines.push(" tools: { listChanged: false }");
1443
+ lines.push(" },");
1444
+ lines.push(" serverInfo: {");
1445
+ lines.push(" name: SERVER_NAME,");
1446
+ lines.push(" version: SERVER_VERSION");
1447
+ lines.push(" }");
1448
+ lines.push(" });");
1449
+ lines.push(" }");
1450
+ lines.push(' case "notifications/initialized":');
1451
+ lines.push(' case "notifications/cancelled":');
1452
+ lines.push(" return null;");
1453
+ lines.push(' case "ping":');
1454
+ lines.push(" return reply({});");
1455
+ lines.push(' case "tools/list":');
1456
+ lines.push(" return reply({ tools: PUBLIC_TOOLS });");
1457
+ lines.push(' case "tools/call": {');
1458
+ lines.push(" if (!isPlainObject(rec.params)) {");
1459
+ lines.push(' return fail(INVALID_PARAMS, "tools/call params must be an object");');
1460
+ lines.push(" }");
1461
+ lines.push(" const toolName = rec.params.name;");
1462
+ lines.push(' if (typeof toolName !== "string" || !toolName || FORBIDDEN_KEYS.has(toolName)) {');
1463
+ lines.push(' return fail(INVALID_PARAMS, "tools/call requires a valid params.name");');
1464
+ lines.push(" }");
1465
+ lines.push(" const rawArgs = rec.params.arguments;");
1466
+ lines.push(" if (rawArgs !== undefined && !isPlainObject(rawArgs)) {");
1467
+ lines.push(' return fail(INVALID_PARAMS, "tools/call params.arguments must be a plain object");');
1468
+ lines.push(" }");
1469
+ lines.push(" const args = (rawArgs" + (isTs ? " as Record<string, unknown> | undefined" : "") + ") || {};");
1470
+ lines.push(" const badKey = findForbiddenKey(args);");
1471
+ lines.push(" if (badKey) {");
1472
+ lines.push(' return fail(INVALID_PARAMS, "Forbidden key in tool arguments: " + badKey);');
1473
+ lines.push(" }");
1474
+ lines.push(" const tool = TOOL_MAP.get(toolName);");
1475
+ lines.push(" if (!tool) {");
1476
+ lines.push(' return fail(INVALID_PARAMS, "Unknown tool: " + toolName);');
1477
+ lines.push(" }");
1478
+ lines.push(" try {");
1479
+ if (hasHttpTools && hasCliTools) {
1480
+ lines.push(' const result = tool.kind === "http" ? await executeHttpTool(tool, args) : executeCliTool(tool, args);');
1481
+ lines.push(" return reply(result);");
1482
+ }
1483
+ else if (hasHttpTools) {
1484
+ lines.push(' if (tool.kind === "http") {');
1485
+ lines.push(" return reply(await executeHttpTool(tool, args));");
1486
+ lines.push(" }");
1487
+ lines.push(' return fail(INTERNAL_ERROR, "Unsupported tool kind");');
1488
+ }
1489
+ else if (hasCliTools) {
1490
+ lines.push(' if (tool.kind === "cli") {');
1491
+ lines.push(" return reply(executeCliTool(tool, args));");
1492
+ lines.push(" }");
1493
+ lines.push(' return fail(INTERNAL_ERROR, "Unsupported tool kind");');
1494
+ }
1495
+ else {
1496
+ lines.push(' return fail(INVALID_PARAMS, "Unknown tool: " + toolName);');
1497
+ }
1498
+ lines.push(" } catch (err" + (isTs ? ": unknown" : "") + ") {");
1499
+ lines.push(" return reply(makeTextResult({ ok: false, tool: toolName, error: toErrorMessage(err) }, true));");
1500
+ lines.push(" }");
1501
+ lines.push(" }");
1502
+ lines.push(" default:");
1503
+ lines.push(' return fail(METHOD_NOT_FOUND, "Method not found: " + rec.method);');
1504
+ lines.push(" }");
1505
+ lines.push("}");
1506
+ lines.push("");
1507
+ lines.push(isTs
1508
+ ? "async function handleMessage(msg: unknown): Promise<JsonRpcResponse | JsonRpcResponse[] | null> {"
1509
+ : "async function handleMessage(msg) {");
1510
+ lines.push(" if (Array.isArray(msg)) {");
1511
+ lines.push(" if (msg.length === 0) {");
1512
+ lines.push(' return { jsonrpc: "2.0", id: null, error: { code: INVALID_REQUEST, message: "Invalid Request: empty batch" } };');
1513
+ lines.push(" }");
1514
+ lines.push(" const out" + (isTs ? ": JsonRpcResponse[]" : "") + " = [];");
1515
+ lines.push(" for (const item of msg) {");
1516
+ lines.push(" const res = await handleSingle(item);");
1517
+ lines.push(" if (res) out.push(res);");
1518
+ lines.push(" }");
1519
+ lines.push(" return out.length > 0 ? out : null;");
1520
+ lines.push(" }");
1521
+ lines.push(" return handleSingle(msg);");
1522
+ lines.push("}");
1523
+ lines.push("");
1524
+ lines.push(isTs
1525
+ ? "function writeMessage(payload: JsonRpcResponse | JsonRpcResponse[]): void {"
1526
+ : "function writeMessage(payload) {");
1527
+ lines.push(' process.stdout.write(JSON.stringify(payload) + "\\n");');
1528
+ lines.push("}");
1529
+ lines.push("");
1530
+ lines.push(isTs
1531
+ ? "async function processLine(line: string): Promise<void> {"
1532
+ : "async function processLine(line) {");
1533
+ lines.push(" const trimmed = line.trim();");
1534
+ lines.push(" if (!trimmed) return;");
1535
+ lines.push(" let msg" + (isTs ? ": unknown" : "") + ";");
1536
+ lines.push(" try {");
1537
+ lines.push(" msg = JSON.parse(trimmed);");
1538
+ lines.push(" } catch (err" + (isTs ? ": unknown" : "") + ") {");
1539
+ lines.push(' writeMessage({ jsonrpc: "2.0", id: null, error: { code: PARSE_ERROR, message: "Parse error: " + toErrorMessage(err) } });');
1540
+ lines.push(" return;");
1541
+ lines.push(" }");
1542
+ lines.push(" try {");
1543
+ lines.push(" const response = await handleMessage(msg);");
1544
+ lines.push(" if (response) writeMessage(response);");
1545
+ lines.push(" } catch (err" + (isTs ? ": unknown" : "") + ") {");
1546
+ lines.push(" const rec = isPlainObject(msg) ? msg : null;");
1547
+ lines.push(' const id' + (isTs ? ": string | number | null" : "") + ' = rec && (typeof rec.id === "string" || typeof rec.id === "number") ? rec.id : null;');
1548
+ lines.push(' writeMessage({ jsonrpc: "2.0", id, error: { code: INTERNAL_ERROR, message: "Internal error: " + toErrorMessage(err) } });');
1549
+ lines.push(" }");
1550
+ lines.push("}");
1551
+ lines.push("");
1552
+ lines.push("function startStdioServer()" + (isTs ? ": void" : "") + " {");
1553
+ lines.push(" const rl = readline.createInterface({");
1554
+ lines.push(" input: process.stdin,");
1555
+ lines.push(" crlfDelay: Infinity,");
1556
+ lines.push(" terminal: false");
1557
+ lines.push(" });");
1558
+ lines.push(" let queue = Promise.resolve();");
1559
+ lines.push(' rl.on("line", (line' + (isTs ? ": string" : "") + ") => {");
1560
+ lines.push(" queue = queue.then(() => processLine(line)).catch((err" + (isTs ? ": unknown" : "") + ") => {");
1561
+ lines.push(' process.stderr.write("mcp-server error: " + toErrorMessage(err) + "\\n");');
1562
+ lines.push(" });");
1563
+ lines.push(" });");
1564
+ lines.push("}");
1565
+ lines.push("");
1566
+ lines.push("startStdioServer();");
1567
+ lines.push("");
1568
+ return lines.join("\n");
1569
+ }
1570
+ /**
1571
+ * Compile visible HTTP and CLI invariants from a v0.2 contract into a standalone,
1572
+ * zero-dependency runnable stdio JSON-RPC 2.0 MCP server.
1573
+ */
1574
+ export function exportMcpServer(contract, options = {}) {
1575
+ if (!isRecord(contract)) {
1576
+ throw new VibecodeError("CONTRACT_INVALID", "exportMcpServer requires a valid contract object.");
1577
+ }
1578
+ const format = options.format ?? "node-mjs";
1579
+ if (!VALID_FORMATS.has(format)) {
1580
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported MCP server export format "${String(format)}". Expected "node-mjs" or "ts".`);
1581
+ }
1582
+ const includeHttp = options.includeHttp !== false;
1583
+ const includeCli = options.includeCli !== false;
1584
+ const includeSkippedComments = options.includeSkippedComments !== false;
1585
+ const targetName = isRecord(contract.target) && typeof contract.target.name === "string" && contract.target.name.trim()
1586
+ ? contract.target.name.trim()
1587
+ : DEFAULT_SERVER_NAME;
1588
+ const serverName = sanitizeServerName(options.serverName ?? targetName);
1589
+ const title = sanitizeSingleLineText(options.title ?? `${targetName} MCP Server`, 120) || "MCP Server";
1590
+ const baseUrl = resolveBaseUrl(contract, options);
1591
+ const tools = [];
1592
+ const skippedIds = [];
1593
+ const warnings = [];
1594
+ const usedToolNames = new Set();
1595
+ const invariants = Array.isArray(contract.invariants) ? contract.invariants : [];
1596
+ for (const inv of invariants) {
1597
+ if (!isRecord(inv))
1598
+ continue;
1599
+ // Holdout invariants MUST remain completely invisible: no tools, comments, counts, or warnings.
1600
+ if (inv.holdout === true) {
1601
+ continue;
1602
+ }
1603
+ const invId = typeof inv.id === "string" && inv.id.trim()
1604
+ ? sanitizeSingleLineText(inv.id.trim(), 80)
1605
+ : "unknown";
1606
+ if (inv.type === "http") {
1607
+ if (!includeHttp) {
1608
+ skippedIds.push(invId);
1609
+ continue;
1610
+ }
1611
+ const normalized = normalizeHttpInvariant(inv, usedToolNames);
1612
+ if (!normalized) {
1613
+ skippedIds.push(invId);
1614
+ warnings.push(`Skipped HTTP invariant "${invId}" due to unsupported HTTP method.`);
1615
+ continue;
1616
+ }
1617
+ tools.push(normalized);
1618
+ continue;
1619
+ }
1620
+ if (inv.type === "command") {
1621
+ if (!includeCli) {
1622
+ skippedIds.push(invId);
1623
+ continue;
1624
+ }
1625
+ const normalized = normalizeCliInvariant(inv, contract, usedToolNames);
1626
+ if (!normalized) {
1627
+ skippedIds.push(invId);
1628
+ warnings.push(`Skipped CLI invariant "${invId}" because no safe CLI executable could be resolved.`);
1629
+ continue;
1630
+ }
1631
+ tools.push(normalized);
1632
+ continue;
1633
+ }
1634
+ skippedIds.push(invId);
1635
+ }
1636
+ if (tools.length === 0) {
1637
+ warnings.push("No visible HTTP or CLI invariants exported; generated empty MCP server scaffold.");
1638
+ }
1639
+ const content = emitMcpServerCode({
1640
+ format,
1641
+ title,
1642
+ serverName,
1643
+ baseUrl,
1644
+ tools,
1645
+ skippedIds,
1646
+ includeSkippedComments
1647
+ });
1648
+ return {
1649
+ format,
1650
+ suggestedFilename: suggestedFilenameFor(format),
1651
+ content,
1652
+ exportedCount: tools.length,
1653
+ skippedCount: skippedIds.length,
1654
+ warnings,
1655
+ toolNames: tools.map((t) => t.name),
1656
+ baseUrl
1657
+ };
1658
+ }
1659
+ /**
1660
+ * Generate and atomically write a standalone stdio MCP server file to disk via temp file + rename.
1661
+ */
1662
+ export function writeMcpServer(contract, outPath, options = {}) {
1663
+ if (typeof outPath !== "string" || !outPath.trim() || outPath.includes("\0")) {
1664
+ throw new VibecodeError("CONTRACT_INVALID", "writeMcpServer requires a valid non-empty outPath without NUL bytes.");
1665
+ }
1666
+ const trimmedPath = outPath.trim();
1667
+ const resolvedOut = path.resolve(trimmedPath);
1668
+ if (fs.existsSync(resolvedOut) && fs.statSync(resolvedOut).isDirectory()) {
1669
+ throw new VibecodeError("CONTRACT_INVALID", "writeMcpServer outPath must point to a file, not a directory.");
1670
+ }
1671
+ const result = exportMcpServer(contract, options);
1672
+ const parentDir = path.dirname(resolvedOut);
1673
+ fs.mkdirSync(parentDir, { recursive: true });
1674
+ const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
1675
+ try {
1676
+ fs.writeFileSync(tmpPath, result.content, "utf8");
1677
+ fs.renameSync(tmpPath, resolvedOut);
1678
+ }
1679
+ catch (err) {
1680
+ try {
1681
+ if (fs.existsSync(tmpPath)) {
1682
+ fs.rmSync(tmpPath, { force: true });
1683
+ }
1684
+ }
1685
+ catch {
1686
+ // ignore cleanup error
1687
+ }
1688
+ throw err;
1689
+ }
1690
+ return {
1691
+ ...result,
1692
+ outPath: resolvedOut
1693
+ };
1694
+ }
1695
+ function style(text, codes, useColor) {
1696
+ return useColor ? `${codes}${text}${ANSI.reset}` : text;
1697
+ }
1698
+ /**
1699
+ * Render a pure ASCII/ANSI terminal summary for an MCP server export with zero raw secrets or vault paths.
1700
+ */
1701
+ export function formatPrettyMcpExport(result, outPath, color = false) {
1702
+ const useColor = color === true;
1703
+ const lines = [];
1704
+ const banner = style("[MCP SERVER]", `${ANSI.bold}${ANSI.cyan}`, useColor);
1705
+ const fmt = style(sanitizeSingleLineText(result.format, 32), ANSI.bold, useColor);
1706
+ const filename = sanitizeSingleLineText(result.suggestedFilename, 64);
1707
+ lines.push(`${banner} ${fmt} (${filename})`);
1708
+ const safeBaseUrl = sanitizeBaseUrl(result.baseUrl) ?? sanitizeSingleLineText(result.baseUrl, 160);
1709
+ lines.push(`Base URL: ${safeBaseUrl}`);
1710
+ const effectiveOutPath = outPath ?? result.outPath;
1711
+ if (typeof effectiveOutPath === "string" && effectiveOutPath.trim()) {
1712
+ lines.push(`Output: ${sanitizeSingleLineText(effectiveOutPath, 240)}`);
1713
+ }
1714
+ const countText = style(`${result.exportedCount} ${result.exportedCount === 1 ? "tool" : "tools"}`, result.exportedCount > 0 ? ANSI.green : ANSI.yellow, useColor);
1715
+ const summaryParts = [countText];
1716
+ if (result.skippedCount > 0) {
1717
+ summaryParts.push(`${result.skippedCount} skipped`);
1718
+ }
1719
+ lines.push(`Summary: ${summaryParts.join(", ")}`);
1720
+ if (Array.isArray(result.toolNames) && result.toolNames.length > 0) {
1721
+ const maxShown = 16;
1722
+ const shown = result.toolNames.slice(0, maxShown).map((t) => sanitizeSingleLineText(t, 64));
1723
+ const suffix = result.toolNames.length > maxShown
1724
+ ? `, ... (+${result.toolNames.length - maxShown} more)`
1725
+ : "";
1726
+ lines.push(`Tools: ${shown.join(", ")}${suffix}`);
1727
+ }
1728
+ if (Array.isArray(result.warnings) && result.warnings.length > 0) {
1729
+ lines.push("Warnings:");
1730
+ for (const warning of result.warnings.slice(0, 10)) {
1731
+ const cleanWarning = sanitizeSingleLineText(warning, 200);
1732
+ lines.push(` - ${style(cleanWarning, ANSI.yellow, useColor)}`);
1733
+ }
1734
+ }
1735
+ return lines.join("\n");
1736
+ }