devanvil 0.0.0-stage → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.ar.md +113 -0
  3. package/README.md +272 -2
  4. package/SECURITY.md +49 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +659 -0
  7. package/dist/core/contract-drift.d.ts +49 -0
  8. package/dist/core/contract-drift.js +302 -0
  9. package/dist/core/converters.d.ts +18 -0
  10. package/dist/core/converters.js +981 -0
  11. package/dist/core/cron.d.ts +33 -0
  12. package/dist/core/cron.js +306 -0
  13. package/dist/core/crypto.d.ts +59 -0
  14. package/dist/core/crypto.js +250 -0
  15. package/dist/core/curl.d.ts +17 -0
  16. package/dist/core/curl.js +170 -0
  17. package/dist/core/diff.d.ts +36 -0
  18. package/dist/core/diff.js +148 -0
  19. package/dist/core/encoding.d.ts +3 -0
  20. package/dist/core/encoding.js +143 -0
  21. package/dist/core/importers.d.ts +65 -0
  22. package/dist/core/importers.js +361 -0
  23. package/dist/core/jwt.d.ts +39 -0
  24. package/dist/core/jwt.js +256 -0
  25. package/dist/core/llm-tokens.d.ts +38 -0
  26. package/dist/core/llm-tokens.js +125 -0
  27. package/dist/core/log-analyzer.d.ts +30 -0
  28. package/dist/core/log-analyzer.js +155 -0
  29. package/dist/core/network.d.ts +72 -0
  30. package/dist/core/network.js +185 -0
  31. package/dist/core/oauth-protobuf.d.ts +74 -0
  32. package/dist/core/oauth-protobuf.js +390 -0
  33. package/dist/core/openapi.d.ts +27 -0
  34. package/dist/core/openapi.js +257 -0
  35. package/dist/core/pipeline.d.ts +28 -0
  36. package/dist/core/pipeline.js +154 -0
  37. package/dist/core/regex.d.ts +50 -0
  38. package/dist/core/regex.js +351 -0
  39. package/dist/core/runner.d.ts +53 -0
  40. package/dist/core/runner.js +250 -0
  41. package/dist/core/secrets.d.ts +87 -0
  42. package/dist/core/secrets.js +599 -0
  43. package/dist/core/security.d.ts +34 -0
  44. package/dist/core/security.js +284 -0
  45. package/dist/core/sql-explain.d.ts +50 -0
  46. package/dist/core/sql-explain.js +259 -0
  47. package/dist/core/tls.d.ts +44 -0
  48. package/dist/core/tls.js +166 -0
  49. package/dist/index.d.ts +31 -0
  50. package/dist/index.js +31 -0
  51. package/dist/server/app.d.ts +31 -0
  52. package/dist/server/app.js +348 -0
  53. package/dist/server/http-proxy.d.ts +55 -0
  54. package/dist/server/http-proxy.js +364 -0
  55. package/dist/server/http-utils.d.ts +28 -0
  56. package/dist/server/http-utils.js +106 -0
  57. package/dist/server/load-tester.d.ts +53 -0
  58. package/dist/server/load-tester.js +134 -0
  59. package/dist/server/mcp.d.ts +35 -0
  60. package/dist/server/mcp.js +466 -0
  61. package/dist/server/mock-store.d.ts +38 -0
  62. package/dist/server/mock-store.js +197 -0
  63. package/dist/server/plugin-loader.d.ts +60 -0
  64. package/dist/server/plugin-loader.js +285 -0
  65. package/dist/server/recorder-store.d.ts +35 -0
  66. package/dist/server/recorder-store.js +146 -0
  67. package/dist/server/routes/network-routes.d.ts +3 -0
  68. package/dist/server/routes/network-routes.js +391 -0
  69. package/dist/server/routes/tools-routes.d.ts +3 -0
  70. package/dist/server/routes/tools-routes.js +292 -0
  71. package/dist/server/routes/workspace-routes.d.ts +3 -0
  72. package/dist/server/routes/workspace-routes.js +240 -0
  73. package/dist/server/webhook-store.d.ts +29 -0
  74. package/dist/server/webhook-store.js +90 -0
  75. package/dist/server/workspace-store.d.ts +91 -0
  76. package/dist/server/workspace-store.js +447 -0
  77. package/dist/server/ws-probe.d.ts +34 -0
  78. package/dist/server/ws-probe.js +283 -0
  79. package/dist/ui/app.js +274 -0
  80. package/dist/ui/favicon.svg +14 -0
  81. package/dist/ui/index.html +83 -0
  82. package/dist/ui/logo.png +0 -0
  83. package/dist/ui/styles.css +694 -0
  84. package/dist/ui/tools-data.js +704 -0
  85. package/dist/ui/tools-network.js +727 -0
  86. package/dist/ui/tools-ops.js +295 -0
  87. package/dist/ui/tools-pro.js +500 -0
  88. package/dist/ui/tools-security.js +389 -0
  89. package/dist/ui/tools-v12.js +745 -0
  90. package/dist/ui/tools-v13.js +321 -0
  91. package/dist/ui/tools-v20.js +563 -0
  92. package/dist/ui/tools-v21.js +395 -0
  93. package/package.json +75 -4
