-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp-server.js
More file actions
619 lines (527 loc) · 24.3 KB
/
mcp-server.js
File metadata and controls
619 lines (527 loc) · 24.3 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/**
* Browser Logs MCP Server - SSE Consumer
* Simplified implementation - MCP server consuming SSE streams from backend
*/
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const { CallToolRequestSchema, ListToolsRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
const { EventSource } = require('eventsource');
class BrowserLogsMCPServer {
constructor() {
this.server = new Server({
name: 'Browser Logs MCP Server (SSE)',
version: '2.0.0'
}, {
capabilities: {
tools: {}
}
});
// Support custom backend host and port from environment
const backendHost = process.env.BACKEND_HOST || 'localhost';
const backendPort = process.env.BACKEND_PORT || process.env.PORT || 22345;
this.backendUrl = `http://${backendHost}:${backendPort}`;
this.eventSource = null;
this.currentLogs = [];
this.hostStatus = new Map();
this.defaultApp = process.env.FILTER_APP || null; // Default app from environment
this.CHARACTER_LIMIT = 5000; // Maximum response size in characters
this.setupTools();
}
setupTools() {
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
if (name === 'get_logs') {
return await this.handleGetLogs(args);
}
throw new Error(`Unknown tool: ${name}`);
});
this.server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'get_logs',
description: 'Retrieve logs via SSE streaming: frontend browser console logs, namespaced application logs (user-actions, api-calls, etc.), and backend service output logs. Use this to debug issues, monitor user behavior, or trace application flow.',
inputSchema: {
type: 'object',
properties: {
app: {
type: 'string',
description: `Application name${this.defaultApp ? ` (default: "${this.defaultApp}")` : ' (REQUIRED)'} - e.g., "my-app", "dashboard"`
},
lines: {
type: 'number',
description: 'Number of log lines to retrieve (1-20, default: 5)',
minimum: 1,
maximum: 20,
default: 5
},
offset: {
type: 'number',
description: 'Number of log entries to skip for pagination (default: 0)',
minimum: 0,
default: 0
},
filter: {
type: 'string',
description: 'Text filter to search log content',
default: ''
},
frontend_host: {
type: 'string',
description: 'Frontend host to retrieve logs from (e.g., "localhost:3000")',
default: ''
},
namespace: {
type: 'string',
description: 'Log namespace to retrieve (e.g., "browser", "user-actions")',
default: ''
}
},
required: this.defaultApp ? [] : ['app']
},
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true
}
}
]
};
});
}
async handleGetLogs(args = {}) {
const requestedApp = args.app || this.defaultApp || '';
const lines = Math.min(args.lines || 5, 20);
const offset = Math.max(args.offset || 0, 0);
const filter = args.filter || '';
const requestedHost = args.frontend_host || '';
const requestedNamespace = args.namespace || '';
// App is mandatory (unless FILTER_APP is set)
if (!requestedApp) {
try {
// Fetch available apps to help user
const statusResponse = await fetch(`${this.backendUrl}/api/logs/status`);
if (statusResponse.ok) {
const statusData = await statusResponse.json();
const apps = statusData.apps || [];
const availableApps = apps.map(a => `- ${a.app} (${a.totalLogs} entries)`).join('\n') || 'No apps currently connected';
return this.createErrorResponse(
`❌ **Missing required parameter: app**\n\nYou must specify the application name.\n\n**Available apps:**\n${availableApps}\n\nExample: get_logs(app="${apps[0]?.app || 'my-app'}")\n\nOr set FILTER_APP environment variable when starting the MCP server.`
);
}
} catch (error) {
// Fallback to generic error if can't fetch apps
console.warn('Could not fetch available apps:', error.message);
}
return this.createErrorResponse('❌ **Missing required parameter: app**\n\nYou must specify the application name.\n\nExample: get_logs(app="my-app")\n\nOr set FILTER_APP environment variable when starting the MCP server.');
}
try {
// Ensure SSE connection is active
if (!this.eventSource || this.eventSource.readyState === EventSource.CLOSED) {
await this.connectSSE();
}
// Get current status via HTTP for host/namespace selection
const statusResponse = await fetch(`${this.backendUrl}/api/logs/status`);
if (!statusResponse.ok) {
throw new Error(`Backend server not responding: ${statusResponse.status}`);
}
const statusData = await statusResponse.json();
const apps = statusData.apps || [];
// Find the requested app
const appData = apps.find(a => a.app === requestedApp);
if (!appData) {
const availableApps = apps.map(a => `- ${a.app} (${a.totalLogs} entries)`).join('\n') || 'None';
return this.createErrorResponse(`❌ **App not found**\n\nApp "${requestedApp}" is not currently connected.\n\nAvailable apps:\n${availableApps}`);
}
const hosts = appData.hosts || [];
const hostSelection = this.selectHost(hosts, requestedHost);
if (!hostSelection.success) {
return this.createErrorResponse(hostSelection.message);
}
const hostData = hosts.find(h => h.host === hostSelection.host);
const namespaces = hostData ? hostData.namespaces : [];
const namespaceSelection = this.selectNamespace(namespaces, requestedNamespace);
if (!namespaceSelection.success) {
return this.createErrorResponse(namespaceSelection.message);
}
// Connect to SSE stream for real-time logs
const logData = await this.getLogsViaSSE(
requestedApp,
hostSelection.host,
namespaceSelection.namespace,
{ lines, offset, filter }
);
const formattedOutput = this.formatLogs(
logData,
requestedApp,
hostSelection.host,
namespaceSelection.namespace,
hostSelection.autoSelected && namespaceSelection.autoSelected
);
return this.createSuccessResponse(formattedOutput);
} catch (error) {
return this.createErrorResponse(
`❌ **Error retrieving logs**\n\nError: ${error.message}\n\nMake sure the backend logger server is running on http://localhost:22345`
);
}
}
async connectSSE() {
return new Promise((resolve, reject) => {
try {
this.eventSource = new EventSource(`${this.backendUrl}/api/logs/stream`);
this.eventSource.onopen = () => {
console.error('🌊 SSE connection established');
resolve();
};
this.eventSource.onerror = (error) => {
console.error('❌ SSE connection error:', error);
reject(new Error('Failed to establish SSE connection'));
};
this.eventSource.addEventListener('connected', (event) => {
console.error('🌊 SSE client connected');
});
this.eventSource.addEventListener('new_logs', (event) => {
try {
const data = JSON.parse(event.data);
this.processNewLogs(data);
} catch (error) {
console.error('Error processing new logs:', error);
}
});
this.eventSource.addEventListener('initial_logs', (event) => {
try {
const data = JSON.parse(event.data);
this.processInitialLogs(data);
} catch (error) {
console.error('Error processing initial logs:', error);
}
});
this.eventSource.addEventListener('keepalive', (event) => {
// Keep-alive received, connection is stable
});
} catch (error) {
reject(error);
}
});
}
processNewLogs(data) {
// Update our internal cache with new logs
const { app, host, logs } = data;
const cacheKey = `${app}:${host}`;
if (!this.hostStatus.has(cacheKey)) {
this.hostStatus.set(cacheKey, { namespaces: new Map() });
}
const hostData = this.hostStatus.get(cacheKey);
for (const [namespace, logData] of Object.entries(logs)) {
if (!hostData.namespaces.has(namespace)) {
hostData.namespaces.set(namespace, []);
}
const namespaceLogs = hostData.namespaces.get(namespace);
if (Array.isArray(logData)) {
namespaceLogs.push(...logData);
} else {
namespaceLogs.push({
namespace,
data: logData,
timestamp: Date.now()
});
}
// Keep only recent logs (last 1000 per namespace)
if (namespaceLogs.length > 1000) {
hostData.namespaces.set(namespace, namespaceLogs.slice(-1000));
}
}
}
processInitialLogs(data) {
// Process initial log dump from SSE connection
const { app, host, namespace, logs } = data;
const cacheKey = `${app}:${host}`;
if (!this.hostStatus.has(cacheKey)) {
this.hostStatus.set(cacheKey, { namespaces: new Map() });
}
const hostData = this.hostStatus.get(cacheKey);
hostData.namespaces.set(namespace, logs);
console.error(`📋 Loaded ${logs.length} initial logs for ${app}@${host}/${namespace}`);
}
async getLogsViaSSE(app, host, namespace, options = {}) {
return new Promise((resolve, reject) => {
try {
const cacheKey = `${app}:${host}`;
// Check if we have cached logs
if (this.hostStatus.has(cacheKey) && this.hostStatus.get(cacheKey).namespaces.has(namespace)) {
let logs = [...this.hostStatus.get(cacheKey).namespaces.get(namespace)];
// Apply filter
if (options.filter) {
const filterLower = options.filter.toLowerCase();
logs = logs.filter(log => {
if (log.namespace === 'browser') {
return log.message.toLowerCase().includes(filterLower);
} else {
return JSON.stringify(log.data).toLowerCase().includes(filterLower);
}
});
}
// Apply offset and lines limit for pagination
const offset = options.offset || 0;
const totalAfterFilter = logs.length;
// Skip offset entries and take 'lines' entries
const start = Math.max(0, logs.length - offset - options.lines);
const end = logs.length - offset;
logs = logs.slice(start, end);
resolve({
logs,
totalEntries: totalAfterFilter,
offset,
options
});
} else {
// No cached logs available, fetch via HTTP
this.fetchLogsViaHTTP(app, host, namespace, options).then(resolve).catch(reject);
}
} catch (error) {
reject(error);
}
});
}
async fetchLogsViaHTTP(app, host, namespace, options = {}) {
try {
const params = new URLSearchParams();
if (options.lines) params.append('lines', options.lines);
if (options.offset) params.append('offset', options.offset);
if (options.filter) params.append('filter', options.filter);
const response = await fetch(`${this.backendUrl}/api/logs/${encodeURIComponent(app)}/${encodeURIComponent(host)}/${encodeURIComponent(namespace)}?${params}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
throw new Error(`Failed to fetch logs from backend: ${error.message}`);
}
}
selectHost(hosts, requestedHost) {
if (!requestedHost) {
if (hosts.length === 0) {
return {
success: false,
message: '❌ **No frontend hosts connected**\n\nMake sure frontend applications are running with logging enabled.'
};
} else if (hosts.length === 1) {
return {
success: true,
host: hosts[0].host,
autoSelected: true,
message: `Auto-selected host: ${hosts[0].host} (${hosts[0].totalLogs} entries)`
};
} else {
const hostList = hosts.map(h => `- ${h.host} (${h.totalLogs} entries)`).join('\n');
return {
success: false,
message: `🔄 **Multiple Hosts Available**\n\nPlease specify frontend_host:\n${hostList}\n\nExample: get_logs(frontend_host="${hosts[0].host}")`
};
}
} else {
const hostExists = hosts.find(h => h.host === requestedHost);
if (!hostExists) {
const availableHosts = hosts.map(h => `- ${h.host} (${h.totalLogs} entries)`).join('\n') || 'None';
return {
success: false,
message: `❌ **Host not found**\n\nHost "${requestedHost}" is not currently connected.\n\nAvailable hosts:\n${availableHosts}`
};
}
return {
success: true,
host: requestedHost,
autoSelected: false
};
}
}
selectNamespace(namespaces, requestedNamespace) {
if (!requestedNamespace) {
if (namespaces.length === 0) {
return {
success: false,
message: '❌ **No namespaces found** for the selected host'
};
} else if (namespaces.length === 1 && namespaces[0].namespace === 'browser') {
return {
success: true,
namespace: namespaces[0].namespace,
autoSelected: true
};
} else {
const namespaceList = namespaces.map(ns => `- ${ns.namespace} (${ns.count} entries)`).join('\n');
return {
success: false,
message: `📂 **Multiple Namespaces Available**\n\nPlease specify namespace:\n${namespaceList}\n\nExample: get_logs(namespace="${namespaces[0].namespace}")`
};
}
} else {
const namespaceExists = namespaces.find(ns => ns.namespace === requestedNamespace);
if (!namespaceExists) {
const availableNamespaces = namespaces.map(ns => `- ${ns.namespace} (${ns.count} entries)`).join('\n') || 'None';
return {
success: false,
message: `❌ **Namespace not found**\n\nNamespace "${requestedNamespace}" does not exist.\n\nAvailable namespaces:\n${availableNamespaces}`
};
}
return {
success: true,
namespace: requestedNamespace,
autoSelected: false
};
}
}
formatLogs(data, app, host, namespace, autoSelected = false) {
let logsToFormat = data.logs;
let truncated = false;
// Build output with initial logs
let output = this.buildLogOutput(logsToFormat, data, app, host, namespace, autoSelected);
// Check CHARACTER_LIMIT and truncate if needed
if (output.length > this.CHARACTER_LIMIT) {
truncated = true;
// Cut logs in half and rebuild
const halfLogs = Math.ceil(logsToFormat.length / 2);
logsToFormat = logsToFormat.slice(-halfLogs);
output = this.buildLogOutput(logsToFormat, data, app, host, namespace, autoSelected);
// Add truncation warning
output += `\n\nWARNING: Response truncated from ${data.logs.length} to ${logsToFormat.length} entries due to size limits (${this.CHARACTER_LIMIT} chars).\n`;
output += `Use 'filter' parameter, reduce 'lines', or use 'offset' for pagination to see specific logs.`;
}
return output;
}
buildLogOutput(logs, data, app, host, namespace, autoSelected) {
let output = `Application Logs (${logs.length} entries`;
if (data.options && data.options.filter) {
output += `, filtered by "${data.options.filter}"`;
}
if (data.offset > 0) {
output += `, offset: ${data.offset}`;
}
output += `)\n\n`;
output += `App: ${app}\n`;
output += `Host: ${host}\n`;
output += `Namespace: ${namespace}\n`;
output += `Total Available: ${data.totalEntries} entries\n`;
output += `Connection: SSE Streaming\n\n`;
logs.forEach(log => {
const timestamp = new Date(log.timestamp).toLocaleTimeString();
if (log.namespace === 'browser') {
const level = log.level ? log.level.padEnd(5) : 'LOG'.padEnd(5);
output += `[${timestamp}] ${level} ${log.message}\n`;
} else {
output += `[${timestamp}] ${log.namespace.padEnd(15)} ${JSON.stringify(log.data)}\n`;
}
});
if (logs.length === 0) {
output += 'No logs found matching the specified criteria.\n';
}
if (autoSelected) {
output += `\nAuto-selected (single host & namespace available for this app)`;
}
return output;
}
createErrorResponse(message) {
return {
content: [
{
type: 'text',
text: message
}
]
};
}
createSuccessResponse(text) {
return {
content: [
{
type: 'text',
text: text
}
]
};
}
async run() {
console.error('🚀 Browser Logs MCP Server (SSE) starting...');
console.error('📋 Providing get_logs tool for frontend log access via SSE streaming');
if (this.defaultApp) {
console.error(`🎯 Default app filter: ${this.defaultApp}`);
}
console.error('🌊 Connecting to SSE stream: http://localhost:22345/api/logs/stream');
console.error('🔗 Backend status: http://localhost:22345/api/logs/status');
try {
// Establish SSE connection
await this.connectSSE();
console.error('✅ SSE connection established successfully');
} catch (error) {
console.error('⚠️ Warning: Could not establish SSE connection, will fall back to HTTP');
}
const transport = new StdioServerTransport();
await this.server.connect(transport);
console.error('Browser Logs MCP Server (SSE) running on stdio');
}
shutdown() {
if (this.eventSource) {
this.eventSource.close();
console.error('SSE connection closed');
}
}
}
if (require.main === module) {
// Check for help command
if (process.argv.includes('mcp-help') || process.argv.includes('--help') || process.argv.includes('-h')) {
const scriptPath = require('path').resolve(__filename);
console.log(`
╔════════════════════════════════════════════════════════════════════════════╗
║ Browser Logs MCP Server - Setup Guide ║
╚════════════════════════════════════════════════════════════════════════════╝
Add this MCP server to Claude Code:
claude mcp remove FE-logs # remove existing one
claude mcp add FE-logs node ${scriptPath} \\
--env FILTER_APP=my-app-name \\
--scope local
Comments:
FE-logs
MCP server name, can be changed
--env FILTER_APP=my-app-name
defines your app name (frontend app shall declare this name)
--scope local
install only for current project
Environment Variables:
FILTER_APP=app-name Set default app for get_logs (makes app parameter optional)
Test with MCP inspector:
npx @modelcontextprotocol/inspector --cli \\
node ${scriptPath} \\
-e FILTER_APP=my-app --method tools/call --tool-name 'get_logs'
Usage in Claude Code:
Without FILTER_APP:
get_logs(app="my-app")
get_logs(app="my-app", filter="error", lines=50)
With FILTER_APP set:
get_logs() # Uses default app
get_logs(app="other-app") # Override default
get_logs(filter="error", lines=50) # Uses default app
Backend Requirements:
- Backend server must be running: npm run start-backend
- Backend URL: http://localhost:22345
More Information:
- README: See README.md in this directory
- Configuration: See CLAUDE.md for detailed setup
`);
process.exit(0);
}
const server = new BrowserLogsMCPServer();
// Handle shutdown gracefully
process.on('SIGTERM', () => {
console.log('Shutting down Browser Logs MCP Server...');
server.shutdown();
process.exit(0);
});
process.on('SIGINT', () => {
console.log('Shutting down Browser Logs MCP Server...');
server.shutdown();
process.exit(0);
});
server.run().catch(console.error);
}
module.exports = BrowserLogsMCPServer;