Skip to main content
Glama

read_mcp_logs

Access and analyze MCP protocol logs from specified locations, filter entries, and manage pagination for efficient debugging and troubleshooting.

Instructions

Read MCP logs from the standard location

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
customPathNoOptional custom path to log directory (default is system-specific)
fileLimitNoMaximum number of files to read per page (default: 5)
filterNoOptional text to filter log entries by (case-insensitive)
linesNoNumber of lines to read from the end of each log file (default: 100)
pageNoPage number for pagination (default: 1)

Implementation Reference

  • The complete handler implementation for the 'read_mcp_logs' tool. It handles parameter extraction, OS-specific log directory detection, file discovery using glob or fallback readdir, sorting by modification time, pagination, line filtering, tail reading, size limiting with truncation, error handling, and structured JSON-RPC response with pagination info.
    if (request.params.name === "read_mcp_logs") {
        const args = request.params.arguments || {};
        const { 
            lines = 100, 
            filter = "", 
            customPath,
            fileLimit = 5, // Limit number of files to process
            page = 1       // For pagination
        } = args as { 
            lines?: number, 
            filter?: string,
            customPath?: string,
            fileLimit?: number,
            page?: number
        };
    
        try {
            // Get default log directory based on operating system
            let logDir: string;
            
            if (customPath) {
                logDir = customPath;
            } else {
                const homedir = os.homedir();
                
                if (process.platform === 'darwin') {
                    // macOS log path
                    logDir = path.join(homedir, 'Library/Logs/Claude');
                } else if (process.platform === 'win32') {
                    // Windows log path
                    logDir = path.join(homedir, 'AppData/Roaming/Claude/logs');
                } else {
                    // Linux/other OS log path (might need adjustment)
                    logDir = path.join(homedir, '.config/Claude/logs');
                }
            }
            
            await saveLog(`Looking for MCP logs in: ${logDir}`);
            
            let allLogFiles: string[] = [];
            try {
                // Use glob to find all mcp log files
                allLogFiles = await glob(`${logDir}/mcp*.log`);
                
                // If no files found, try a more general pattern as fallback
                if (allLogFiles.length === 0) {
                    allLogFiles = await glob(`${logDir}/*.log`);
                }
            } catch (globError) {
                // If glob fails, try using readdir as a fallback
                const dirFiles = await readdir(logDir);
                allLogFiles = dirFiles
                    .filter(file => file.startsWith('mcp') && file.endsWith('.log'))
                    .map(file => path.join(logDir, file));
                
                // If still no files, try any log file
                if (allLogFiles.length === 0) {
                    allLogFiles = dirFiles
                        .filter(file => file.endsWith('.log'))
                        .map(file => path.join(logDir, file));
                }
            }
            
            // Sort files by modification time (newest first)
            const filesWithStats = await Promise.all(
                allLogFiles.map(async (file) => {
                    const stats = await fs.promises.stat(file);
                    return { 
                        path: file, 
                        mtime: stats.mtime 
                    };
                })
            );
            
            filesWithStats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
            
            // Paginate the files
            const totalFiles = filesWithStats.length;
            const startIndex = (page - 1) * fileLimit;
            const endIndex = Math.min(startIndex + fileLimit, totalFiles);
            
            // Get the files for the current page
            const logFiles = filesWithStats
                .slice(startIndex, endIndex)
                .map(file => file.path);
            
            if (logFiles.length === 0) {
                return {
                    toolResult: {
                        success: false,
                        message: `No log files found in ${logDir}`,
                        logDirectory: logDir
                    }
                };
            }
            
            const results: Record<string, string> = {};
            
            // Process each log file - with size limiting
            const maxBytesPerFile = 100 * 1024; // 100KB per file max
            const maxTotalBytes = 500 * 1024; // 500KB total max
            let totalSize = 0;
            
            for (const logFile of logFiles) {
                try {
                    // Check if we've already exceeded total max size
                    if (totalSize >= maxTotalBytes) {
                        const filename = path.basename(logFile);
                        results[filename] = "[Log content skipped due to total size limits]";
                        continue;
                    }
                    
                    const filename = path.basename(logFile);
                    const content = await readFile(logFile, 'utf8');
                    
                    // Split content into lines
                    let logLines = content.split(/\r?\n/);
                    
                    // Apply filter if provided
                    if (filter) {
                        const filterLower = filter.toLowerCase();
                        logLines = logLines.filter(line => 
                            line.toLowerCase().includes(filterLower)
                        );
                    }
                    
                    // Get the specified number of lines from the end
                    const selectedLines = logLines.slice(-lines);
                    const selectedContent = selectedLines.join('\n');
                    
                    // Check if this file would exceed per-file limit
                    if (Buffer.from(selectedContent).length > maxBytesPerFile) {
                        // Take just enough lines to stay under the limit
                        let truncatedContent = '';
                        let truncatedLines = [];
                        for (let i = selectedLines.length - 1; i >= 0; i--) {
                            const newLine = selectedLines[i] + '\n';
                            if (Buffer.from(newLine + truncatedContent).length <= maxBytesPerFile) {
                                truncatedLines.unshift(selectedLines[i]);
                                truncatedContent = truncatedLines.join('\n');
                            } else {
                                break;
                            }
                        }
                        
                        results[filename] = '[Content truncated due to size limits]\n' + truncatedContent;
                        totalSize += Buffer.from(results[filename]).length;
                    } else {
                        // Store the results if under limit
                        results[filename] = selectedContent;
                        totalSize += Buffer.from(selectedContent).length;
                    }
                } catch (readError) {
                    const errorMessage = readError instanceof Error ? readError.message : String(readError);
                    results[path.basename(logFile)] = `Error reading log: ${errorMessage}`;
                    totalSize += Buffer.from(results[path.basename(logFile)]).length;
                }
            }
            
            return {
                toolResult: {
                    success: true,
                    message: `Read logs from ${logFiles.length} file(s)`,
                    logDirectory: logDir,
                    logs: results,
                    pagination: {
                        currentPage: page,
                        filesPerPage: fileLimit,
                        totalFiles: totalFiles,
                        totalPages: Math.ceil(totalFiles / fileLimit),
                        hasNextPage: endIndex < totalFiles,
                        hasPreviousPage: page > 1
                    }
                }
            };
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            await saveLog(`Error reading MCP logs: ${errorMessage}`);
            
            throw new McpError(ErrorCode.InternalError, `Failed to read MCP logs: ${errorMessage}`);
        }
    }
  • Input schema defining the parameters for the read_mcp_logs tool: lines (tail count), filter (text search), customPath (override dir), fileLimit (files per page), page (pagination).
    inputSchema: {
        type: "object",
        properties: {
            lines: {
                type: "number",
                description: "Number of lines to read from the end of each log file (default: 100)"
            },
            filter: {
                type: "string",
                description: "Optional text to filter log entries by (case-insensitive)"
            },
            customPath: {
                type: "string", 
                description: "Optional custom path to log directory (default is system-specific)"
            },
            fileLimit: {
                type: "number",
                description: "Maximum number of files to read per page (default: 5)"
            },
            page: {
                type: "number",
                description: "Page number for pagination (default: 1)"
            }
        }
    }
  • src/index.ts:37-71 (registration)
    Registration of the 'read_mcp_logs' tool in the ListToolsRequestSchema response, including name, description, and reference to input schema.
    server.setRequestHandler(ListToolsRequestSchema, async () => {
        return {
            tools: [
                {
                    name: "read_mcp_logs",
                    description: "Read MCP logs from the standard location",
                    inputSchema: {
                        type: "object",
                        properties: {
                            lines: {
                                type: "number",
                                description: "Number of lines to read from the end of each log file (default: 100)"
                            },
                            filter: {
                                type: "string",
                                description: "Optional text to filter log entries by (case-insensitive)"
                            },
                            customPath: {
                                type: "string", 
                                description: "Optional custom path to log directory (default is system-specific)"
                            },
                            fileLimit: {
                                type: "number",
                                description: "Maximum number of files to read per page (default: 5)"
                            },
                            page: {
                                type: "number",
                                description: "Page number for pagination (default: 1)"
                            }
                        }
                    }
                }
            ]
        };
    });
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions reading logs but fails to describe key behaviors like whether this is a safe read operation, what the output format looks like, or any limitations (e.g., file size constraints, error handling). This leaves significant gaps for a tool with multiple parameters.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It is appropriately sized and front-loaded, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has 5 parameters, no annotations, and no output schema, the description is incomplete. It does not address what the tool returns, how results are structured, or behavioral aspects like pagination details or error conditions, which are crucial for effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, meaning all parameters are documented in the input schema. The description does not add any additional meaning or context beyond what the schema provides, such as explaining interactions between parameters or typical use cases. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Read') and resource ('MCP logs from the standard location'), providing a specific verb+resource combination. However, with no sibling tools mentioned, it cannot demonstrate differentiation from alternatives, so it falls short of a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description offers no guidance on when to use this tool versus alternatives, prerequisites, or exclusions. It simply states what the tool does without context for its application, leaving the agent to infer usage scenarios.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/klara-research/MCP-Analyzer'

If you have feedback or need assistance with the MCP directory API, please join our Discord server