@@ -0,0 +1,35 @@
1
+ export interface McpToolDefinition {
2
+ name: string;
3
+ description: string;
4
+ inputSchema: Record<string, unknown>;
5
+ }
6
+ export interface JsonRpcRequest {
7
+ jsonrpc: '2.0';
8
+ id?: string | number | null;
9
+ method: string;
10
+ params?: Record<string, unknown>;
11
+ }
12
+ export interface JsonRpcResponse {
13
+ jsonrpc: '2.0';
14
+ id: string | number | null;
15
+ result?: unknown;
16
+ error?: {
17
+ code: number;
18
+ message: string;
19
+ data?: unknown;
20
+ };
21
+ }
22
+ export declare const MCP_PROTOCOL_VERSION = "2024-11-05";
23
+ export declare const MCP_SERVER_VERSION = "2.1.0";
24
+ export declare const MCP_TOOLS: McpToolDefinition[];
25
+ export declare function executeMcpTool(name: string, rawArgs: Record<string, unknown> | undefined): unknown;
26
+ /**
27
+ * Pure JSON-RPC 2.0 dispatcher for DevAnvil MCP Server.
28
+ * Returns null for notifications (which must not emit a response per JSON-RPC 2.0).
29
+ */
30
+ export declare function handleMcpMessage(msg: JsonRpcRequest): JsonRpcResponse | null;
31
+ /**
32
+ * Starts DevAnvil as a zero-dependency MCP Server over stdio (newline-delimited JSON-RPC 2.0).
33
+ * Compatible with Claude Desktop, Claude Code, Cursor, Windsurf, and VS Code Copilot.
34
+ */
35
+ export declare function startMcpStdioServer(): void;
@@ -0,0 +1,466 @@
1
+ import * as readline from 'node:readline';
2
+ import { checkOpenApiContractDrift } from '../core/contract-drift.js';
3
+ import { convertData } from '../core/converters.js';
4
+ import { describeCron, getNextCronRuns } from '../core/cron.js';
5
+ import { generateApiKey, generateNanoId, generateUlid, generateUuidV4, generateUuidV7 } from '../core/crypto.js';
6
+ import { diffJsonSemantic, diffText } from '../core/diff.js';
7
+ import { decodeJwt, verifyJwt } from '../core/jwt.js';
8
+ import { analyzeLlmText, compactContextText } from '../core/llm-tokens.js';
9
+ import { analyzeLogs } from '../core/log-analyzer.js';
10
+ import { decodeProtobufWire } from '../core/oauth-protobuf.js';
11
+ import { openApiToMockRoutes, parseOpenApiSpec } from '../core/openapi.js';
12
+ import { testRegex } from '../core/regex.js';
13
+ import { analyzeEnvFile, formatSecretsAsSarif, scanDirectory, scanSecrets } from '../core/secrets.js';
14
+ import { safeJsonParse } from '../core/security.js';
15
+ import { analyzeSqlExplain } from '../core/sql-explain.js';
16
+ import { inspectPemCertificates } from '../core/tls.js';
17
+ export const MCP_PROTOCOL_VERSION = '2024-11-05';
18
+ export const MCP_SERVER_VERSION = '2.1.0';
19
+ export const MCP_TOOLS = [
20
+ {
21
+ name: 'devanvil_scan_secrets',
22
+ description: 'Scan text, code, diffs, or logs offline for leaked secrets (18 provider rules + Shannon entropy) and return safe redacted output.',
23
+ inputSchema: {
24
+ type: 'object',
25
+ properties: {
26
+ input: { type: 'string', description: 'Raw text, code, or log snippet to scan.' },
27
+ checkHighEntropy: { type: 'boolean', description: 'Enable Shannon entropy scan for unknown secret assignments (default true).' },
28
+ },
29
+ required: ['input'],
30
+ },
31
+ },
32
+ {
33
+ name: 'devanvil_scan_directory',
34
+ description: 'Recursively scan a local directory for leaked secrets (respects .gitignore, skips binaries/node_modules) and optionally return SARIF 2.1.0.',
35
+ inputSchema: {
36
+ type: 'object',
37
+ properties: {
38
+ directory: { type: 'string', description: 'Path to directory or file to scan.' },
39
+ sarif: { type: 'boolean', description: 'Return SARIF 2.1.0 JSON format for GitHub Code Scanning.' },
40
+ },
41
+ required: ['directory'],
42
+ },
43
+ },
44
+ {
45
+ name: 'devanvil_check_env',
46
+ description: 'Validate a .env file for duplicate keys, unquoted spaces, syntax errors, and missing keys compared to .env.example.',
47
+ inputSchema: {
48
+ type: 'object',
49
+ properties: {
50
+ env: { type: 'string', description: 'Contents of .env file.' },
51
+ example: { type: 'string', description: 'Optional contents of .env.example schema.' },
52
+ },
53
+ required: ['env'],
54
+ },
55
+ },
56
+ {
57
+ name: 'devanvil_openapi_to_mocks',
58
+ description: 'Parse an OpenAPI 3.x / Swagger 2.0 YAML or JSON spec (circular-$ref safe) and synthesize realistic Mock routes and cURL snippets.',
59
+ inputSchema: {
60
+ type: 'object',
61
+ properties: {
62
+ spec: { type: 'string', description: 'OpenAPI YAML or JSON document.' },
63
+ },
64
+ required: ['spec'],
65
+ },
66
+ },
67
+ {
68
+ name: 'devanvil_jwt_audit',
69
+ description: 'Decode a JWT offline, run an automated security audit (alg:none, missing exp, expired, sensitive claims), and optionally verify HS/RS/ES signature.',
70
+ inputSchema: {
71
+ type: 'object',
72
+ properties: {
73
+ token: { type: 'string', description: 'Compact JWT string (header.payload.signature).' },
74
+ secretOrKey: { type: 'string', description: 'Optional HMAC secret or PEM public key to cryptographically verify.' },
75
+ algorithms: { type: 'array', items: { type: 'string' }, description: 'Optional algorithm allowlist (e.g. ["HS256"]).' },
76
+ },
77
+ required: ['token'],
78
+ },
79
+ },
80
+ {
81
+ name: 'devanvil_regex_test',
82
+ description: 'Analyze a regular expression for catastrophic ReDoS risk statically and execute it inside an isolated 250ms node:vm sandbox.',
83
+ inputSchema: {
84
+ type: 'object',
85
+ properties: {
86
+ pattern: { type: 'string', description: 'Regex pattern.' },
87
+ flags: { type: 'string', description: 'Regex flags (default "g").' },
88
+ text: { type: 'string', description: 'Test text to run the pattern against.' },
89
+ },
90
+ required: ['pattern', 'text'],
91
+ },
92
+ },
93
+ {
94
+ name: 'devanvil_convert_data',
95
+ description: 'Convert structured data between json, yaml, toml, csv, query, typescript interfaces, and json-schema offline.',
96
+ inputSchema: {
97
+ type: 'object',
98
+ properties: {
99
+ input: { type: 'string', description: 'Input data text.' },
100
+ from: { type: 'string', enum: ['json', 'yaml', 'toml', 'csv', 'query'] },
101
+ to: { type: 'string', enum: ['json', 'json-minified', 'yaml', 'toml', 'csv', 'query', 'typescript', 'json-schema'] },
102
+ },
103
+ required: ['input', 'from', 'to'],
104
+ },
105
+ },
106
+ {
107
+ name: 'devanvil_semantic_diff',
108
+ description: 'Compute order-independent Semantic JSON Structural Diff or line-by-line LCS diff between two payloads.',
109
+ inputSchema: {
110
+ type: 'object',
111
+ properties: {
112
+ left: { type: 'string', description: 'Original text or JSON.' },
113
+ right: { type: 'string', description: 'Modified text or JSON.' },
114
+ mode: { type: 'string', enum: ['json', 'text'], description: 'Diff mode (default "json").' },
115
+ },
116
+ required: ['left', 'right'],
117
+ },
118
+ },
119
+ {
120
+ name: 'devanvil_llm_tokens',
121
+ description: 'Estimate offline BPE tokens & multi-model API costs across English/Arabic/CJK/code, and optionally compact redundant whitespace/comments.',
122
+ inputSchema: {
123
+ type: 'object',
124
+ properties: {
125
+ input: { type: 'string', description: 'Prompt or context text.' },
126
+ compact: { type: 'boolean', description: 'Also run Smart Context Compactor.' },
127
+ stripLineComments: { type: 'boolean', description: 'Strip // and # comments when compacting.' },
128
+ },
129
+ required: ['input'],
130
+ },
131
+ },
132
+ {
133
+ name: 'devanvil_generate_id',
134
+ description: 'Generate CSPRNG identifiers offline: RFC 9562 sortable UUIDv7, UUIDv4, ULID, NanoID, or prefixed API keys.',
135
+ inputSchema: {
136
+ type: 'object',
137
+ properties: {
138
+ kind: { type: 'string', enum: ['uuidv7', 'uuidv4', 'ulid', 'nanoid', 'apikey'] },
139
+ count: { type: 'number', description: 'Number of IDs to generate (1-50, default 5).' },
140
+ prefix: { type: 'string', description: 'Prefix for apikey kind (default "da_live").' },
141
+ },
142
+ required: ['kind'],
143
+ },
144
+ },
145
+ {
146
+ name: 'devanvil_cron_explain',
147
+ description: 'Describe a 5-field or 6-field Cron expression in plain English and compute the next UTC scheduled runs.',
148
+ inputSchema: {
149
+ type: 'object',
150
+ properties: {
151
+ expression: { type: 'string', description: 'Cron expression (e.g. "0 9 * * MON-FRI" or "@daily").' },
152
+ count: { type: 'number', description: 'How many upcoming UTC runs to compute (1-25, default 5).' },
153
+ },
154
+ required: ['expression'],
155
+ },
156
+ },
157
+ {
158
+ name: 'devanvil_inspect_cert',
159
+ description: 'Inspect one or more PEM-encoded X.509 SSL/TLS certificates completely offline (subject, issuer, SANs, expiry, warnings, SHA-256 fingerprint).',
160
+ inputSchema: {
161
+ type: 'object',
162
+ properties: {
163
+ pem: { type: 'string', description: 'PEM certificate string containing -----BEGIN CERTIFICATE-----.' },
164
+ },
165
+ required: ['pem'],
166
+ },
167
+ },
168
+ {
169
+ name: 'devanvil_explain_sql',
170
+ description: 'Analyze PostgreSQL EXPLAIN (ANALYZE, FORMAT JSON) or SQLite EXPLAIN QUERY PLAN output offline to compute exclusive node times and detect bottlenecks (Seq Scan, Disk Sort, Cardinality Drift).',
171
+ inputSchema: {
172
+ type: 'object',
173
+ properties: {
174
+ input: { type: 'string', description: 'PostgreSQL EXPLAIN JSON or SQLite EXPLAIN QUERY PLAN text.' },
175
+ },
176
+ required: ['input'],
177
+ },
178
+ },
179
+ {
180
+ name: 'devanvil_analyze_logs',
181
+ description: 'Analyze NDJSON/JSONL or text application/server logs offline: level breakdown, HTTP status classes, latency P50/P95/P99, deduplicated error fingerprints, and leaked secret count.',
182
+ inputSchema: {
183
+ type: 'object',
184
+ properties: {
185
+ input: { type: 'string', description: 'Raw log lines (NDJSON, Pino, Winston, Nginx, or plain text).' },
186
+ },
187
+ required: ['input'],
188
+ },
189
+ },
190
+ {
191
+ name: 'devanvil_check_contract_drift',
192
+ description: 'Validate a real API response (method, path, HTTP status, JSON body) against an OpenAPI 3.x / Swagger 2.0 contract to detect breaking schema drift, missing required fields, type/enum/format mismatches, and undocumented fields.',
193
+ inputSchema: {
194
+ type: 'object',
195
+ properties: {
196
+ spec: { type: 'string', description: 'OpenAPI 3.x or Swagger 2.0 YAML/JSON specification.' },
197
+ method: { type: 'string', description: 'HTTP method (GET, POST, PUT, DELETE, etc.).' },
198
+ path: { type: 'string', description: 'Actual request path (e.g. /pets/42).' },
199
+ status: { type: 'number', description: 'Actual HTTP status code (e.g. 200).' },
200
+ body: { type: 'string', description: 'Actual JSON response body string.' },
201
+ },
202
+ required: ['spec', 'method', 'path', 'status', 'body'],
203
+ },
204
+ },
205
+ {
206
+ name: 'devanvil_decode_protobuf',
207
+ description: 'Decode raw Protobuf binary wire payloads (hex or base64) offline without external tools, with optional .proto schema mapping for named fields and ZigZag/float/double/nested message decoding.',
208
+ inputSchema: {
209
+ type: 'object',
210
+ properties: {
211
+ input: { type: 'string', description: 'Raw Protobuf payload encoded as hex or base64.' },
212
+ protoSchema: { type: 'string', description: 'Optional .proto message schema text to map field numbers to names & types.' },
213
+ messageName: { type: 'string', description: 'Optional root message name in protoSchema.' },
214
+ },
215
+ required: ['input'],
216
+ },
217
+ },
218
+ ];
219
+ function reqString(args, key) {
220
+ const val = args[key];
221
+ if (typeof val !== 'string') {
222
+ throw new Error(`Argument "${key}" must be a string`);
223
+ }
224
+ return val;
225
+ }
226
+ export function executeMcpTool(name, rawArgs) {
227
+ const args = rawArgs ?? {};
228
+ switch (name) {
229
+ case 'devanvil_scan_secrets':
230
+ return scanSecrets(reqString(args, 'input'), {
231
+ checkHighEntropy: args.checkHighEntropy !== false,
232
+ });
233
+ case 'devanvil_scan_directory': {
234
+ const scan = scanDirectory(reqString(args, 'directory'));
235
+ if (args.sarif === true) {
236
+ return formatSecretsAsSarif(scan.findings, MCP_SERVER_VERSION);
237
+ }
238
+ return scan;
239
+ }
240
+ case 'devanvil_check_env':
241
+ return analyzeEnvFile(reqString(args, 'env'), typeof args.example === 'string' ? args.example : undefined);
242
+ case 'devanvil_openapi_to_mocks': {
243
+ const parsed = parseOpenApiSpec(reqString(args, 'spec'));
244
+ return { spec: parsed, mockRoutes: openApiToMockRoutes(parsed) };
245
+ }
246
+ case 'devanvil_jwt_audit': {
247
+ const token = reqString(args, 'token');
248
+ const decoded = decodeJwt(token);
249
+ if (typeof args.secretOrKey === 'string' && args.secretOrKey.length > 0) {
250
+ const algs = Array.isArray(args.algorithms)
251
+ ? args.algorithms.filter((a) => typeof a === 'string')
252
+ : undefined;
253
+ return { decoded, verification: verifyJwt(token, args.secretOrKey, algs ? { allowedAlgorithms: algs } : undefined) };
254
+ }
255
+ return decoded;
256
+ }
257
+ case 'devanvil_regex_test':
258
+ return testRegex(reqString(args, 'pattern'), typeof args.flags === 'string' ? args.flags : 'g', reqString(args, 'text'));
259
+ case 'devanvil_convert_data':
260
+ return {
261
+ output: convertData(reqString(args, 'input'), reqString(args, 'from'), reqString(args, 'to')),
262
+ };
263
+ case 'devanvil_semantic_diff': {
264
+ const left = reqString(args, 'left');
265
+ const right = reqString(args, 'right');
266
+ return args.mode === 'text' ? diffText(left, right) : diffJsonSemantic(left, right);
267
+ }
268
+ case 'devanvil_llm_tokens': {
269
+ const text = reqString(args, 'input');
270
+ const analysis = analyzeLlmText(text);
271
+ if (args.compact === true) {
272
+ return {
273
+ analysis,
274
+ compaction: compactContextText(text, {
275
+ stripLineComments: args.stripLineComments === true,
276
+ }),
277
+ };
278
+ }
279
+ return analysis;
280
+ }
281
+ case 'devanvil_generate_id': {
282
+ const kind = reqString(args, 'kind');
283
+ const count = Math.min(Math.max(typeof args.count === 'number' ? Math.trunc(args.count) : 5, 1), 50);
284
+ const ids = [];
285
+ for (let i = 0; i < count; i++) {
286
+ if (kind === 'uuidv7')
287
+ ids.push(generateUuidV7());
288
+ else if (kind === 'uuidv4')
289
+ ids.push(generateUuidV4());
290
+ else if (kind === 'ulid')
291
+ ids.push(generateUlid());
292
+ else if (kind === 'nanoid')
293
+ ids.push(generateNanoId(21));
294
+ else if (kind === 'apikey')
295
+ ids.push(generateApiKey(typeof args.prefix === 'string' ? args.prefix : 'da_live'));
296
+ else
297
+ throw new Error(`Unsupported ID kind "${kind}"`);
298
+ }
299
+ return { kind, count: ids.length, ids };
300
+ }
301
+ case 'devanvil_cron_explain': {
302
+ const expr = reqString(args, 'expression');
303
+ const count = Math.min(Math.max(typeof args.count === 'number' ? Math.trunc(args.count) : 5, 1), 25);
304
+ return {
305
+ expression: expr,
306
+ description: describeCron(expr),
307
+ nextRunsUtc: getNextCronRuns(expr, count),
308
+ };
309
+ }
310
+ case 'devanvil_inspect_cert': {
311
+ const certs = inspectPemCertificates(reqString(args, 'pem'));
312
+ return { count: certs.length, certificates: certs };
313
+ }
314
+ case 'devanvil_explain_sql':
315
+ return analyzeSqlExplain(reqString(args, 'input'));
316
+ case 'devanvil_analyze_logs':
317
+ return analyzeLogs(reqString(args, 'input'));
318
+ case 'devanvil_check_contract_drift':
319
+ return checkOpenApiContractDrift({
320
+ spec: reqString(args, 'spec'),
321
+ method: reqString(args, 'method'),
322
+ path: reqString(args, 'path'),
323
+ status: typeof args.status === 'number' ? args.status : 200,
324
+ body: reqString(args, 'body'),
325
+ });
326
+ case 'devanvil_decode_protobuf':
327
+ return decodeProtobufWire(reqString(args, 'input'), {
328
+ protoSchema: typeof args.protoSchema === 'string' ? args.protoSchema : undefined,
329
+ messageName: typeof args.messageName === 'string' ? args.messageName : undefined,
330
+ });
331
+ default:
332
+ throw new Error(`Unknown MCP tool: "${name}"`);
333
+ }
334
+ }
335
+ /**
336
+ * Pure JSON-RPC 2.0 dispatcher for DevAnvil MCP Server.
337
+ * Returns null for notifications (which must not emit a response per JSON-RPC 2.0).
338
+ */
339
+ export function handleMcpMessage(msg) {
340
+ const isNotification = msg.id === undefined;
341
+ const id = msg.id ?? null;
342
+ if (msg.method === 'notifications/initialized' || msg.method === 'notifications/cancelled') {
343
+ return null;
344
+ }
345
+ try {
346
+ if (msg.method === 'initialize') {
347
+ return {
348
+ jsonrpc: '2.0',
349
+ id,
350
+ result: {
351
+ protocolVersion: MCP_PROTOCOL_VERSION,
352
+ capabilities: { tools: {} },
353
+ serverInfo: {
354
+ name: 'devanvil',
355
+ version: MCP_SERVER_VERSION,
356
+ },
357
+ },
358
+ };
359
+ }
360
+ if (msg.method === 'ping') {
361
+ return { jsonrpc: '2.0', id, result: {} };
362
+ }
363
+ if (msg.method === 'tools/list') {
364
+ return {
365
+ jsonrpc: '2.0',
366
+ id,
367
+ result: { tools: MCP_TOOLS },
368
+ };
369
+ }
370
+ if (msg.method === 'tools/call') {
371
+ const params = msg.params ?? {};
372
+ const toolName = typeof params.name === 'string' ? params.name : '';
373
+ const toolArgs = params.arguments && typeof params.arguments === 'object' && !Array.isArray(params.arguments)
374
+ ? params.arguments
375
+ : {};
376
+ try {
377
+ const result = executeMcpTool(toolName, toolArgs);
378
+ return {
379
+ jsonrpc: '2.0',
380
+ id,
381
+ result: {
382
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
383
+ isError: false,
384
+ },
385
+ };
386
+ }
387
+ catch (toolErr) {
388
+ const message = toolErr instanceof Error ? toolErr.message : String(toolErr);
389
+ return {
390
+ jsonrpc: '2.0',
391
+ id,
392
+ result: {
393
+ content: [{ type: 'text', text: `Error: ${message}` }],
394
+ isError: true,
395
+ },
396
+ };
397
+ }
398
+ }
399
+ if (isNotification)
400
+ return null;
401
+ return {
402
+ jsonrpc: '2.0',
403
+ id,
404
+ error: { code: -32601, message: `Method not found: ${msg.method}` },
405
+ };
406
+ }
407
+ catch (err) {
408
+ if (isNotification)
409
+ return null;
410
+ return {
411
+ jsonrpc: '2.0',
412
+ id,
413
+ error: { code: -32603, message: err instanceof Error ? err.message : String(err) },
414
+ };
415
+ }
416
+ }
417
+ /**
418
+ * Starts DevAnvil as a zero-dependency MCP Server over stdio (newline-delimited JSON-RPC 2.0).
419
+ * Compatible with Claude Desktop, Claude Code, Cursor, Windsurf, and VS Code Copilot.
420
+ */
421
+ export function startMcpStdioServer() {
422
+ const rl = readline.createInterface({
423
+ input: process.stdin,
424
+ crlfDelay: Infinity,
425
+ });
426
+ rl.on('line', (rawLine) => {
427
+ const line = rawLine.trim();
428
+ if (!line)
429
+ return;
430
+ if (Buffer.byteLength(line, 'utf8') > 4 * 1024 * 1024) {
431
+ const resp = {
432
+ jsonrpc: '2.0',
433
+ id: null,
434
+ error: { code: -32600, message: 'Message exceeds 4 MB limit' },
435
+ };
436
+ process.stdout.write(`${JSON.stringify(resp)}\n`);
437
+ return;
438
+ }
439
+ let parsed;
440
+ try {
441
+ parsed = safeJsonParse(line);
442
+ }
443
+ catch {
444
+ const resp = {
445
+ jsonrpc: '2.0',
446
+ id: null,
447
+ error: { code: -32700, message: 'Parse error: invalid JSON' },
448
+ };
449
+ process.stdout.write(`${JSON.stringify(resp)}\n`);
450
+ return;
451
+ }
452
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.method !== 'string') {
453
+ const resp = {
454
+ jsonrpc: '2.0',
455
+ id: parsed && 'id' in parsed ? (parsed.id ?? null) : null,
456
+ error: { code: -32600, message: 'Invalid JSON-RPC request' },
457
+ };
458
+ process.stdout.write(`${JSON.stringify(resp)}\n`);
459
+ return;
460
+ }
461
+ const response = handleMcpMessage(parsed);
462
+ if (response) {
463
+ process.stdout.write(`${JSON.stringify(response)}\n`);
464
+ }
465
+ });
466
+ }
@@ -0,0 +1,38 @@
1
+ export interface MockRoute {
2
+ id: string;
3
+ method: string;
4
+ path: string;
5
+ status: number;
6
+ headers: Record<string, string>;
7
+ body: string;
8
+ delayMs: number;
9
+ enabled: boolean;
10
+ hits: number;
11
+ createdAt: string;
12
+ }
13
+ export interface MockRouteInput {
14
+ method?: string;
15
+ path: string;
16
+ status?: number;
17
+ headers?: Record<string, string>;
18
+ body?: string;
19
+ delayMs?: number;
20
+ enabled?: boolean;
21
+ }
22
+ export declare class MockStore {
23
+ private routes;
24
+ constructor(seedDefaults?: boolean);
25
+ list(): MockRoute[];
26
+ create(input: MockRouteInput): MockRoute;
27
+ update(id: string, patch: Partial<MockRouteInput>): MockRoute;
28
+ delete(id: string): boolean;
29
+ clear(): void;
30
+ importRoutes(inputs: MockRouteInput[], replace?: boolean): MockRoute[];
31
+ totalHits(): number;
32
+ match(method: string, relativePath: string, query: Record<string, string>): {
33
+ route: MockRoute;
34
+ renderedBody: string;
35
+ params: Record<string, string>;
36
+ } | null;
37
+ private interpolateTemplate;
38
+ }