codexmate 0.0.27 → 0.0.28

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 (137) hide show
  1. package/README.md +421 -421
  2. package/README.zh.md +354 -354
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +375 -375
  6. package/cli/builtin-proxy.js +1620 -1299
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/openai-bridge.js +1489 -1091
  13. package/cli/openclaw-config.js +629 -629
  14. package/cli/session-convert-args.js +65 -65
  15. package/cli/session-convert-io.js +82 -82
  16. package/cli/session-convert.js +43 -43
  17. package/cli/session-usage.concurrent.js +28 -28
  18. package/cli/session-usage.js +118 -118
  19. package/cli/session-usage.models.js +176 -176
  20. package/cli/skills.js +1141 -1141
  21. package/cli/zip-commands.js +510 -510
  22. package/cli.js +15264 -15251
  23. package/lib/automation.js +404 -404
  24. package/lib/cli-file-utils.js +151 -151
  25. package/lib/cli-models-utils.js +440 -379
  26. package/lib/cli-network-utils.js +190 -190
  27. package/lib/cli-path-utils.js +85 -85
  28. package/lib/cli-session-utils.js +121 -121
  29. package/lib/cli-sessions.js +417 -417
  30. package/lib/cli-utils.js +155 -155
  31. package/lib/download-artifacts.js +92 -92
  32. package/lib/mcp-stdio.js +453 -453
  33. package/lib/task-orchestrator.js +869 -869
  34. package/lib/text-diff.js +303 -303
  35. package/lib/workflow-engine.js +340 -340
  36. package/package.json +3 -1
  37. package/plugins/README.md +20 -20
  38. package/plugins/README.zh-CN.md +20 -20
  39. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  40. package/plugins/prompt-templates/computed.mjs +253 -253
  41. package/plugins/prompt-templates/index.mjs +8 -8
  42. package/plugins/prompt-templates/manifest.mjs +15 -15
  43. package/plugins/prompt-templates/methods.mjs +553 -619
  44. package/plugins/prompt-templates/overview.mjs +91 -90
  45. package/plugins/prompt-templates/ownership.mjs +19 -19
  46. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  47. package/plugins/prompt-templates/storage.mjs +64 -64
  48. package/plugins/registry.mjs +16 -16
  49. package/web-ui/app.js +625 -634
  50. package/web-ui/index.html +35 -35
  51. package/web-ui/logic.agents-diff.mjs +386 -386
  52. package/web-ui/logic.claude.mjs +168 -168
  53. package/web-ui/logic.codex.mjs +56 -0
  54. package/web-ui/logic.mjs +5 -5
  55. package/web-ui/logic.runtime.mjs +128 -128
  56. package/web-ui/logic.session-convert.mjs +70 -70
  57. package/web-ui/logic.sessions.mjs +765 -765
  58. package/web-ui/modules/api.mjs +90 -90
  59. package/web-ui/modules/app.computed.dashboard.mjs +225 -171
  60. package/web-ui/modules/app.computed.index.mjs +17 -17
  61. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  62. package/web-ui/modules/app.computed.session.mjs +994 -994
  63. package/web-ui/modules/app.constants.mjs +15 -15
  64. package/web-ui/modules/app.methods.agents.mjs +632 -632
  65. package/web-ui/modules/app.methods.claude-config.mjs +190 -184
  66. package/web-ui/modules/app.methods.codex-config.mjs +892 -860
  67. package/web-ui/modules/app.methods.index.mjs +92 -92
  68. package/web-ui/modules/app.methods.install.mjs +205 -205
  69. package/web-ui/modules/app.methods.navigation.mjs +743 -743
  70. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  71. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  72. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  73. package/web-ui/modules/app.methods.providers.mjs +412 -404
  74. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  75. package/web-ui/modules/app.methods.session-actions.mjs +593 -596
  76. package/web-ui/modules/app.methods.session-browser.mjs +984 -989
  77. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  78. package/web-ui/modules/app.methods.session-trash.mjs +439 -439
  79. package/web-ui/modules/app.methods.startup-claude.mjs +533 -526
  80. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  81. package/web-ui/modules/config-mode.computed.mjs +124 -124
  82. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  83. package/web-ui/modules/i18n.dict.mjs +2109 -2131
  84. package/web-ui/modules/i18n.mjs +56 -56
  85. package/web-ui/modules/plugins.computed.mjs +3 -3
  86. package/web-ui/modules/plugins.methods.mjs +3 -3
  87. package/web-ui/modules/plugins.storage.mjs +11 -11
  88. package/web-ui/modules/provider-url-display.mjs +17 -0
  89. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  90. package/web-ui/modules/skills.computed.mjs +107 -107
  91. package/web-ui/modules/skills.methods.mjs +481 -481
  92. package/web-ui/partials/index/layout-footer.html +13 -13
  93. package/web-ui/partials/index/layout-header.html +475 -475
  94. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  95. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  96. package/web-ui/partials/index/modal-health-check.html +45 -45
  97. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  98. package/web-ui/partials/index/modal-skills.html +200 -200
  99. package/web-ui/partials/index/modals-basic.html +165 -165
  100. package/web-ui/partials/index/panel-config-claude.html +188 -187
  101. package/web-ui/partials/index/panel-config-codex.html +312 -283
  102. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  103. package/web-ui/partials/index/panel-dashboard.html +186 -186
  104. package/web-ui/partials/index/panel-docs.html +147 -147
  105. package/web-ui/partials/index/panel-market.html +177 -177
  106. package/web-ui/partials/index/panel-orchestration.html +391 -391
  107. package/web-ui/partials/index/panel-plugins.html +253 -279
  108. package/web-ui/partials/index/panel-sessions.html +316 -326
  109. package/web-ui/partials/index/panel-settings.html +253 -274
  110. package/web-ui/partials/index/panel-usage.html +371 -371
  111. package/web-ui/res/json5.min.js +1 -1
  112. package/web-ui/res/vue.global.prod.js +13 -13
  113. package/web-ui/session-helpers.mjs +576 -576
  114. package/web-ui/source-bundle.cjs +233 -233
  115. package/web-ui/styles/base-theme.css +281 -268
  116. package/web-ui/styles/controls-forms.css +422 -423
  117. package/web-ui/styles/dashboard.css +274 -274
  118. package/web-ui/styles/docs-panel.css +247 -247
  119. package/web-ui/styles/feedback.css +108 -108
  120. package/web-ui/styles/health-check-dialog.css +144 -144
  121. package/web-ui/styles/layout-shell.css +606 -603
  122. package/web-ui/styles/modals-core.css +466 -464
  123. package/web-ui/styles/navigation-panels.css +391 -390
  124. package/web-ui/styles/openclaw-structured.css +266 -266
  125. package/web-ui/styles/plugins-panel.css +523 -523
  126. package/web-ui/styles/responsive.css +454 -454
  127. package/web-ui/styles/sessions-list.css +419 -415
  128. package/web-ui/styles/sessions-preview.css +411 -411
  129. package/web-ui/styles/sessions-toolbar-trash.css +330 -330
  130. package/web-ui/styles/sessions-usage.css +1040 -1040
  131. package/web-ui/styles/settings-panel.css +185 -185
  132. package/web-ui/styles/skills-list.css +303 -303
  133. package/web-ui/styles/skills-market.css +406 -406
  134. package/web-ui/styles/task-orchestration.css +822 -822
  135. package/web-ui/styles/titles-cards.css +472 -408
  136. package/web-ui/styles.css +21 -21
  137. package/web-ui.html +17 -17
