-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.ts
More file actions
304 lines (256 loc) · 8.78 KB
/
server.ts
File metadata and controls
304 lines (256 loc) · 8.78 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
import Fastify from 'fastify';
import cors from '@fastify/cors';
import websocket from '@fastify/websocket';
import jwt from '@fastify/jwt';
import { getConfig } from './config/index.js';
import { createExecutor } from './executor.js';
import type {
ExecutionRequest
} from './types/core.js';
const fastify = Fastify({
logger: {
level: 'info',
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'HH:MM:ss Z',
ignore: 'pid,hostname'
}
}
}
});
let executor: any;
// Global error handlers
process.on('uncaughtException', (error) => {
fastify.log.fatal('Uncaught exception: %s', error.message || String(error));
process.exit(1);
});
process.on('unhandledRejection', (reason) => {
fastify.log.fatal('Unhandled rejection: %s', reason instanceof Error ? reason.message : String(reason));
process.exit(1);
});
async function startServer() {
try {
// Parse CLI arguments
const args = process.argv.slice(2);
const mcpConfigPath = args.find(arg => arg.startsWith('--mcp-config='))?.split('=')[1] ||
process.env.MCP_CONFIG_PATH ||
'./.mcp.json';
// Load configuration
const config = await getConfig();
fastify.log.info('Starting Code Mode Unified server...');
// Register plugins
await fastify.register(cors, config.server.cors);
await fastify.register(websocket);
if (config.security.auth.provider === 'jwt') {
await fastify.register(jwt, {
secret: config.security.auth.secretKey || 'default-secret'
});
}
// Initialize executor
executor = createExecutor({
config: config as any,
mcpConfigPath
});
await executor.initialize();
// Authentication middleware
const authenticate = async (request: any, reply: any) => {
if (config.security.auth.provider === 'jwt') {
try {
const token = request.headers.authorization?.replace('Bearer ', '');
if (!token) {
reply.code(401).send({ error: 'No token provided' });
return null;
}
const authResult = await executor.authenticate(token);
if (!authResult.success) {
reply.code(401).send({ error: authResult.error });
return null;
}
return authResult.authContext;
} catch (error: unknown) {
reply.code(401).send({ error: 'Invalid token' });
return null;
}
}
return null; // No auth required
};
// Health check endpoint
fastify.get('/health', async (request, reply) => {
const health = executor.getHealth();
reply.send(health);
});
// Capabilities endpoint
fastify.get('/capabilities', async (request, reply) => {
const authContext = await authenticate(request, reply);
if (reply.sent) return;
const capabilities = executor.getCapabilities(authContext);
reply.send(capabilities);
});
// Main execution endpoint
fastify.post('/execute', async (request, reply) => {
const authContext = await authenticate(request, reply);
if (reply.sent) return;
const body = request.body as any;
if (!body.code) {
reply.code(400).send({ error: 'No code provided' });
return;
}
const executionRequest: ExecutionRequest = {
code: body.code,
options: body.options || {},
authContext: authContext || undefined,
requestId: body.requestId
};
try {
const result = await executor.execute(executionRequest);
reply.send(result);
} catch (error: unknown) {
fastify.log.error('Execution error: %s', error instanceof Error ? error.message : String(error));
reply.code(500).send({
error: 'Internal execution error',
message: (error instanceof Error ? error.message : String(error))
});
}
});
// Authentication endpoints
if (config.security.auth.provider === 'jwt') {
// Create session
fastify.post('/auth/session', async (request, reply) => {
const body = request.body as any;
if (!body.userId || !body.scopes) {
reply.code(400).send({ error: 'userId and scopes required' });
return;
}
const result = await executor.createUserSession(body.userId, body.scopes);
reply.send(result);
});
// Validate token
fastify.post('/auth/validate', async (request, reply) => {
const authContext = await authenticate(request, reply);
if (reply.sent) return;
reply.send({ valid: true, authContext });
});
}
// WebSocket endpoint for real-time execution
fastify.register(async function (fastify) {
fastify.get('/ws', { websocket: true }, (connection, request) => {
connection.on('message', async (message) => {
try {
const data = JSON.parse(message.toString());
if (data.type === 'execute') {
const executionRequest: ExecutionRequest = {
code: data.code,
options: data.options || {},
requestId: data.requestId
};
const result = await executor.execute(executionRequest);
connection.send(JSON.stringify({
type: 'result',
requestId: data.requestId,
result
}));
}
} catch (error: unknown) {
connection.send(JSON.stringify({
type: 'error',
error: (error instanceof Error ? error.message : String(error))
}));
}
});
});
});
// MCP Bridge endpoint (for Claude integration)
fastify.post('/mcp/execute', async (request, reply) => {
const authContext = await authenticate(request, reply);
if (!authContext && config.security.auth.provider === 'jwt') return;
const body = request.body as any;
const { server, tool, arguments: toolArgs } = body;
if (!server || !tool) {
reply.code(400).send({
content: [
{
type: 'text',
text: 'Error: Missing required fields: server and tool'
}
]
});
return;
}
try {
// Call MCP tool directly using namespace format
const namespace = `${server}.${tool}`;
const mcpManager = (executor as any).mcpManager;
if (!mcpManager) {
throw new Error('MCP Manager not initialized');
}
const result = await mcpManager.callTool(namespace, toolArgs || {});
// Transform to MCP response format
const mcpResponse = {
content: [
{
type: 'text',
text: JSON.stringify(result, null, 2)
}
]
};
reply.send(mcpResponse);
} catch (error: unknown) {
reply.code(500).send({
content: [
{
type: 'text',
text: `Error: ${(error instanceof Error ? error.message : String(error))}`
}
]
});
}
});
// Metrics endpoint
fastify.get('/metrics', async (request, reply) => {
const health = executor.getHealth();
const capabilities = executor.getCapabilities();
const metrics = {
timestamp: new Date().toISOString(),
uptime: process.uptime(),
memory: process.memoryUsage(),
health,
capabilities: {
totalTools: capabilities.tools.native.length + capabilities.tools.mcp.length,
mcpServers: capabilities.mcpServers.length
}
};
reply.send(metrics);
});
// Graceful shutdown
const gracefulShutdown = async (signal: string) => {
fastify.log.info(`Received ${signal}, shutting down gracefully...`);
try {
if (executor) {
await executor.shutdown();
}
await fastify.close();
process.exit(0);
} catch (error: unknown) {
fastify.log.error('Error during shutdown: %s', error instanceof Error ? error.message : String(error));
process.exit(1);
}
};
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
// Start the server
const address = await fastify.listen({
port: config.server.port,
host: config.server.host
});
fastify.log.info(`🚀 Code Mode Unified server running at ${address}`);
fastify.log.info(`📡 WebSocket endpoint: ws://${config.server.host}:${config.server.port}/ws`);
fastify.log.info(`🔧 MCP Bridge endpoint: ${address}/mcp/execute`);
} catch (error: unknown) {
fastify.log.error('Failed to start server: %s', error instanceof Error ? error.message : String(error));
process.exit(1);
}
}
// Start the server
startServer();