perf: optimize MCP server (O(1) auth, compact JSON, trashedAt fix) + memento-note performance (lazy loading, server-side filtering, XSS fixes, dead code removal, security hardening)
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 1m35s
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 1m35s
MCP Server: - Fix validateApiKey: O(1) direct lookup by shortId instead of loading all keys - Add trashedAt:null filter to ALL note queries (trashed notes leaked in results) - Compact JSON output (~40% smaller responses) - Bounded session cache (Map with MAX_SESSIONS=500) to prevent memory leaks - PostgreSQL connection pooling (connection_limit=10) - Rewrite all 22 tool descriptions in clear English - Fix /sse fallback to proper 307 redirect memento-note Performance: - loading=lazy on all note images - Split notebooksRefreshKey from global refreshKey (note CRUD no longer re-fetches notebooks) - Remove searchKey from trash count deps (no re-fetch on every keystroke) - Server-side notebookId filter in getAllNotes() (biggest win) - Skip collaborator fetch for non-shared notes (eliminates N+1 API calls) - next/dynamic for MarkdownContent + 4 modals (code-split remark/rehype/KaTeX) - Memoize DOMPurify sanitize with useMemo Security: - XSS: DOMPurify sanitize in note-card and note-history-modal - Auth anti-enumeration: uniform errors in auth.ts - CRON_SECRET mandatory on cron endpoints - Rate limiting on login (5 attempts/min per email) - Centralized API auth helpers (requireAuth/requireAdmin) - randomize-labels changed GET→POST - Removed debug endpoints (/api/debug/config, /api/debug/test-chat) Cleanup: - Removed dead code: .backup-keep, settings-backup, fix-*.js, debug-theme, fix-labels route - Removed sensitive console.error in auth.ts - Ollama fetchWithTimeout (30s/60s AbortController) - i18n: full Arabic translation, Farsi missing keys - Masonry drag-and-drop fix (localOrderMap, cross-section block) - Sidebar notebook tooltip on truncation
This commit is contained in:
@@ -1,31 +1,19 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Memento MCP Server - Stdio Transport (Optimized)
|
||||
* Memento MCP Server - Stdio Transport
|
||||
*
|
||||
* Performance improvements:
|
||||
* - Prisma connection pooling
|
||||
* - Prepared statements caching
|
||||
* - Optimized JSON serialization
|
||||
* - Lazy user resolution
|
||||
*
|
||||
* Environment variables:
|
||||
* DATABASE_URL - Prisma database URL (default: ../../memento-note/prisma/dev.db)
|
||||
* USER_ID - Optional user ID to filter data
|
||||
* APP_BASE_URL - Optional Next.js app URL for AI features (default: http://localhost:3000)
|
||||
* MCP_LOG_LEVEL - Log level: debug, info, warn, error (default: info)
|
||||
* Environment:
|
||||
* DATABASE_URL Prisma database URL
|
||||
* USER_ID Optional user ID filter
|
||||
* APP_BASE_URL Next.js app URL (default: http://localhost:3000)
|
||||
* MCP_LOG_LEVEL debug, info, warn, error (default: info)
|
||||
*/
|
||||
|
||||
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
||||
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname, join } from 'path';
|
||||
import { registerTools } from './tools.js';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
// Configuration
|
||||
const LOG_LEVEL = process.env.MCP_LOG_LEVEL || 'info';
|
||||
const logLevels = { debug: 0, info: 1, warn: 2, error: 3 };
|
||||
const currentLogLevel = logLevels[LOG_LEVEL] ?? 1;
|
||||
@@ -36,44 +24,24 @@ function log(level, ...args) {
|
||||
}
|
||||
}
|
||||
|
||||
// Database - requires DATABASE_URL environment variable
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
if (!databaseUrl) {
|
||||
console.error('ERROR: DATABASE_URL environment variable is required');
|
||||
console.error('ERROR: DATABASE_URL is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// OPTIMIZED: Prisma client with connection pooling and prepared statements
|
||||
const isPostgres = databaseUrl.startsWith('postgresql://') || databaseUrl.startsWith('postgres://');
|
||||
|
||||
const prisma = new PrismaClient({
|
||||
datasources: {
|
||||
db: { url: databaseUrl },
|
||||
db: { url: isPostgres ? `${databaseUrl}${databaseUrl.includes('?') ? '&' : '?'}connection_limit=10&pool_timeout=10` : databaseUrl },
|
||||
},
|
||||
// SQLite optimizations
|
||||
log: LOG_LEVEL === 'debug' ? ['query', 'info', 'warn', 'error'] : ['warn', 'error'],
|
||||
});
|
||||
|
||||
// Connection health check
|
||||
let isConnected = false;
|
||||
async function checkConnection() {
|
||||
try {
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
isConnected = true;
|
||||
return true;
|
||||
} catch (error) {
|
||||
isConnected = false;
|
||||
log('error', 'Database connection failed:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'memento-mcp-server',
|
||||
version: '3.1.0',
|
||||
},
|
||||
{
|
||||
capabilities: { tools: {} },
|
||||
},
|
||||
{ name: 'memento-mcp-server', version: '3.2.0' },
|
||||
{ capabilities: { tools: {} } },
|
||||
);
|
||||
|
||||
const appBaseUrl = process.env.APP_BASE_URL || 'http://localhost:3000';
|
||||
@@ -84,21 +52,19 @@ registerTools(server, prisma, {
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Verify database connection on startup
|
||||
const connected = await checkConnection();
|
||||
if (!connected) {
|
||||
console.error('FATAL: Could not connect to database');
|
||||
try {
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
} catch (error) {
|
||||
console.error('FATAL: Database connection failed:', error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
|
||||
log('info', `Memento MCP Server v3.1.0 (stdio) - Optimized`);
|
||||
log('info', `Database: ${databaseUrl}`);
|
||||
log('info', `App URL: ${appBaseUrl}`);
|
||||
log('info', `User filter: ${process.env.USER_ID || 'none (all data)'}`);
|
||||
log('debug', 'Performance optimizations enabled: connection pooling, batch operations, caching');
|
||||
|
||||
log('info', `Memento MCP Server v3.2.0 (stdio)`);
|
||||
log('info', `Database: ${isPostgres ? 'PostgreSQL' : 'SQLite'}`);
|
||||
log('info', `User filter: ${process.env.USER_ID || 'none'}`);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
@@ -106,24 +72,13 @@ main().catch((error) => {
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
// Graceful shutdown
|
||||
process.on('SIGINT', async () => {
|
||||
log('info', 'Shutting down gracefully...');
|
||||
async function shutdown() {
|
||||
log('info', 'Shutting down...');
|
||||
await prisma.$disconnect();
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
|
||||
process.on('SIGTERM', async () => {
|
||||
log('info', 'Shutting down gracefully...');
|
||||
await prisma.$disconnect();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
// Handle uncaught errors
|
||||
process.on('uncaughtException', (error) => {
|
||||
log('error', 'Uncaught exception:', error.message);
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
log('error', 'Unhandled rejection:', reason);
|
||||
});
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
process.on('uncaughtException', (err) => log('error', 'Uncaught:', err.message));
|
||||
process.on('unhandledRejection', (reason) => log('error', 'Unhandled:', reason));
|
||||
|
||||
Reference in New Issue
Block a user