package/lib/mcp-stdio.js CHANGED
@@ -1,453 +1,453 @@
1
- const DEFAULT_PROTOCOL_VERSION = '2025-11-25';
2
-
3
- function jsonRpcError(code, message, data) {
4
- const error = {
5
- code,
6
- message: String(message || 'Unknown error')
7
- };
8
- if (data !== undefined) {
9
- error.data = data;
10
- }
11
- return error;
12
- }
13
-
14
- function createToolMap(tools = []) {
15
- const map = new Map();
16
- for (const tool of Array.isArray(tools) ? tools : []) {
17
- if (!tool || typeof tool !== 'object') continue;
18
- const name = typeof tool.name === 'string' ? tool.name.trim() : '';
19
- if (!name) continue;
20
- map.set(name, {
21
- name,
22
- description: typeof tool.description === 'string' ? tool.description : '',
23
- inputSchema: tool.inputSchema && typeof tool.inputSchema === 'object'
24
- ? tool.inputSchema
25
- : { type: 'object', properties: {}, additionalProperties: false },
26
- annotations: tool.annotations && typeof tool.annotations === 'object' ? tool.annotations : undefined,
27
- handler: typeof tool.handler === 'function' ? tool.handler : async () => ({})
28
- });
29
- }
30
- return map;
31
- }
32
-
33
- function createResourceMap(resources = []) {
34
- const map = new Map();
35
- for (const resource of Array.isArray(resources) ? resources : []) {
36
- if (!resource || typeof resource !== 'object') continue;
37
- const uri = typeof resource.uri === 'string' ? resource.uri.trim() : '';
38
- if (!uri) continue;
39
- map.set(uri, {
40
- uri,
41
- name: typeof resource.name === 'string' ? resource.name : uri,
42
- description: typeof resource.description === 'string' ? resource.description : '',
43
- mimeType: typeof resource.mimeType === 'string' ? resource.mimeType : 'application/json',
44
- read: typeof resource.read === 'function'
45
- ? resource.read
46
- : async () => ({ contents: [] })
47
- });
48
- }
49
- return map;
50
- }
51
-
52
- function createPromptMap(prompts = []) {
53
- const map = new Map();
54
- for (const prompt of Array.isArray(prompts) ? prompts : []) {
55
- if (!prompt || typeof prompt !== 'object') continue;
56
- const name = typeof prompt.name === 'string' ? prompt.name.trim() : '';
57
- if (!name) continue;
58
- map.set(name, {
59
- name,
60
- description: typeof prompt.description === 'string' ? prompt.description : '',
61
- arguments: Array.isArray(prompt.arguments) ? prompt.arguments : [],
62
- get: typeof prompt.get === 'function'
63
- ? prompt.get
64
- : async () => ({ messages: [] })
65
- });
66
- }
67
- return map;
68
- }
69
-
70
- function createMcpRequestRouter(options = {}) {
71
- const protocolVersion = typeof options.protocolVersion === 'string' && options.protocolVersion.trim()
72
- ? options.protocolVersion.trim()
73
- : DEFAULT_PROTOCOL_VERSION;
74
- const serverInfo = options.serverInfo && typeof options.serverInfo === 'object'
75
- ? options.serverInfo
76
- : { name: 'mcp-server', version: '0.0.0' };
77
- const logger = typeof options.logger === 'function' ? options.logger : () => {};
78
-
79
- const tools = createToolMap(options.tools);
80
- const resources = createResourceMap(options.resources);
81
- const prompts = createPromptMap(options.prompts);
82
-
83
- const listTools = () => Array.from(tools.values()).map((tool) => ({
84
- name: tool.name,
85
- description: tool.description,
86
- inputSchema: tool.inputSchema,
87
- ...(tool.annotations ? { annotations: tool.annotations } : {})
88
- }));
89
-
90
- const listResources = () => Array.from(resources.values()).map((resource) => ({
91
- uri: resource.uri,
92
- name: resource.name,
93
- description: resource.description,
94
- mimeType: resource.mimeType
95
- }));
96
-
97
- const listPrompts = () => Array.from(prompts.values()).map((prompt) => ({
98
- name: prompt.name,
99
- description: prompt.description,
100
- arguments: prompt.arguments
101
- }));
102
-
103
- const capabilities = {};
104
- if (tools.size > 0) {
105
- capabilities.tools = { listChanged: false };
106
- }
107
- if (resources.size > 0) {
108
- capabilities.resources = { listChanged: false, subscribe: false };
109
- }
110
- if (prompts.size > 0) {
111
- capabilities.prompts = { listChanged: false };
112
- }
113
-
114
- const withToolError = (error) => ({
115
- content: [{ type: 'text', text: `Error: ${error.message || error}` }],
116
- isError: true
117
- });
118
-
119
- const normalizeResourceResult = (uri, resource, result) => {
120
- if (result && Array.isArray(result.contents)) {
121
- return { contents: result.contents };
122
- }
123
- if (result && typeof result === 'object' && typeof result.text === 'string') {
124
- return {
125
- contents: [{
126
- uri,
127
- mimeType: result.mimeType || resource.mimeType,
128
- text: result.text
129
- }]
130
- };
131
- }
132
- const text = typeof result === 'string'
133
- ? result
134
- : JSON.stringify(result === undefined ? {} : result, null, 2);
135
- return {
136
- contents: [{
137
- uri,
138
- mimeType: resource.mimeType,
139
- text
140
- }]
141
- };
142
- };
143
-
144
- const resolveResourceByUri = (uri) => {
145
- const exact = resources.get(uri);
146
- if (exact) {
147
- return exact;
148
- }
149
- try {
150
- const parsed = new URL(uri);
151
- parsed.search = '';
152
- parsed.hash = '';
153
- const baseUri = parsed.toString();
154
- if (baseUri && resources.has(baseUri)) {
155
- return resources.get(baseUri);
156
- }
157
- } catch (_) {}
158
- return null;
159
- };
160
-
161
- const handleRequest = async (request) => {
162
- if (!request || typeof request !== 'object') {
163
- throw jsonRpcError(-32600, 'Invalid Request');
164
- }
165
- const method = typeof request.method === 'string' ? request.method : '';
166
- const params = request.params && typeof request.params === 'object' ? request.params : {};
167
-
168
- if (method === 'initialize') {
169
- return {
170
- protocolVersion,
171
- capabilities,
172
- serverInfo: {
173
- name: serverInfo.name || 'codexmate-mcp',
174
- version: serverInfo.version || '0.0.0'
175
- }
176
- };
177
- }
178
-
179
- if (method === 'ping') {
180
- return {};
181
- }
182
-
183
- if (method === 'tools/list') {
184
- return { tools: listTools() };
185
- }
186
-
187
- if (method === 'tools/call') {
188
- const name = typeof params.name === 'string' ? params.name.trim() : '';
189
- if (!name) {
190
- throw jsonRpcError(-32602, 'Missing tool name');
191
- }
192
- const tool = tools.get(name);
193
- if (!tool) {
194
- throw jsonRpcError(-32602, `Unknown tool: ${name}`);
195
- }
196
- try {
197
- const args = params.arguments && typeof params.arguments === 'object'
198
- ? params.arguments
199
- : {};
200
- const result = await tool.handler(args, request);
201
- if (result && Array.isArray(result.content)) {
202
- return result;
203
- }
204
- return {
205
- content: [{
206
- type: 'text',
207
- text: JSON.stringify(result === undefined ? {} : result, null, 2)
208
- }],
209
- structuredContent: result === undefined ? {} : result
210
- };
211
- } catch (error) {
212
- logger('error', `tools/call failed (${name}): ${error && error.message ? error.message : error}`);
213
- return withToolError(error || new Error('Tool execution failed'));
214
- }
215
- }
216
-
217
- if (method === 'resources/list') {
218
- return { resources: listResources() };
219
- }
220
-
221
- if (method === 'resources/read') {
222
- const uri = typeof params.uri === 'string' ? params.uri.trim() : '';
223
- if (!uri) {
224
- throw jsonRpcError(-32602, 'Missing resource uri');
225
- }
226
- const resource = resolveResourceByUri(uri);
227
- if (!resource) {
228
- throw jsonRpcError(-32602, `Unknown resource: ${uri}`);
229
- }
230
- try {
231
- const result = await resource.read(params, request);
232
- return normalizeResourceResult(uri, resource, result);
233
- } catch (error) {
234
- throw jsonRpcError(-32000, `Resource read failed: ${error && error.message ? error.message : error}`);
235
- }
236
- }
237
-
238
- if (method === 'prompts/list') {
239
- return { prompts: listPrompts() };
240
- }
241
-
242
- if (method === 'prompts/get') {
243
- const name = typeof params.name === 'string' ? params.name.trim() : '';
244
- if (!name) {
245
- throw jsonRpcError(-32602, 'Missing prompt name');
246
- }
247
- const prompt = prompts.get(name);
248
- if (!prompt) {
249
- throw jsonRpcError(-32602, `Unknown prompt: ${name}`);
250
- }
251
- try {
252
- const args = params.arguments && typeof params.arguments === 'object'
253
- ? params.arguments
254
- : {};
255
- const result = await prompt.get(args, request);
256
- return {
257
- description: prompt.description,
258
- messages: Array.isArray(result && result.messages) ? result.messages : []
259
- };
260
- } catch (error) {
261
- throw jsonRpcError(-32000, `Prompt get failed: ${error && error.message ? error.message : error}`);
262
- }
263
- }
264
-
265
- if (method === 'notifications/initialized') {
266
- return null;
267
- }
268
-
269
- throw jsonRpcError(-32601, `Method not found: ${method}`);
270
- };
271
-
272
- return {
273
- handleRequest
274
- };
275
- }
276
-
277
- function createMcpStdioServer(options = {}) {
278
- const logger = typeof options.logger === 'function' ? options.logger : () => {};
279
- const stdin = options.stdin || process.stdin;
280
- const stdout = options.stdout || process.stdout;
281
- const router = createMcpRequestRouter(options);
282
- const jsonRpcVersion = '2.0';
283
- const maxFrameBytes = Number.isFinite(options.maxFrameBytes) && options.maxFrameBytes > 0
284
- ? Math.floor(options.maxFrameBytes)
285
- : 16 * 1024 * 1024;
286
-
287
- let buffer = Buffer.alloc(0);
288
- let started = false;
289
- let stopped = false;
290
-
291
- const writeMessage = (payload) => {
292
- const text = JSON.stringify(payload);
293
- const body = Buffer.from(text, 'utf-8');
294
- const header = Buffer.from(`Content-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n`, 'utf-8');
295
- stdout.write(Buffer.concat([header, body]));
296
- };
297
-
298
- const writeResponse = (id, result) => {
299
- writeMessage({
300
- jsonrpc: jsonRpcVersion,
301
- id,
302
- result
303
- });
304
- };
305
-
306
- const writeError = (id, error) => {
307
- const normalized = error && typeof error === 'object' && Number.isFinite(error.code)
308
- ? error
309
- : jsonRpcError(-32000, error && error.message ? error.message : String(error || 'Unknown error'));
310
- writeMessage({
311
- jsonrpc: jsonRpcVersion,
312
- id,
313
- error: normalized
314
- });
315
- };
316
-
317
- const processMessage = async (rawText) => {
318
- let message = null;
319
- try {
320
- message = JSON.parse(rawText);
321
- } catch (error) {
322
- writeError(null, jsonRpcError(-32700, 'Parse error'));
323
- return;
324
- }
325
-
326
- if (!message || typeof message !== 'object') {
327
- writeError(null, jsonRpcError(-32600, 'Invalid Request'));
328
- return;
329
- }
330
-
331
- if (Array.isArray(message)) {
332
- writeError(null, jsonRpcError(-32600, 'Batch request is not supported'));
333
- return;
334
- }
335
-
336
- const hasMethod = typeof message.method === 'string' && message.method.trim().length > 0;
337
- const hasId = Object.prototype.hasOwnProperty.call(message, 'id');
338
-
339
- if (!hasMethod) {
340
- if (hasId) {
341
- writeError(message.id, jsonRpcError(-32600, 'Invalid Request'));
342
- } else {
343
- writeError(null, jsonRpcError(-32600, 'Invalid Request'));
344
- }
345
- return;
346
- }
347
-
348
- try {
349
- const result = await router.handleRequest(message);
350
- if (hasId) {
351
- writeResponse(message.id, result === null ? {} : result);
352
- }
353
- } catch (error) {
354
- if (hasId) {
355
- writeError(message.id, error);
356
- } else {
357
- logger('error', `MCP notification handling failed: ${error && error.message ? error.message : error}`);
358
- }
359
- }
360
- };
361
-
362
- const parseBuffer = async () => {
363
- while (buffer.length > 0) {
364
- const headerEnd = buffer.indexOf('\r\n\r\n');
365
- if (headerEnd < 0) {
366
- return;
367
- }
368
-
369
- const headerText = buffer.slice(0, headerEnd).toString('utf-8');
370
- const headers = {};
371
- for (const line of headerText.split('\r\n')) {
372
- const idx = line.indexOf(':');
373
- if (idx <= 0) continue;
374
- const key = line.slice(0, idx).trim().toLowerCase();
375
- const value = line.slice(idx + 1).trim();
376
- headers[key] = value;
377
- }
378
-
379
- const length = Number.parseInt(headers['content-length'] || '', 10);
380
- if (!Number.isFinite(length) || length < 0) {
381
- buffer = Buffer.alloc(0);
382
- writeError(null, jsonRpcError(-32600, 'Invalid Content-Length header'));
383
- return;
384
- }
385
- if (length > maxFrameBytes) {
386
- buffer = Buffer.alloc(0);
387
- writeError(null, jsonRpcError(-32600, 'Content-Length too large'));
388
- return;
389
- }
390
-
391
- const bodyOffset = headerEnd + 4;
392
- const frameLength = bodyOffset + length;
393
- if (buffer.length < frameLength) {
394
- return;
395
- }
396
-
397
- const body = buffer.slice(bodyOffset, frameLength);
398
- buffer = buffer.slice(frameLength);
399
- await processMessage(body.toString('utf-8'));
400
- }
401
- };
402
-
403
- const onData = async (chunk) => {
404
- if (stopped) return;
405
- if (chunk && (buffer.length + chunk.length) > (maxFrameBytes + 64 * 1024)) {
406
- buffer = Buffer.alloc(0);
407
- writeError(null, jsonRpcError(-32600, 'Frame too large'));
408
- return;
409
- }
410
- buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]);
411
- try {
412
- await parseBuffer();
413
- } catch (error) {
414
- logger('error', `MCP stdio parse failed: ${error && error.message ? error.message : error}`);
415
- writeError(null, jsonRpcError(-32000, 'Internal parse failure'));
416
- }
417
- };
418
-
419
- const onError = (error) => {
420
- logger('error', `MCP stdio stream error: ${error && error.message ? error.message : error}`);
421
- };
422
-
423
- const start = () => {
424
- if (started || stopped) return;
425
- started = true;
426
- stdin.on('data', onData);
427
- stdin.on('error', onError);
428
- stdout.on('error', onError);
429
- if (stdin.isTTY) {
430
- stdin.resume();
431
- }
432
- };
433
-
434
- const stop = () => {
435
- if (stopped) return;
436
- stopped = true;
437
- stdin.removeListener('data', onData);
438
- stdin.removeListener('error', onError);
439
- stdout.removeListener('error', onError);
440
- };
441
-
442
- return {
443
- start,
444
- stop
445
- };
446
- }
447
-
448
- module.exports = {
449
- DEFAULT_PROTOCOL_VERSION,
450
- jsonRpcError,
451
- createMcpRequestRouter,
452
- createMcpStdioServer
453
- };
1
+ const DEFAULT_PROTOCOL_VERSION = '2025-11-25';
2
+
3
+ function jsonRpcError(code, message, data) {
4
+ const error = {
5
+ code,
6
+ message: String(message || 'Unknown error')
7
+ };
8
+ if (data !== undefined) {
9
+ error.data = data;
10
+ }
11
+ return error;
12
+ }
13
+
14
+ function createToolMap(tools = []) {
15
+ const map = new Map();
16
+ for (const tool of Array.isArray(tools) ? tools : []) {
17
+ if (!tool || typeof tool !== 'object') continue;
18
+ const name = typeof tool.name === 'string' ? tool.name.trim() : '';
19
+ if (!name) continue;
20
+ map.set(name, {
21
+ name,
22
+ description: typeof tool.description === 'string' ? tool.description : '',
23
+ inputSchema: tool.inputSchema && typeof tool.inputSchema === 'object'
24
+ ? tool.inputSchema
25
+ : { type: 'object', properties: {}, additionalProperties: false },
26
+ annotations: tool.annotations && typeof tool.annotations === 'object' ? tool.annotations : undefined,
27
+ handler: typeof tool.handler === 'function' ? tool.handler : async () => ({})
28
+ });
29
+ }
30
+ return map;
31
+ }
32
+
33
+ function createResourceMap(resources = []) {
34
+ const map = new Map();
35
+ for (const resource of Array.isArray(resources) ? resources : []) {
36
+ if (!resource || typeof resource !== 'object') continue;
37
+ const uri = typeof resource.uri === 'string' ? resource.uri.trim() : '';
38
+ if (!uri) continue;
39
+ map.set(uri, {
40
+ uri,
41
+ name: typeof resource.name === 'string' ? resource.name : uri,
42
+ description: typeof resource.description === 'string' ? resource.description : '',
43
+ mimeType: typeof resource.mimeType === 'string' ? resource.mimeType : 'application/json',
44
+ read: typeof resource.read === 'function'
45
+ ? resource.read
46
+ : async () => ({ contents: [] })
47
+ });
48
+ }
49
+ return map;
50
+ }
51
+
52
+ function createPromptMap(prompts = []) {
53
+ const map = new Map();
54
+ for (const prompt of Array.isArray(prompts) ? prompts : []) {
55
+ if (!prompt || typeof prompt !== 'object') continue;
56
+ const name = typeof prompt.name === 'string' ? prompt.name.trim() : '';
57
+ if (!name) continue;
58
+ map.set(name, {
59
+ name,
60
+ description: typeof prompt.description === 'string' ? prompt.description : '',
61
+ arguments: Array.isArray(prompt.arguments) ? prompt.arguments : [],
62
+ get: typeof prompt.get === 'function'
63
+ ? prompt.get
64
+ : async () => ({ messages: [] })
65
+ });
66
+ }
67
+ return map;
68
+ }
69
+
70
+ function createMcpRequestRouter(options = {}) {
71
+ const protocolVersion = typeof options.protocolVersion === 'string' && options.protocolVersion.trim()
72
+ ? options.protocolVersion.trim()
73
+ : DEFAULT_PROTOCOL_VERSION;
74
+ const serverInfo = options.serverInfo && typeof options.serverInfo === 'object'
75
+ ? options.serverInfo
76
+ : { name: 'mcp-server', version: '0.0.0' };
77
+ const logger = typeof options.logger === 'function' ? options.logger : () => {};
78
+
79
+ const tools = createToolMap(options.tools);
80
+ const resources = createResourceMap(options.resources);
81
+ const prompts = createPromptMap(options.prompts);
82
+
83
+ const listTools = () => Array.from(tools.values()).map((tool) => ({
84
+ name: tool.name,
85
+ description: tool.description,
86
+ inputSchema: tool.inputSchema,
87
+ ...(tool.annotations ? { annotations: tool.annotations } : {})
88
+ }));
89
+
90
+ const listResources = () => Array.from(resources.values()).map((resource) => ({
91
+ uri: resource.uri,
92
+ name: resource.name,
93
+ description: resource.description,
94
+ mimeType: resource.mimeType
95
+ }));
96
+
97
+ const listPrompts = () => Array.from(prompts.values()).map((prompt) => ({
98
+ name: prompt.name,
99
+ description: prompt.description,
100
+ arguments: prompt.arguments
101
+ }));
102
+
103
+ const capabilities = {};
104
+ if (tools.size > 0) {
105
+ capabilities.tools = { listChanged: false };
106
+ }
107
+ if (resources.size > 0) {
108
+ capabilities.resources = { listChanged: false, subscribe: false };
109
+ }
110
+ if (prompts.size > 0) {
111
+ capabilities.prompts = { listChanged: false };
112
+ }
113
+
114
+ const withToolError = (error) => ({
115
+ content: [{ type: 'text', text: `Error: ${error.message || error}` }],
116
+ isError: true
117
+ });
118
+
119
+ const normalizeResourceResult = (uri, resource, result) => {
120
+ if (result && Array.isArray(result.contents)) {
121
+ return { contents: result.contents };
122
+ }
123
+ if (result && typeof result === 'object' && typeof result.text === 'string') {
124
+ return {
125
+ contents: [{
126
+ uri,
127
+ mimeType: result.mimeType || resource.mimeType,
128
+ text: result.text
129
+ }]
130
+ };
131
+ }
132
+ const text = typeof result === 'string'
133
+ ? result
134
+ : JSON.stringify(result === undefined ? {} : result, null, 2);
135
+ return {
136
+ contents: [{
137
+ uri,
138
+ mimeType: resource.mimeType,
139
+ text
140
+ }]
141
+ };
142
+ };
143
+
144
+ const resolveResourceByUri = (uri) => {
145
+ const exact = resources.get(uri);
146
+ if (exact) {
147
+ return exact;
148
+ }
149
+ try {
150
+ const parsed = new URL(uri);
151
+ parsed.search = '';
152
+ parsed.hash = '';
153
+ const baseUri = parsed.toString();
154
+ if (baseUri && resources.has(baseUri)) {
155
+ return resources.get(baseUri);
156
+ }
157
+ } catch (_) {}
158
+ return null;
159
+ };
160
+
161
+ const handleRequest = async (request) => {
162
+ if (!request || typeof request !== 'object') {
163
+ throw jsonRpcError(-32600, 'Invalid Request');
164
+ }
165
+ const method = typeof request.method === 'string' ? request.method : '';
166
+ const params = request.params && typeof request.params === 'object' ? request.params : {};
167
+
168
+ if (method === 'initialize') {
169
+ return {
170
+ protocolVersion,
171
+ capabilities,
172
+ serverInfo: {
173
+ name: serverInfo.name || 'codexmate-mcp',
174
+ version: serverInfo.version || '0.0.0'
175
+ }
176
+ };
177
+ }
178
+
179
+ if (method === 'ping') {
180
+ return {};
181
+ }
182
+
183
+ if (method === 'tools/list') {
184
+ return { tools: listTools() };
185
+ }
186
+
187
+ if (method === 'tools/call') {
188
+ const name = typeof params.name === 'string' ? params.name.trim() : '';
189
+ if (!name) {
190
+ throw jsonRpcError(-32602, 'Missing tool name');
191
+ }
192
+ const tool = tools.get(name);
193
+ if (!tool) {
194
+ throw jsonRpcError(-32602, `Unknown tool: ${name}`);
195
+ }
196
+ try {
197
+ const args = params.arguments && typeof params.arguments === 'object'
198
+ ? params.arguments
199
+ : {};
200
+ const result = await tool.handler(args, request);
201
+ if (result && Array.isArray(result.content)) {
202
+ return result;
203
+ }
204
+ return {
205
+ content: [{
206
+ type: 'text',
207
+ text: JSON.stringify(result === undefined ? {} : result, null, 2)
208
+ }],
209
+ structuredContent: result === undefined ? {} : result
210
+ };
211
+ } catch (error) {
212
+ logger('error', `tools/call failed (${name}): ${error && error.message ? error.message : error}`);
213
+ return withToolError(error || new Error('Tool execution failed'));
214
+ }
215
+ }
216
+
217
+ if (method === 'resources/list') {
218
+ return { resources: listResources() };
219
+ }
220
+
221
+ if (method === 'resources/read') {
222
+ const uri = typeof params.uri === 'string' ? params.uri.trim() : '';
223
+ if (!uri) {
224
+ throw jsonRpcError(-32602, 'Missing resource uri');
225
+ }
226
+ const resource = resolveResourceByUri(uri);
227
+ if (!resource) {
228
+ throw jsonRpcError(-32602, `Unknown resource: ${uri}`);
229
+ }
230
+ try {
231
+ const result = await resource.read(params, request);
232
+ return normalizeResourceResult(uri, resource, result);
233
+ } catch (error) {
234
+ throw jsonRpcError(-32000, `Resource read failed: ${error && error.message ? error.message : error}`);
235
+ }
236
+ }
237
+
238
+ if (method === 'prompts/list') {
239
+ return { prompts: listPrompts() };
240
+ }
241
+
242
+ if (method === 'prompts/get') {
243
+ const name = typeof params.name === 'string' ? params.name.trim() : '';
244
+ if (!name) {
245
+ throw jsonRpcError(-32602, 'Missing prompt name');
246
+ }
247
+ const prompt = prompts.get(name);
248
+ if (!prompt) {
249
+ throw jsonRpcError(-32602, `Unknown prompt: ${name}`);
250
+ }
251
+ try {
252
+ const args = params.arguments && typeof params.arguments === 'object'
253
+ ? params.arguments
254
+ : {};
255
+ const result = await prompt.get(args, request);
256
+ return {
257
+ description: prompt.description,
258
+ messages: Array.isArray(result && result.messages) ? result.messages : []
259
+ };
260
+ } catch (error) {
261
+ throw jsonRpcError(-32000, `Prompt get failed: ${error && error.message ? error.message : error}`);
262
+ }
263
+ }
264
+
265
+ if (method === 'notifications/initialized') {
266
+ return null;
267
+ }
268
+
269
+ throw jsonRpcError(-32601, `Method not found: ${method}`);
270
+ };
271
+
272
+ return {
273
+ handleRequest
274
+ };
275
+ }
276
+
277
+ function createMcpStdioServer(options = {}) {
278
+ const logger = typeof options.logger === 'function' ? options.logger : () => {};
279
+ const stdin = options.stdin || process.stdin;
280
+ const stdout = options.stdout || process.stdout;
281
+ const router = createMcpRequestRouter(options);
282
+ const jsonRpcVersion = '2.0';
283
+ const maxFrameBytes = Number.isFinite(options.maxFrameBytes) && options.maxFrameBytes > 0
284
+ ? Math.floor(options.maxFrameBytes)
285
+ : 16 * 1024 * 1024;
286
+
287
+ let buffer = Buffer.alloc(0);
288
+ let started = false;
289
+ let stopped = false;
290
+
291
+ const writeMessage = (payload) => {
292
+ const text = JSON.stringify(payload);
293
+ const body = Buffer.from(text, 'utf-8');
294
+ const header = Buffer.from(`Content-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n`, 'utf-8');
295
+ stdout.write(Buffer.concat([header, body]));
296
+ };
297
+
298
+ const writeResponse = (id, result) => {
299
+ writeMessage({
300
+ jsonrpc: jsonRpcVersion,
301
+ id,
302
+ result
303
+ });
304
+ };
305
+
306
+ const writeError = (id, error) => {
307
+ const normalized = error && typeof error === 'object' && Number.isFinite(error.code)
308
+ ? error
309
+ : jsonRpcError(-32000, error && error.message ? error.message : String(error || 'Unknown error'));
310
+ writeMessage({
311
+ jsonrpc: jsonRpcVersion,
312
+ id,
313
+ error: normalized
314
+ });
315
+ };
316
+
317
+ const processMessage = async (rawText) => {
318
+ let message = null;
319
+ try {
320
+ message = JSON.parse(rawText);
321
+ } catch (error) {
322
+ writeError(null, jsonRpcError(-32700, 'Parse error'));
323
+ return;
324
+ }
325
+
326
+ if (!message || typeof message !== 'object') {
327
+ writeError(null, jsonRpcError(-32600, 'Invalid Request'));
328
+ return;
329
+ }
330
+
331
+ if (Array.isArray(message)) {
332
+ writeError(null, jsonRpcError(-32600, 'Batch request is not supported'));
333
+ return;
334
+ }
335
+
336
+ const hasMethod = typeof message.method === 'string' && message.method.trim().length > 0;
337
+ const hasId = Object.prototype.hasOwnProperty.call(message, 'id');
338
+
339
+ if (!hasMethod) {
340
+ if (hasId) {
341
+ writeError(message.id, jsonRpcError(-32600, 'Invalid Request'));
342
+ } else {
343
+ writeError(null, jsonRpcError(-32600, 'Invalid Request'));
344
+ }
345
+ return;
346
+ }
347
+
348
+ try {
349
+ const result = await router.handleRequest(message);
350
+ if (hasId) {
351
+ writeResponse(message.id, result === null ? {} : result);
352
+ }
353
+ } catch (error) {
354
+ if (hasId) {
355
+ writeError(message.id, error);
356
+ } else {
357
+ logger('error', `MCP notification handling failed: ${error && error.message ? error.message : error}`);
358
+ }
359
+ }
360
+ };
361
+
362
+ const parseBuffer = async () => {
363
+ while (buffer.length > 0) {
364
+ const headerEnd = buffer.indexOf('\r\n\r\n');
365
+ if (headerEnd < 0) {
366
+ return;
367
+ }
368
+
369
+ const headerText = buffer.slice(0, headerEnd).toString('utf-8');
370
+ const headers = {};
371
+ for (const line of headerText.split('\r\n')) {
372
+ const idx = line.indexOf(':');
373
+ if (idx <= 0) continue;
374
+ const key = line.slice(0, idx).trim().toLowerCase();
375
+ const value = line.slice(idx + 1).trim();
376
+ headers[key] = value;
377
+ }
378
+
379
+ const length = Number.parseInt(headers['content-length'] || '', 10);
380
+ if (!Number.isFinite(length) || length < 0) {
381
+ buffer = Buffer.alloc(0);
382
+ writeError(null, jsonRpcError(-32600, 'Invalid Content-Length header'));
383
+ return;
384
+ }
385
+ if (length > maxFrameBytes) {
386
+ buffer = Buffer.alloc(0);
387
+ writeError(null, jsonRpcError(-32600, 'Content-Length too large'));
388
+ return;
389
+ }
390
+
391
+ const bodyOffset = headerEnd + 4;
392
+ const frameLength = bodyOffset + length;
393
+ if (buffer.length < frameLength) {
394
+ return;
395
+ }
396
+
397
+ const body = buffer.slice(bodyOffset, frameLength);
398
+ buffer = buffer.slice(frameLength);
399
+ await processMessage(body.toString('utf-8'));
400
+ }
401
+ };
402
+
403
+ const onData = async (chunk) => {
404
+ if (stopped) return;
405
+ if (chunk && (buffer.length + chunk.length) > (maxFrameBytes + 64 * 1024)) {
406
+ buffer = Buffer.alloc(0);
407
+ writeError(null, jsonRpcError(-32600, 'Frame too large'));
408
+ return;
409
+ }
410
+ buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]);
411
+ try {
412
+ await parseBuffer();
413
+ } catch (error) {
414
+ logger('error', `MCP stdio parse failed: ${error && error.message ? error.message : error}`);
415
+ writeError(null, jsonRpcError(-32000, 'Internal parse failure'));
416
+ }
417
+ };
418
+
419
+ const onError = (error) => {
420
+ logger('error', `MCP stdio stream error: ${error && error.message ? error.message : error}`);
421
+ };
422
+
423
+ const start = () => {
424
+ if (started || stopped) return;
425
+ started = true;
426
+ stdin.on('data', onData);
427
+ stdin.on('error', onError);
428
+ stdout.on('error', onError);
429
+ if (stdin.isTTY) {
430
+ stdin.resume();
431
+ }
432
+ };
433
+
434
+ const stop = () => {
435
+ if (stopped) return;
436
+ stopped = true;
437
+ stdin.removeListener('data', onData);
438
+ stdin.removeListener('error', onError);
439
+ stdout.removeListener('error', onError);
440
+ };
441
+
442
+ return {
443
+ start,
444
+ stop
445
+ };
446
+ }
447
+
448
+ module.exports = {
449
+ DEFAULT_PROTOCOL_VERSION,
450
+ jsonRpcError,
451
+ createMcpRequestRouter,
452
+ createMcpStdioServer
453
+ };