### Install Pino Adapter Dependencies Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Instructions for installing the necessary peer dependency for the Pino adapter. This involves installing the `pino` npm package. This is required if you plan to use SimpleMcpLogger with an existing Pino logging setup. ```bash # For Pino adapter npm install pino ``` -------------------------------- ### Install Both Winston and Pino Adapter Dependencies Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Instructions for installing the peer dependencies for both the Winston and Pino adapters. This command installs `winston`, `winston-transport`, and `pino`. Install this if you intend to use SimpleMcpLogger with both logging frameworks. ```bash # Or install both npm install winston winston-transport pino ``` -------------------------------- ### Install Winston Adapter Dependencies Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Instructions for installing the necessary peer dependencies for the Winston adapter. This includes the `winston` and `winston-transport` npm packages. These are required if you plan to use SimpleMcpLogger with an existing Winston logging setup. ```bash # For Winston adapter npm install winston winston-transport ``` -------------------------------- ### Browser + Pino Integration Example (TypeScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Demonstrates how to integrate SimpleMcpLogger with Pino in a browser environment. It shows the usage of `createPinoDestination` from SimpleMcpLogger along with a browser-compatible Pino build to configure logging. ```typescript import { createPinoDestination } from "@alcyone-labs/simple-mcp-logger"; // Import browser-compatible Pino build import pino from "pino/browser"; const destination = createPinoDestination({ level: "info", prefix: "Browser", }); const logger = pino({ level: "info" }, destination); logger.info("Hello from Pino in browser!"); ``` -------------------------------- ### Configuring Different Loggers with Options API (TypeScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Provides examples of creating loggers with different configurations using the options-based API. This includes a recommended setup for MCP servers, a debug logger, and a logger for non-MCP testing. ```typescript // Comprehensive MCP server logging const logger = createMcpLogger({ prefix: "MCP-Server", logToFile: "./logs/server.log", level: "info", // Captures info, warn, error (recommended) mcpMode: true // MCP compliant }); // Development/debugging with all levels const debugLogger = createMcpLogger({ prefix: "Debug", logToFile: "./logs/debug.log", level: "debug", // Captures everything mcpMode: true }); // Non-MCP mode for testing const testLogger = createMcpLogger({ prefix: "Test", level: "debug", mcpMode: false // Enable console output for testing }); ``` -------------------------------- ### Basic SimpleMcpLogger Usage in TypeScript Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Provides a quick start example demonstrating basic logger instantiation and usage. It covers using the global logger instance, creating a custom logger with options like level and prefix, and enabling file logging. ```typescript import { Logger, logger } from "@alcyone-labs/simple-mcp-logger"; // Use the global logger instance logger.info("Hello, world!"); logger.error("Something went wrong"); // Create a custom logger const myLogger = new Logger({ level: "debug", prefix: "MyApp", mcpMode: false, }); myLogger.debug("Debug message"); myLogger.info("Info message"); // Create a logger with file output const fileLogger = new Logger({ level: "info", prefix: "MyApp", logToFile: "./logs/app.log", // Logs to file, directory created automatically }); fileLogger.info("This goes to both console and file"); // For MCP servers: use mcpError() for debugging (safe STDERR output) myLogger.mcpError("Debug info visible in client logs"); ``` -------------------------------- ### Migrating from Winston to SimpleMcpLogger in TypeScript Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Demonstrates how to integrate SimpleMcpLogger's Winston transport, allowing a gradual migration from a standard Winston setup. ```typescript // Before import winston from "winston"; const logger = winston.createLogger({ transports: [new winston.transports.Console()], }); // After import { createWinstonTransport } from "@alcyone-labs/simple-mcp-logger"; const logger = winston.createLogger({ transports: [createWinstonTransport()], }); ``` -------------------------------- ### Installing SimpleMcpLogger via npm Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Installs the core SimpleMcpLogger package using npm. This package provides the essential logging functionality with zero external dependencies. ```bash npm install @alcyone-labs/simple-mcp-logger ``` -------------------------------- ### General Purpose Logging with createCliLogger Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md This example shows how to create a logger for general-purpose use in applications like web apps, APIs, or CLI tools using the `createCliLogger` function. It allows setting the log level and a prefix. The logger supports all standard console methods, including `table`, `time`, and `timeEnd`. ```typescript import { Logger, createCliLogger } from "@alcyone-labs/simple-mcp-logger"; // Perfect for web apps, APIs, CLI tools, etc. const appLogger = createCliLogger("info", "MyApp"); appLogger.info("Server starting on port 3000"); appLogger.warn("High memory usage detected"); appLogger.error("Database connection failed"); // Use all console methods appLogger.table([{ user: "john", status: "active" }]); appLogger.time("API Response"); // ... some operation appLogger.timeEnd("API Response"); ``` -------------------------------- ### Test Table Logging (JavaScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/browser-demo.html This JavaScript function demonstrates the `table` method of SimpleMcpLogger, which formats arrays of objects or objects into a tabular view in the console. It shows two examples: logging a full table and logging a table with specific columns selected. ```javascript window.testTable = function() { console.log('=== Testing Table Logging ==='); const users = [ { name: 'John', age: 30, role: 'Admin' }, { name: 'Jane', age: 25, role: 'User' }, { name: 'Bob', age: 35, role: 'Moderator' } ]; appLogger.table(users); appLogger.table(users, ['name', 'role']); }; ``` -------------------------------- ### File Logging Best Practices: Closing Loggers in TypeScript Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Ensures proper application shutdown by closing the logger to flush pending writes. This example uses `SIGINT` to gracefully handle termination signals. ```typescript process.on("SIGINT", async () => { await logger.close(); process.exit(0); }); ``` -------------------------------- ### MCP Logging: Safe vs. Unsafe Output in TypeScript Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Demonstrates the critical difference between logging to STDOUT (which breaks MCP communication) and STDERR (which is safe for debugging). Uses `console.log` as an example of unsafe output and `mcpLogger.mcpError` for safe output. ```typescript // ❌ This breaks MCP communication (writes to STDOUT) console.log("Debug info"); // Corrupts STDOUT → Protocol failure logger.info("Processing request"); // Invalid MCP message → Connection lost // ✅ This works perfectly (suppressed STDOUT, safe STDERR) mcpLogger.info("Processing request"); // Suppressed in MCP mode mcpLogger.mcpError("Debug info", data); // Safe: writes to STDERR ``` -------------------------------- ### Test MCP Mode Functionality (JavaScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/browser-demo.html This JavaScript function illustrates the MCP (Message Control Protocol) mode in SimpleMcpLogger. It compares logging behavior between a standard logger and an MCP-enabled logger, showing how MCP mode can suppress certain log levels (like info and error in this example) based on its configuration. ```javascript window.testMcpMode = function() { console.log('=== Testing MCP Mode ==='); console.log('1. Regular logger (MCP mode OFF):'); appLogger.info('✓ This WILL be logged (normal mode)'); console.log('2. MCP logger (MCP mode ON) - should suppress most output:'); console.log(' Calling mcpLogger.info() - should be silent...'); mcpLogger.info('❌ This should NOT appear (MCP mode suppresses info)'); console.log(' Calling mcpLogger.error() - should be silent...'); mcpLogger.error('❌ This should NOT appear (MCP mode suppresses error)'); console.log(' Calling mcpLogger.mcpError(' is not a valid method for this example, assuming it should be mcpLogger.error() based on context.' ); }; ``` -------------------------------- ### Basic Browser Usage of SimpleMcpLogger (HTML/JavaScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Shows how to use SimpleMcpLogger directly in a browser using a script tag. It demonstrates importing the logger, using the global logger instance, creating a custom logger with specific options, and even replacing the global console object. ```html

