#!/usr/bin/env node /** * Memento MCP Server - Stdio Transport * * 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 { registerTools } from './tools.js'; 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; function log(level, ...args) { if (logLevels[level] >= currentLogLevel) { console.error(`[${level.toUpperCase()}]`, ...args); } } const databaseUrl = process.env.DATABASE_URL; if (!databaseUrl) { console.error('ERROR: DATABASE_URL is required'); process.exit(1); } const isPostgres = databaseUrl.startsWith('postgresql://') || databaseUrl.startsWith('postgres://'); const prisma = new PrismaClient({ datasources: { db: { url: isPostgres ? `${databaseUrl}${databaseUrl.includes('?') ? '&' : '?'}connection_limit=10&pool_timeout=10` : databaseUrl }, }, log: LOG_LEVEL === 'debug' ? ['query', 'info', 'warn', 'error'] : ['warn', 'error'], }); const server = new Server( { name: 'memento-mcp-server', version: '3.2.0' }, { capabilities: { tools: {} } }, ); const appBaseUrl = process.env.APP_BASE_URL || 'http://localhost:3000'; registerTools(server, prisma, { userId: process.env.USER_ID || null, appBaseUrl, }); async function main() { 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.2.0 (stdio)`); log('info', `Database: ${isPostgres ? 'PostgreSQL' : 'SQLite'}`); log('info', `User filter: ${process.env.USER_ID || 'none'}`); } main().catch((error) => { console.error('Server error:', error); process.exit(1); }); async function shutdown() { log('info', 'Shutting down...'); await prisma.$disconnect(); process.exit(0); } 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));