-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathserver.js
More file actions
421 lines (372 loc) · 12.7 KB
/
server.js
File metadata and controls
421 lines (372 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#!/usr/bin/env node
/**
* Interactive Feedback MCP Server - Node.js Implementation
* Compliant with MCP Specification and JSON-RPC 2.0
*
* Author: STMMO Project
* Version: 1.0.0
*/
// Load environment variables from .env file
// Ensure .env is loaded from the script directory, not the current working directory
const path = require('path');
const envPath = path.join(__dirname, '.env');
const dotenvResult = require('dotenv').config({ path: envPath });
// Debug logging for environment loading
if (dotenvResult.error) {
console.error('❌ Error loading .env file:', dotenvResult.error.message);
console.error(' Expected path:', envPath);
} else {
console.log('✅ Environment variables loaded from:', envPath);
console.log(' OPENAI_API_KEY exists:', !!process.env.OPENAI_API_KEY);
console.log(' WHISPER_LANGUAGE:', process.env.WHISPER_LANGUAGE || 'not set');
}
const fs = require('fs-extra');
const os = require('os');
const crypto = require('crypto');
const { spawn } = require('child_process');
/**
* Get first line from text
* @param {string} text - Input text
* @returns {string} First line trimmed
*/
function firstLine(text) {
if (!text || typeof text !== 'string') {
return '';
}
return text.split('\n')[0].trim();
}
/**
* Launch Web UI and wait for feedback result
* @param {string} projectDirectory - Project directory
* @param {string} summary - Request summary
* @returns {Promise<Object>} Feedback result from UI
*/
async function launchFeedbackUI(projectDirectory, summary) {
// Create temporary file for result
const tempDir = os.tmpdir();
const uuid = crypto.randomUUID();
const outputFile = path.join(tempDir, `feedback-${uuid}.json`);
try {
// Get path to web-ui.js
const scriptDir = __dirname;
const webUIPath = path.join(scriptDir, 'web-ui.js');
// Prepare arguments for web UI process
const args = [
webUIPath,
'--project-directory', projectDirectory,
'--prompt', summary,
'--output-file', outputFile
];
// Spawn Web UI process
const childProcess = spawn('node', args, {
stdio: ['ignore', 'ignore', 'ignore'],
detached: false
});
// Wait for process completion
await new Promise((resolve, reject) => {
childProcess.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Web UI process exited with code ${code}`));
}
});
childProcess.on('error', (error) => {
reject(error);
});
});
// Read result from temp file
const result = await fs.readJson(outputFile);
// Cleanup temp file
await fs.unlink(outputFile);
return result;
} catch (error) {
// Cleanup temp file if error occurs
try {
await fs.unlink(outputFile);
} catch (cleanupError) {
// Ignore cleanup errors
}
throw error;
}
}
/**
* Wrapper function for interactive feedback
* @param {string} projectDirectory - Project directory
* @param {string} summary - Request summary
* @returns {Promise<Object>} Feedback result
*/
async function interactiveFeedback(projectDirectory, summary) {
// Validate OPENAI_API_KEY before proceeding
if (!process.env.OPENAI_API_KEY) {
const error = new Error('OpenAI API key not configured. Please set OPENAI_API_KEY in your .env file.');
console.error('❌ API Key Validation Failed:', error.message);
console.error(' Expected .env path:', path.join(__dirname, '.env'));
console.error(' Current working directory:', process.cwd());
console.error(' Script directory (__dirname):', __dirname);
throw error;
}
// Validate API key format
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey.startsWith('sk-') || apiKey.length < 20) {
const error = new Error('Invalid OpenAI API key format. Key should start with "sk-" and be at least 20 characters long.');
console.error('❌ API Key Format Validation Failed:', error.message);
console.error(' Key length:', apiKey.length);
console.error(' Key prefix:', apiKey.substring(0, 3));
throw error;
}
console.log('✅ API Key validation passed for interactive feedback');
// Apply firstLine only to projectDirectory to ensure it's a valid path
// Keep summary intact to preserve multi-line content
const cleanProjectDirectory = firstLine(projectDirectory);
const cleanSummary = summary || 'I implemented the changes you requested.';
return await launchFeedbackUI(cleanProjectDirectory, cleanSummary);
}
/**
* MCP Server Class
* Handles communication with AI assistants via MCP protocol
* Compliant with MCP Specification and JSON-RPC 2.0
*/
class MCPServer {
constructor() {
this.initialized = false;
this.clientCapabilities = null;
// Initialize tools object with interactive_feedback tool
this.tools = {
interactive_feedback: {
description: 'Request interactive feedback for a given project directory and summary',
inputSchema: {
type: 'object',
properties: {
project_directory: {
type: 'string',
description: 'Path to the project directory'
},
summary: {
type: 'string',
description: 'Summary of the request or context'
}
},
required: ['project_directory', 'summary']
},
handler: interactiveFeedback
}
};
// Server capabilities
this.serverCapabilities = {
tools: {
listChanged: false
}
};
// Server info
this.serverInfo = {
name: 'interactive-feedback-mcp',
version: '1.0.0'
};
}
/**
* Launch MCP Server
*/
run() {
// Setup stdin encoding
process.stdin.setEncoding('utf8');
// Listen for stdin data events
process.stdin.on('data', async (data) => {
try {
const lines = data.trim().split('\n');
for (const line of lines) {
if (line.trim()) {
const request = JSON.parse(line);
const response = await this.handleRequest(request);
if (response) {
this.sendMessage(response);
}
}
}
} catch (error) {
// Send error response
const errorResponse = {
jsonrpc: '2.0',
id: null,
error: {
code: -32700,
message: 'Parse error',
data: error.message
}
};
this.sendMessage(errorResponse);
}
});
// Handle process termination
process.on('SIGINT', () => {
process.exit(0);
});
process.on('SIGTERM', () => {
process.exit(0);
});
}
/**
* Send message to stdout
* @param {Object} message - Message to send
*/
sendMessage(message) {
console.log(JSON.stringify(message));
}
/**
* Handle MCP request
* @param {Object} request - MCP request object
* @returns {Object|null} MCP response object or null for notifications
*/
async handleRequest(request) {
try {
// Validate JSON-RPC 2.0 format
if (request.jsonrpc !== '2.0') {
return {
jsonrpc: '2.0',
id: request.id || null,
error: {
code: -32600,
message: 'Invalid Request',
data: 'Invalid JSON-RPC version'
}
};
}
switch (request.method) {
case 'initialize':
return this.handleInitialize(request);
case 'initialized':
// Notification - no response needed
this.initialized = true;
return null;
case 'tools/list':
return this.handleToolsList(request);
case 'tools/call':
return await this.handleToolsCall(request);
default:
return {
jsonrpc: '2.0',
id: request.id || null,
error: {
code: -32601,
message: 'Method not found',
data: `Unknown method: ${request.method}`
}
};
}
} catch (error) {
return {
jsonrpc: '2.0',
id: request.id || null,
error: {
code: -32603,
message: 'Internal error',
data: error.message
}
};
}
}
/**
* Handle initialize request
* @param {Object} request - Initialize request
* @returns {Object} Initialize response
*/
handleInitialize(request) {
const { params } = request;
// Store client capabilities
this.clientCapabilities = params.capabilities || {};
// Return server capabilities and info
return {
jsonrpc: '2.0',
id: request.id,
result: {
protocolVersion: '2024-11-05',
capabilities: this.serverCapabilities,
serverInfo: this.serverInfo
}
};
}
/**
* Handle tools/list request
* @param {Object} request - Tools list request
* @returns {Object} Tools list response
*/
handleToolsList(request) {
const tools = Object.keys(this.tools).map(name => ({
name,
description: this.tools[name].description,
inputSchema: this.tools[name].inputSchema
}));
return {
jsonrpc: '2.0',
id: request.id,
result: {
tools
}
};
}
/**
* Handle tools/call request
* @param {Object} request - Tools call request
* @returns {Object} Tools call response
*/
async handleToolsCall(request) {
const { name: toolName, arguments: toolArgs } = request.params;
// Validate tool exists
if (!this.tools[toolName]) {
return {
jsonrpc: '2.0',
id: request.id,
error: {
code: -32602,
message: 'Invalid params',
data: `Unknown tool: ${toolName}`
}
};
}
try {
// Call tool handler
const result = await this.tools[toolName].handler(
toolArgs.project_directory,
toolArgs.summary
);
// Return MCP response format
return {
jsonrpc: '2.0',
id: request.id,
result: {
content: [{
type: 'text',
text: JSON.stringify(result, null, 2)
}]
}
};
} catch (error) {
return {
jsonrpc: '2.0',
id: request.id,
error: {
code: -32603,
message: 'Internal error',
data: `Tool execution failed: ${error.message}`
}
};
}
}
}
// Command line interface
if (require.main === module) {
try {
const server = new MCPServer();
server.run();
} catch (error) {
console.error('Error starting MCP Server:', error.message);
process.exit(1);
}
}
// Module exports
module.exports = {
MCPServer,
interactiveFeedback,
launchFeedbackUI,
firstLine
};