/**
* Logger utility that writes to stderr (stdout is reserved for MCP JSON-RPC)
*/
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
const LOG_LEVELS: Record<LogLevel, number> = {
debug: 0,
info: 1,
warn: 2,
error: 3,
};
class Logger {
private level: LogLevel = 'info';
setLevel(level: LogLevel): void {
this.level = level;
}
private shouldLog(level: LogLevel): boolean {
return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
}
private formatMessage(level: LogLevel, message: string, ...args: unknown[]): string {
const timestamp = new Date().toISOString();
const formattedArgs = args.length > 0
? ' ' + args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
).join(' ')
: '';
return `[${timestamp}] [${level.toUpperCase()}] ${message}${formattedArgs}`;
}
debug(message: string, ...args: unknown[]): void {
if (this.shouldLog('debug')) {
console.error(this.formatMessage('debug', message, ...args));
}
}
info(message: string, ...args: unknown[]): void {
if (this.shouldLog('info')) {
console.error(this.formatMessage('info', message, ...args));
}
}
warn(message: string, ...args: unknown[]): void {
if (this.shouldLog('warn')) {
console.error(this.formatMessage('warn', message, ...args));
}
}
error(message: string, ...args: unknown[]): void {
if (this.shouldLog('error')) {
console.error(this.formatMessage('error', message, ...args));
}
}
}
export const logger = new Logger();