SimpleMcpLogger Browser Demo

Check the browser console for log messages!

``` -------------------------------- ### Console Replacement with SimpleMcpLogger Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Demonstrates how to replace the global `console` object with the `Logger` instance from SimpleMcpLogger to ensure all console output is MCP-compliant. This should be done at application startup. ```APIDOC ## Console Replacement ### Description Replace the global `console` object with an instance of `Logger` from the `@alcyone-labs/simple-mcp-logger` package. This ensures all subsequent calls to `console.log`, `console.error`, etc., are handled by SimpleMcpLogger. **Important:** Perform this replacement at the very beginning of your application's startup process before any other logging occurs to prevent potential infinite loops or missed logs. ### Method Instantiation and Global Assignment ### Code Example ```typescript import { Logger } from "@alcyone-labs/simple-mcp-logger"; // Initialize the logger with desired configuration const logger = new Logger({ level: "info", prefix: "App" }); // Replace the global console object globalThis.console = logger as any; // Now, all console calls will use the SimpleMcpLogger instance console.log("This message is logged via SimpleMcpLogger."); console.error("This error message is also handled by SimpleMcpLogger."); ``` ### Usage Notes - Ensure this code runs before any other part of your application that might use `console`. - The `logger` can be configured with various options like `level`, `prefix`, `logToFile`, and `mcpMode`. ``` -------------------------------- ### Import and Initialize SimpleMcpLogger in Browser Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/browser-demo.html This JavaScript snippet demonstrates how to import SimpleMcpLogger and its related functions (Logger, logger, createMcpLogger, createCliLogger) from a local distribution file. It then initializes different logger instances with various configurations and exposes them globally for interactive testing within the browser's console. ```javascript // Import SimpleMcpLogger from the built distribution // In a real application, you would import from npm + bundle or from a CDN import { Logger, logger, createMcpLogger, createCliLogger } from './dist/index.mjs'; // PROPER CONSOLE REPLACEMENT EXAMPLE (do this at app startup): // const appLogger = new Logger({ level: 'info', prefix: 'App' }); // globalThis.console = appLogger; // Now all console.* calls will use SimpleMcpLogger safely! // Create different logger instances const appLogger = new Logger({ level: 'debug', prefix: 'BrowserApp', mcpMode: false }); const mcpLogger = createMcpLogger('MCP'); const cliLogger = createCliLogger('debug', 'CLI'); // Make loggers available globally for the demo window.appLogger = appLogger; window.mcpLogger = mcpLogger; window.cliLogger = cliLogger; window.globalLogger = logger; ``` -------------------------------- ### File Logging with Winston and Pino Adapters Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Illustrates how to configure file logging when using Winston and Pino adapters with SimpleMcpLogger. This allows leveraging existing logging frameworks while maintaining MCP compliance. ```typescript // Winston with file logging import { createWinstonTransport } from "@alcyone-labs/simple-mcp-logger/adapters"; const transport = createWinstonTransport({ logToFile: "./logs/winston.log", mcpMode: true, }); // Pino with file logging import { createPinoDestination } from "@alcyone-labs/simple-mcp-logger/adapters"; const destination = createPinoDestination({ logToFile: "./logs/pino.log", mcpMode: true, }); ``` -------------------------------- ### Test Console Replacement and Compatibility (JavaScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/browser-demo.html This JavaScript function illustrates how SimpleMcpLogger can replace the browser's native console object. It logs a message to demonstrate that replacement and then lists all available methods on the logger instance to show compatibility. It emphasizes that console replacement should ideally occur at application startup to prevent infinite loops. ```javascript window.testConsoleReplacement = function() { console.log('=== Testing Console Replacement ==='); console.log('Note: This demonstrates the concept. In practice, you would replace console before any logging occurs.'); // Show that our logger has all the same methods as console const loggerMethods = Object.getOwnPropertyNames(Object.getPrototypeOf(appLogger)) .filter(name => typeof appLogger[name] === 'function' && !name.startsWith('_') && name !== 'constructor'); console.log('SimpleMcpLogger methods:', loggerMethods.sort()); // Demonstrate method compatibility without infinite loop console.log('Calling appLogger methods directly:'); appLogger.log('✓ log() method works'); appLogger.info('✓ info() method works'); appLogger.warn('✓ warn() method works'); appLogger.error('✓ error() method works'); appLogger.debug('✓ debug() method works'); appLogger.trace('✓ trace() method works'); console.log('Console replacement is safe when done at application startup!'); }; ``` -------------------------------- ### Migrating from Pino to SimpleMcpLogger in TypeScript Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Shows how to switch from a standard Pino logger to one managed by SimpleMcpLogger for MCP compliance. ```typescript // Before import pino from "pino"; const logger = pino(); // After import { createPinoLogger } from "@alcyone-labs/simple-mcp-logger"; const logger = createPinoLogger(); ``` -------------------------------- ### Migration to Enhanced API for Comprehensive Logging (TypeScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Demonstrates the recommended options-based API for new projects and provides steps for gradual migration in existing projects. The enhanced API allows for comprehensive logging, including debug, info, and warn messages, with better control over log levels. ```typescript // ✅ RECOMMENDED: Comprehensive logging const logger = createMcpLogger({ prefix: "MyMcpServer", logToFile: "./logs/server.log", level: "info", // Captures info, warn, error mcpMode: true }); ``` ```typescript // Step 1: Keep existing code working (no changes needed) const logger = createMcpLogger("MyServer", "./logs/mcp.log"); // Step 2: Add comprehensive logging where needed const debugLogger = createMcpLogger({ prefix: "MyServer-Debug", logToFile: "./logs/debug.log", level: "debug" // Capture everything for debugging }); // Step 3: Eventually migrate to options-based API const logger = createMcpLogger({ prefix: "MyServer", logToFile: "./logs/mcp.log", level: "info" // Better than error-only default }); ``` -------------------------------- ### createCliLogger Factory Function Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Explains the `createCliLogger` factory function, used for creating logger instances specifically tailored for command-line interface (CLI) applications. It allows setting the logging level and an optional prefix. ```APIDOC ## Factory Function - createCliLogger ### Description The `createCliLogger` function is a convenient factory for generating `Logger` instances designed for command-line interface (CLI) environments. It simplifies the setup process by allowing you to specify the desired logging level and an optional prefix for your application's logs. ### Method Factory Function ### Signature: ```typescript createCliLogger(level?: LogLevel, prefix?: string): Logger ``` ### Parameters: #### Query Parameters - **level** (LogLevel) - Optional - The minimum severity level for log messages to be outputted. Possible values include 'debug', 'info', 'warn', 'error', and 'silent'. Defaults to 'info' if not provided. - **prefix** (string) - Optional - A string that will be prepended to all log messages generated by this logger instance. ### Examples: ```typescript import { createCliLogger } from "@alcyone-labs/simple-mcp-logger"; // Create a logger with default level ('info') and no prefix const defaultLogger = createCliLogger(); // Create a logger with 'debug' level and a 'CLI' prefix const debugLogger = createCliLogger("debug", "CLI"); debugLogger.debug("Starting CLI process..."); debugLogger.info("Processing arguments..."); ``` ### Response #### Success Response (200) Returns a `Logger` instance configured for CLI use with the specified level and prefix. ``` -------------------------------- ### Browser Usage with Bundlers (Webpack, Vite) (TypeScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Illustrates how to import and use SimpleMcpLogger within a project managed by bundlers like Webpack or Vite. It covers creating a logger instance with custom settings, utilizing various console methods, and timing operations. ```typescript import { Logger, createMcpLogger } from "@alcyone-labs/simple-mcp-logger"; // Create logger for browser app const appLogger = new Logger({ level: "info", prefix: "MyApp", mcpMode: false, }); // Use all console methods appLogger.log("Application started"); appLogger.group("User Actions"); appLogger.info("User clicked button"); appLogger.warn("Form validation warning"); appLogger.groupEnd(); // Time operations appLogger.time("API Call"); // ... some async operation appLogger.timeEnd("API Call"); ``` -------------------------------- ### Migrating from Console to SimpleMcpLogger in TypeScript Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Shows how to replace direct `console` calls with SimpleMcpLogger's methods for better control and MCP compliance. It also demonstrates globally replacing `console`. ```typescript // Before console.log("Hello"); console.error("Error"); // After import { logger } from "@alcyone-labs/simple-mcp-logger"; logger.log("Hello"); logger.error("Error"); // Or replace globally globalThis.console = logger as any; ``` -------------------------------- ### Logger Class Methods Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Lists and describes all standard and special methods available on the `Logger` instance, including logging functions, utility methods like `table` and `time`, and special MCP-related functions. ```APIDOC ## Logger Class - Methods ### Description The `Logger` class supports all standard methods found on the browser's `console` object, along with several specialized methods for enhanced logging capabilities, including MCP-specific functions and utilities for managing log output. ### Method Instance Methods ### Standard Console Methods: - `debug(message: string, ...args: any[]): void` - `envDebug(message: string, ...args: any[]): void` - Logs only if the `DEBUG` environment variable is truthy. - `info(message: string, ...args: any[]): void` - `warn(message: string, ...args: any[]): void` - `error(message: string, ...args: any[]): void` - `log(message: string, ...args: any[]): void` - Alias for `info`. - `trace(message?: string, ...args: any[]): void` - `table(data: any, columns?: string[]): void` - Displays tabular data. - `group(label?: string): void` - Starts a new nested log group. - `groupCollapsed(label?: string): void` - Starts a collapsed nested log group. - `groupEnd(): void` - Ends the current log group. - `time(label?: string): void` - Starts a timer. - `timeEnd(label?: string): void` - Stops a timer and logs the duration. - `timeLog(label?: string, ...args: any[]): void` - Logs the current value of a timer. - `count(label?: string): void` - Increments a counter. - `countReset(label?: string): void` - Resets a counter. - `assert(condition: boolean, message?: string, ...args: any[]): void` - Logs if the condition is false. - `clear(): void` - Clears the console output. - `dir(obj: any, options?: any): void` - Displays an interactive list of properties of a JavaScript object. - `dirxml(obj: any): void` - Renders XML/HTML expression. ### Special Methods: - `mcpError(message: string, ...args: any[]): void` - Logs an error message regardless of the `mcpMode` setting. - `child(prefix: string): Logger` - Creates a new logger instance with a prefix that combines the parent's prefix and the new prefix. - `setMcpMode(enabled: boolean): void` - Dynamically enables or disables MCP mode. - `setLevel(level: LogLevel): void` - Changes the logger's level at runtime. - `setPrefix(prefix: string): void` - Updates the logger's prefix. - `setLogFile(filePath: string): Promise` - Sets or changes the file path for persistent logging. Returns a Promise that resolves when the file stream is ready. - `close(): Promise` - Closes the file stream associated with the logger and flushes any pending writes. Returns a Promise that resolves upon completion. ``` -------------------------------- ### Create MCP Logger with Legacy API Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Shows the legacy API for `createMcpLogger`, which is deprecated and will be removed in v2.0.0. It allows creating a logger with an optional prefix and file path, and an optional options object to override defaults. The new options-based API is recommended for new development. ```typescript // Legacy API (Deprecated, will be removed in v2.0.0): createMcpLogger(prefix?: string, logToFile?: string): Logger createMcpLogger(prefix?: string, logToFile?: string, options?: Partial): Logger // ⚠️ LEGACY: Still works but only captures errors by default const legacyLogger = createMcpLogger("MyServer", "./logs/mcp.log"); // ⚠️ LEGACY: With options override const enhancedLegacy = createMcpLogger("MyServer", "./logs/mcp.log", { level: "info" // Override to capture more levels }); ``` -------------------------------- ### Critical: Initialize MCP Logger Before Any Logging Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Demonstrates the correct initialization order for the MCP logger to ensure all logging is captured. It replaces the global console object at the earliest possible point in application startup. ```typescript // ✅ CORRECT: Do this FIRST, before importing any other modules import { createMcpLogger } from "@alcyone-labs/simple-mcp-logger"; globalThis.console = createMcpLogger("MCP-Server") as any; // Now import your application code import "./my-mcp-server.js"; ``` ```typescript // ❌ WRONG: Too late, some logging may have already occurred import "./my-mcp-server.js"; import { createMcpLogger } from "@alcyone-labs/simple-mcp-logger"; globalThis.console = createMcpLogger("MCP-Server") as any; ``` -------------------------------- ### Winston Adapter for MCP-Safe Logging Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Integrates Winston logger with MCP-safe transports. Ensures that logs are handled correctly within the MCP protocol, optionally logging to files. Requires the 'winston' package. ```typescript // Import adapters separately to avoid bundling unused dependencies import { createWinstonTransport } from "@alcyone-labs/simple-mcp-logger/adapters"; import winston from "winston"; // Replace your existing Winston transports with MCP-safe transport const logger = winston.createLogger({ transports: [ createWinstonTransport({ level: "debug", mcpMode: true, // Automatically suppresses STDOUT in MCP mode prefix: "MCP-Server", logToFile: "./logs/mcp-server.log", // Optional: log to file }), ], }); // Your existing logging code works unchanged logger.info("Processing MCP request"); // Safe in MCP mode, written to file logger.error("Request failed"); // Safe in MCP mode, written to file ``` -------------------------------- ### Pino Adapter for MCP-Safe Logging Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Integrates Pino logger with MCP-safe destinations. Ensures that logs are handled correctly within the MCP protocol, optionally logging to files. Requires the 'pino' package. ```typescript // Import adapters separately to avoid bundling unused dependencies import { createPinoDestination } from "@alcyone-labs/simple-mcp-logger/adapters"; import pino from "pino"; // Replace your existing Pino destination with MCP-safe destination const destination = createPinoDestination({ level: "debug", mcpMode: true, // Automatically suppresses STDOUT in MCP mode prefix: "MCP-Server", logToFile: "./logs/mcp-server.log", // Optional: log to file }); const logger = pino({ level: "debug" }, destination); // Your existing logging code works unchanged logger.info("Processing MCP request"); // Safe in MCP mode, written to file logger.error("Request failed"); // Safe in MCP mode, written to file ``` -------------------------------- ### createMcpLogger Factory Function Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Details the `createMcpLogger` factory function, which provides two APIs: a recommended options-based API (v1.2.0+) and a legacy API for backward compatibility. Both allow creating MCP-compliant loggers. ```APIDOC ## Factory Function - createMcpLogger ### Description `createMcpLogger` is a factory function used to create `Logger` instances that are MCP-compliant. It offers a modern, options-based API (recommended) and a legacy API for compatibility with older versions. This function is ideal for setting up loggers specifically for MCP environments or when needing fine-grained control over MCP behavior. ### Method Factory Function ### Options-Based API (v1.2.0+ - Recommended): ```typescript interface McpLoggerOptions { level?: LogLevel; // Default: 'error' mcpMode?: boolean; // Default: true prefix?: string; // Optional prefix logToFile?: string; // Optional file path } createMcpLogger(options: McpLoggerOptions): Logger ``` ### Legacy API (Deprecated): ```typescript createMcpLogger(prefix?: string, logToFile?: string): Logger createMcpLogger(prefix?: string, logToFile?: string, options?: Partial): Logger ``` ### Parameters (Options-Based API): #### Request Body - **options** (McpLoggerOptions) - An object containing configuration for the logger. - **level** (LogLevel) - Optional - The minimum logging level ('debug' | 'info' | 'warn' | 'error' | 'silent'). Defaults to 'error'. - **mcpMode** (boolean) - Optional - Enables MCP mode by default (true). Set to `false` to disable MCP suppression. - **prefix** (string) - Optional - A prefix string to be added to all log messages. - **logToFile** (string) - Optional - A file path for persistent log storage. ### Examples: ```typescript // ✅ NEW: Using the recommended options-based API const logger = createMcpLogger({ prefix: "MyServer", logToFile: "./logs/mcp.log", level: "debug" // Captures all log levels }); // ⚠️ LEGACY: Using the legacy API (defaults to 'error' level and MCP mode) const legacyLogger = createMcpLogger("MyServer", "./logs/mcp.log"); // ⚠️ LEGACY: Using legacy API with options override const enhancedLegacy = createMcpLogger("MyServer", "./logs/mcp.log", { level: "info" // Overrides default level to capture 'info' and above }); ``` ### Response #### Success Response (200) Returns a configured `Logger` instance. ``` -------------------------------- ### General Purpose Logging (Non-MCP) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Illustrates how to use `createCliLogger` for general-purpose logging in applications like web servers, APIs, or CLI tools. This method provides a convenient way to set up a logger with a specific level and prefix. ```APIDOC ## General Purpose Logging (Non-MCP) ### Description Utilize the `createCliLogger` factory function for creating logger instances suitable for various application types, including web applications, APIs, and command-line interfaces. This function simplifies logger setup by allowing you to specify the logging level and a custom prefix. ### Method Factory Function ### Code Example ```typescript import { createCliLogger } from "@alcyone-labs/simple-mcp-logger"; // Create a logger for CLI applications with 'info' level and 'MyApp' prefix const appLogger = createCliLogger("info", "MyApp"); // Log messages at different levels appLogger.info("Server starting on port 3000"); appLogger.warn("High memory usage detected"); appLogger.error("Database connection failed"); // Utilize all available console methods appLogger.table([{ user: "john", status: "active" }]); appLogger.time("API Response"); // Simulate some operation // ... appLogger.timeEnd("API Response"); ``` ### Usage Notes - `createCliLogger` is ideal when you don't need to replace the global `console` but want a dedicated, configured logger. - You can use all standard console methods (`info`, `warn`, `error`, `table`, `time`, `timeEnd`, etc.) with the logger instance returned by `createCliLogger`. ``` -------------------------------- ### Logger Class Constructor Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Details the `Logger` class constructor, including its configuration options (`LoggerConfig`) which allow customization of logging level, MCP mode, message prefix, and file logging. ```APIDOC ## Logger Class - Constructor ### Description Initializes a new instance of the `Logger` class. The constructor accepts an optional configuration object (`LoggerConfig`) to customize its behavior, including the logging level, MCP mode, message prefix, and the ability to log to a file. ### Method Constructor ### Endpoint `new Logger(config?: Partial)` ### Parameters #### Request Body - **config** (LoggerConfig) - Optional - Configuration object for the logger. - **level** (LogLevel) - Required - The minimum logging level to output ('debug' | 'info' | 'warn' | 'error' | 'silent'). - **mcpMode** (boolean) - Optional - If true, suppresses output unless `mcpError` is used. Defaults to `false`. - **prefix** (string) - Optional - A string to prepend to all log messages. - **logToFile** (string) - Optional - The file path where logs should be persisted. ### Request Example ```json { "config": { "level": "debug", "mcpMode": false, "prefix": "MyService", "logToFile": "./app.log" } } ``` ### Response #### Success Response (200) Returns a new `Logger` instance configured according to the provided options. ``` -------------------------------- ### Logger Class Methods Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Lists the standard console methods supported by the `Logger` class, such as `debug`, `info`, `warn`, `error`, `log`, `table`, `time`, and `timeEnd`. It also includes environment-aware debug logging via `envDebug` and assertion logging via `assert`. ```typescript - `debug(message: string, ...args: any[]): void` - `envDebug(message: string, ...args: any[]): void` - Environment-aware debug logging (only outputs when `DEBUG` env var is truthy) - `info(message: string, ...args: any[]): void` - `warn(message: string, ...args: any[]): void` - `error(message: string, ...args: any[]): void` - `log(message: string, ...args: any[]): void` - Alias for info - `trace(message?: string, ...args: any[]): void` - `table(data: any, columns?: string[]): void` - `group(label?: string): void` - `groupCollapsed(label?: string): void` - `groupEnd(): void` - `time(label?: string): void` - `timeEnd(label?: string): void` - `timeLog(label?: string, ...args: any[]): void` - `count(label?: string): void` - `countReset(label?: string): void` - `assert(condition: boolean, message?: string, ...args: any[]): void` - `clear(): void` - `dir(obj: any, options?: any): void` - `dirxml(obj: any): void` ``` -------------------------------- ### Replace Global Console with SimpleMcpLogger Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md This snippet demonstrates how to globally replace the console object with an instance of SimpleMcpLogger. This should be done at application startup to ensure all subsequent console calls are handled by the logger. It requires the Logger class from '@alcyone-labs/simple-mcp-logger'. ```typescript import { Logger } from "@alcyone-labs/simple-mcp-logger"; // Replace console globally (do this at application startup) const logger = new Logger({ level: "info", prefix: "App" }); globalThis.console = logger as any; // Now all console calls use SimpleMcpLogger console.log("This uses SimpleMcpLogger"); console.error("This too"); ``` -------------------------------- ### Basic File Logging in TypeScript Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Demonstrates how to initialize SimpleMcpLogger for file output, specifying the log file path. It logs messages to both the console and the specified file. Remember to close the logger to ensure all data is written. ```typescript import { Logger, createMcpLogger } from "@alcyone-labs/simple-mcp-logger"; // Create logger with file output const logger = new Logger({ level: "info", logToFile: "./logs/app.log", // Directory created automatically }); logger.info("This goes to both console and file"); logger.error("Errors are logged to file too"); // Always close the logger when done to flush pending writes await logger.close(); ``` -------------------------------- ### File Logging Best Practices: Absolute Paths in TypeScript Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Recommends using absolute paths for log files in production environments to avoid issues related to the current working directory. ```typescript import { resolve } from "node:path"; const logFile = resolve(process.cwd(), "logs", "app.log"); const logger = new Logger({ logToFile: logFile }); ``` -------------------------------- ### Test Basic Logging Functionality (JavaScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/browser-demo.html This JavaScript function demonstrates the basic logging capabilities of the SimpleMcpLogger. It logs messages at different levels (debug, info, warn, error, log) using a pre-initialized logger instance. The output is intended to be viewed in the browser's developer console. ```javascript window.testBasicLogging = function() { console.log('=== Testing Basic Logging ==='); appLogger.debug('This is a debug message'); appLogger.info('This is an info message'); appLogger.warn('This is a warning message'); appLogger.error('This is an error message'); appLogger.log('This is a log message (alias for info)'); }; ``` -------------------------------- ### Create MCP Logger with Options-Based API Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Demonstrates the recommended new options-based API for `createMcpLogger` (v1.2.0+). This API allows configuring the logger with an `McpLoggerOptions` object, specifying level, MCP mode, prefix, and log file path. This is the preferred method for creating MCP-compliant loggers. ```typescript interface McpLoggerOptions { level?: LogLevel; // Default: 'error' (for backward compatibility) mcpMode?: boolean; // Default: true prefix?: string; // Optional prefix logToFile?: string; // Optional file path } createMcpLogger(options: McpLoggerOptions): Logger // ✅ NEW: Options-based API (recommended) const logger = createMcpLogger({ prefix: "MyServer", logToFile: "./logs/mcp.log", level: "debug" // Capture all levels }); ``` -------------------------------- ### Test Timing Functionality (JavaScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/browser-demo.html This JavaScript function demonstrates the timing features of SimpleMcpLogger, specifically `time`, `timeLog`, and `timeEnd`. It simulates an asynchronous operation using `setTimeout` and logs checkpoints and the final duration, useful for measuring performance. ```javascript window.testTiming = function() { console.log('=== Testing Timing ==='); appLogger.time('API Call'); // Simulate async operation setTimeout(() => { appLogger.timeLog('API Call', 'Checkpoint: received response'); setTimeout(() => { appLogger.timeEnd('API Call'); }, 100); }, 200); }; ``` -------------------------------- ### Importing SimpleMcpLogger Modules in TypeScript Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Shows how to import the core logger and adapter modules from the SimpleMcpLogger package. The core logger has no external dependencies, while adapters require peer dependencies. ```typescript // Core logger (no external dependencies bundled) import { Logger } from "@alcyone-labs/simple-mcp-logger"; // Adapters (requires peer dependencies) import { SimpleMcpWinstonTransport } from "@alcyone-labs/simple-mcp-logger/adapters"; ``` -------------------------------- ### Hijacking Global Console for MCP Safety (TypeScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Demonstrates how to replace the global `console` object with an MCP-safe logger instance. This ensures that all logging, including from third-party libraries, automatically becomes MCP-compliant. ```typescript import { createMcpLogger } from "@alcyone-labs/simple-mcp-logger"; // Replace console at startup (before any other code runs) const mcpLogger = createMcpLogger("MCP-Server"); globalThis.console = mcpLogger as any; // Now ALL console calls are MCP-safe console.log("This is safe"); // Suppressed in MCP mode console.error("This is safe too"); // Suppressed in MCP mode someLibrary.log("Third-party logs"); // Also safe! ``` -------------------------------- ### Create CLI Logger Function Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md This snippet describes the `createCliLogger` factory function, which is used to create loggers specifically for command-line interface (CLI) applications. It takes an optional log level and prefix as arguments. ```typescript // Create logger for CLI mode createCliLogger(level?: LogLevel, prefix?: string): Logger ``` -------------------------------- ### Logger Class Constructor and Configuration Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md This snippet details the constructor for the `Logger` class and its configuration options. The constructor accepts an optional `LoggerConfig` object to customize log level, MCP mode, prefix, and file logging. `LogLevel` can be 'debug', 'info', 'warn', 'error', or 'silent'. ```typescript new Logger(config?: Partial) interface LoggerConfig { level: LogLevel; // 'debug' | 'info' | 'warn' | 'error' | 'silent' mcpMode: boolean; // Suppress output when true prefix?: string; // Prefix for all messages logToFile?: string; // Optional file path for persistent logging } ``` -------------------------------- ### Enhanced MCP Logging with Options API (TypeScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Explains the options-based API for `createMcpLogger` introduced in v1.2.0. This allows for capturing all log levels (debug, info, warn, error) in MCP mode, unlike the default behavior which only captures errors. ```typescript // ❌ DEFAULT: Only captures errors (backward compatible) const basicLogger = createMcpLogger("MyServer", "./logs/mcp.log"); basicLogger.debug("Not captured"); // Silent - below error level basicLogger.info("Not captured"); // Silent - below error level basicLogger.error("Captured"); // ✅ Written to file // ✅ ENHANCED: Capture ALL log levels with options API const comprehensiveLogger = createMcpLogger({ prefix: "MyServer", logToFile: "./logs/mcp.log", level: "debug", // Captures debug, info, warn, error mcpMode: true // MCP compliant (default) }); comprehensiveLogger.debug("✅ Captured"); // Written to file comprehensiveLogger.info("✅ Captured"); // Written to file comprehensiveLogger.warn("✅ Captured"); // Written to file comprehensiveLogger.error("✅ Captured"); // Written to file ``` -------------------------------- ### Dynamic File Path Changes in TypeScript Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Shows how to dynamically change the log file path during runtime, including enabling and disabling file logging by setting the path to an empty string. ```typescript const logger = new Logger({ level: "info" }); // Start logging to one file await logger.setLogFile("./logs/startup.log"); logger.info("Application starting"); // Switch to a different file await logger.setLogFile("./logs/runtime.log"); logger.info("Now logging to runtime file"); // Disable file logging await logger.setLogFile(""); // Empty string disables file logging ``` -------------------------------- ### Environment-Aware Debug Logging with envDebug() Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Provides controlled debug logging that only outputs when the `DEBUG` environment variable is set. This prevents log pollution in production while allowing detailed debugging during development. Logs are prefixed with `[ENV-DEBUG]`. ```typescript import { Logger, createMcpLogger } from "@alcyone-labs/simple-mcp-logger"; const logger = createMcpLogger("MyApp"); // These will only output when DEBUG environment variable is truthy logger.envDebug("Processing user request", { userId: 123 }); logger.envDebug("Database query", { sql: "SELECT * FROM users" }); logger.envDebug("API response time", { duration: "245ms" }); // Regular debug logging (always respects log level) logger.debug("This always logs when level allows"); ``` ```bash # Enable debug logging DEBUG=1 node my-mcp-server.js # Disable debug logging (production) node my-mcp-server.js # Enable with custom value DEBUG=verbose node my-mcp-server.js ``` ```typescript // Logs to file only when DEBUG is set const logger = createMcpLogger("MCP-Server", "./logs/debug.log"); logger.envDebug("Server state", serverState); // Only written when DEBUG=1 ``` -------------------------------- ### McpLoggerOptions Interface Definition (TypeScript) Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Defines the `McpLoggerOptions` interface used for configuring the enhanced MCP logger. This includes options for log level, MCP mode, message prefix, and file logging. ```typescript interface McpLoggerOptions { level?: LogLevel; // 'debug' | 'info' | 'warn' | 'error' | 'silent' mcpMode?: boolean; // Default: true (MCP compliant) prefix?: string; // Optional prefix for all messages logToFile?: string; // Optional file path for persistent logging } ``` -------------------------------- ### Logger Class Special Methods Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Details special methods available on the `Logger` class, including `mcpError` (always logs), `child` (creates a prefixed logger), and methods for controlling logger behavior like `setMcpMode`, `setLevel`, `setPrefix`, `setLogFile`, and `close`. ```typescript - `mcpError(message: string, ...args: any[]): void` - Always logs even in MCP mode - `child(prefix: string): Logger` - Create child logger with combined prefix - `setMcpMode(enabled: boolean): void` - Toggle MCP mode - `setLevel(level: LogLevel): void` - Change log level - `setPrefix(prefix: string): void` - Change prefix - `setLogFile(filePath: string): Promise` - Set or change log file path - `close(): Promise` - Close file stream and flush pending writes ``` -------------------------------- ### Preventing STDOUT Contamination in MCP Development Source: https://github.com/alcyone-labs/simple-mcp-logger/blob/main/README.md Highlights the critical issue of `console.log()` calls contaminating STDOUT in MCP servers, leading to communication errors. It advises using `console.error()` or MCP-compliant logging instead. ```typescript // This innocent debug line breaks everything (writes to STDOUT): console.log("Debug: processing request"); // MCP client expects: {"jsonrpc":"2.0","id":1,"result":{...}} // But receives: Debug: processing request{"jsonrpc":"2.0","id":1,"result":{...}} // Result: JSON parse error, connection terminated // The fix is simple - use STDERR instead: console.error("Debug: processing request"); // Safe: goes to STDERR ```