Skip to main content
Glama
mfreeman451

JSON Logs MCP Server

by mfreeman451

JSON Logs MCP Server

A Model Context Protocol (MCP) server that enables Claude Desktop (or any MCP client) to read and analyze JSON-formatted log files. This server provides tools for searching, filtering, aggregating, and analyzing structured log data.

Features

  • 📁 Browse log files - List and read JSON-formatted log files

  • 🔍 Search and filter - Query logs by level, module, function, message content, and time range

  • 📊 Aggregate data - Group and analyze logs by various criteria

  • 📈 Statistics - Get comprehensive statistics about your log data

  • 🚀 Fast and efficient - Optimized for handling large log files

Related MCP server: journald-mcp-server

Prerequisites

  • Python 3.11 or higher

  • Claude Desktop (or another MCP client)

Installation

  1. Clone this repository:

git clone https://github.com/mfreeman451/json-logs-mcp-server.git
cd json-logs-mcp-server
  1. Create a virtual environment:

python3 -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
  1. Install the package:

pip install -e .
  1. Create the wrapper script:

cat > run-json-logs-server.sh << 'EOF'
#!/bin/bash
cd "$(dirname "$0")"
source .venv/bin/activate
exec python json_logs_mcp_server.py
EOF
chmod +x run-json-logs-server.sh

Configuration

Configure Log Directory

By default, the server looks for logs in the ./logs directory relative to where it's run. You can change this by setting an environment variable or editing the code:

Option 1: Environment Variable

export MCP_JSON_LOGS_DIR="/path/to/your/logs"

Configure Claude Desktop

Add the server to your Claude Desktop configuration file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

  • Linux: ~/.config/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "json-logs": {
      "command": "/absolute/path/to/run-json-logs-server.sh",
      "args": [],
      "env": {
        "MCP_JSON_LOGS_DIR": "/path/to/your/logs"
      }
    }
  }
}

Important: Use the absolute path to the wrapper script.

Log Format

The server expects JSON log files with one JSON object per line. Each log entry should include these fields:

{
  "timestamp": "2024-01-15T10:30:45.123456",
  "level": "INFO",
  "message": "User authentication successful",
  "module": "auth.handler",
  "function": "authenticate_user",
  "line": 42
}

Required Fields:

  • timestamp - ISO format timestamp

  • level - Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)

  • message - Log message

  • module - Module name

  • function - Function name

  • line - Line number

Sample Log File

Create a file named example.log with the following content to test the server:

{"timestamp": "2024-01-15T10:30:45.123456", "level": "INFO", "message": "Application started successfully", "module": "main", "function": "startup", "line": 15}
{"timestamp": "2024-01-15T10:30:46.234567", "level": "DEBUG", "message": "Loading configuration from config.json", "module": "config.loader", "function": "load_config", "line": 42}
{"timestamp": "2024-01-15T10:30:47.345678", "level": "INFO", "message": "Database connection established", "module": "db.connection", "function": "connect", "line": 78}
{"timestamp": "2024-01-15T10:31:02.456789", "level": "WARNING", "message": "Rate limit approaching: 85% of quota used", "module": "api.ratelimit", "function": "check_limits", "line": 156}
{"timestamp": "2024-01-15T10:32:15.567890", "level": "ERROR", "message": "Failed to authenticate user: Invalid credentials", "module": "auth.handler", "function": "authenticate_user", "line": 203}
{"timestamp": "2024-01-15T10:32:16.678901", "level": "INFO", "message": "Retry attempt 1/3 for user authentication", "module": "auth.handler", "function": "retry_auth", "line": 215}
{"timestamp": "2024-01-15T10:33:45.789012", "level": "CRITICAL", "message": "Database connection lost: Connection timeout", "module": "db.connection", "function": "health_check", "line": 92}
{"timestamp": "2024-01-15T10:33:46.890123", "level": "INFO", "message": "Attempting database reconnection", "module": "db.connection", "function": "reconnect", "line": 105}
{"timestamp": "2024-01-15T10:33:48.901234", "level": "INFO", "message": "Database connection restored", "module": "db.connection", "function": "reconnect", "line": 112}
{"timestamp": "2024-01-15T10:35:22.012345", "level": "DEBUG", "message": "Cache hit for key: user_session_abc123", "module": "cache.manager", "function": "get", "line": 67}

Python Logger Configuration Example

Here's how to configure a Python logger to output in the required format:

import logging
import json
from datetime import datetime

class JSONFormatter(logging.Formatter):
    def format(self, record):
        log_obj = {
            "timestamp": datetime.fromtimestamp(record.created).isoformat(),
            "level": record.levelname,
            "message": record.getMessage(),
            "module": record.module,
            "function": record.funcName,
            "line": record.lineno
        }
        return json.dumps(log_obj)

# Configure logger
logger = logging.getLogger()
handler = logging.FileHandler('app.log')
handler.setFormatter(JSONFormatter())
logger.addHandler(handler)
logger.setLevel(logging.INFO)

# Example usage
logger.info("Application started")
logger.error("Something went wrong")

Available Tools

1. list_log_files

Lists all available log files with metadata.

Example usage in Claude:

  • "List all log files"

  • "Show me available logs"

2. query_logs

Search and filter log entries.

Parameters:

  • files - List of files to search (optional, defaults to all)

  • level - Filter by log level

  • module - Filter by module name

  • function - Filter by function name

  • message_contains - Search in message content

  • start_time - Start time filter (ISO format)

  • end_time - End time filter (ISO format)

  • limit - Maximum results (default: 100)

Example usage in Claude:

  • "Show me all ERROR logs from today"

  • "Find logs containing 'database connection'"

  • "Show errors from the auth module in the last hour"

  • "Search for authentication failures"

3. aggregate_logs

Aggregate log data by specified criteria.

Parameters:

  • files - Files to analyze (optional)

  • group_by - Grouping criteria: "level", "module", "function", or "hour"

Example usage in Claude:

  • "Group logs by level"

  • "Show me which modules generate the most logs"

  • "Analyze log distribution by hour"

  • "What's the breakdown of log levels?"

4. get_log_stats

Get comprehensive statistics about log files.

Example usage in Claude:

  • "Show me log statistics"

  • "What's the overall summary of my logs?"

  • "How many errors do I have total?"

Usage Examples

Once configured, you can interact with your logs through Claude Desktop:

Example 1: Finding Errors

You: "Show me all ERROR and CRITICAL logs from the last hour"
Claude: I'll search for ERROR and CRITICAL level logs from the last hour...
[Uses query_logs tool with level and time filters]

Example 2: Analyzing Patterns

You: "Which module is generating the most warnings?"
Claude: Let me analyze the distribution of WARNING logs by module...
[Uses query_logs with level filter, then aggregate_logs grouped by module]

Example 3: Debugging Issues

You: "Find all database connection errors and show me what happened right before them"
Claude: I'll search for database connection errors and their context...
[Uses query_logs to find specific errors and surrounding log entries]

Running Standalone

You can also run the server standalone for testing (MCP Inspector or other MCP clients):

# With stdio transport (default)
python json_logs_mcp_server.py

Troubleshooting

Server won't start

  • Check that Python 3.8+ is installed: python3 --version

  • Ensure all dependencies are installed: pip install -e .

  • Verify the log directory exists and contains .log files

"spawn python ENOENT" error

  • Use python3 instead of python in your configuration

  • Use the wrapper script with the full absolute path

  • Check that the wrapper script is executable: chmod +x run-json-logs-server.sh

"Module not found" errors

  • Make sure you're using the wrapper script that activates the virtual environment

  • Check that dependencies are installed in the venv: source .venv/bin/activate && pip list

  • Reinstall dependencies: pip install -e .

No logs found

  • Verify log files exist in the configured directory

  • Check that log files have .log extension (files matching *.log* are found)

  • Ensure log files are in the correct JSON format (one JSON object per line)

  • Try with the sample log file provided above

Tools not appearing in Claude

  • Restart Claude Desktop after configuration changes

  • Check the "Connect Apps" section in Claude Desktop

  • Look for error messages in Claude's developer console

  • Ensure the server shows as "Connected" in Claude's UI

Debugging tips

  • Run the server manually to see any error messages: ./run-json-logs-server.sh

  • Check server output: When running via stdio, diagnostic messages appear on stderr

  • Test with a simple log file first using the sample data above

  • Verify JSON format: Each line must be valid JSON with all required fields

Performance Considerations

  • The server loads log files on-demand, not all at once

  • Large log files (>100MB) may take a moment to process

  • Use the limit parameter in queries to control result size

  • Consider rotating log files to maintain performance

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details

Available Tools

4 tools
aggregate_logsC

Aggregate log data by specified criteria

ParametersJSON Schema
NameRequiredDescriptionDefault
filesNoLog files to analyze (default: all files)
group_byNoField to group bylevel

TDQS

C2.6/5.0
Behavior2/5

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

With no annotations, the description carries full burden but only mentions aggregation by criteria without detailing behavioral traits. It omits information on permissions, rate limits, output format, or whether it's read-only or destructive, leaving significant gaps in transparency.

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

Conciseness4/5

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

The description is a single, efficient sentence with no wasted words, making it appropriately sized and front-loaded. However, it lacks structural elements like examples or clarifications that could enhance usability.

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's complexity (aggregation with parameters), lack of annotations, and no output schema, the description is incomplete. It fails to explain what the aggregation returns (e.g., counts, summaries) or provide context needed for effective use, leaving key aspects undocumented.

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?

Schema description coverage is 100%, so the schema fully documents parameters like 'files' and 'group_by'. The description adds no additional meaning beyond what's in the schema, such as explaining criteria or aggregation methods, meeting the baseline for high coverage.

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

Purpose3/5

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

The description states the action ('aggregate') and resource ('log data') but lacks specificity about what aggregation entails (e.g., counting, summing, averaging). It doesn't differentiate from sibling tools like 'get_log_stats' or 'query_logs', leaving the purpose somewhat vague.

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?

No guidance is provided on when to use this tool versus alternatives like 'get_log_stats' or 'query_logs'. The description implies usage for grouping log data but offers no context on prerequisites, exclusions, or comparative scenarios.

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

get_log_statsC

Get overall statistics for log files

ParametersJSON Schema
NameRequiredDescriptionDefault
filesNoLog files to analyze (default: all files)

TDQS

C2.9/5.0
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool 'gets' statistics, implying a read-only operation, but doesn't clarify aspects like performance impact, rate limits, authentication needs, or what 'overall statistics' entail (e.g., counts, averages, summaries). This leaves significant gaps in understanding the tool's behavior.

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's front-loaded and appropriately sized for a simple tool, with every part earning its place.

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 lack of annotations and output schema, the description is incomplete. It doesn't specify what 'overall statistics' include (e.g., format, data types) or behavioral traits like error handling. For a tool that likely returns aggregated data, more context is needed to help the agent use it effectively.

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 input schema has 100% description coverage, with the 'files' parameter documented as 'Log files to analyze (default: all files)'. The description adds no additional meaning beyond this, as it doesn't explain parameter usage or constraints. With high schema coverage, the baseline score of 3 is appropriate, as the schema does the heavy lifting.

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 tool's purpose with a specific verb ('Get') and resource ('overall statistics for log files'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'aggregate_logs' or 'query_logs', which might also involve log analysis.

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 provides no guidance on when to use this tool versus alternatives like 'aggregate_logs' or 'query_logs'. It lacks context about scenarios where overall statistics are preferred over detailed queries or aggregation, leaving the agent to infer usage based on tool names alone.

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

list_log_filesB

List available log files with metadata

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

B3.2/5.0
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 listing files with metadata, but fails to describe key traits like whether this is a read-only operation, if it requires authentication, any rate limits, pagination behavior, or what the metadata includes. This leaves significant gaps for a tool that interacts with log files.

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 front-loads the core action ('List available log files') and adds a useful detail ('with metadata') without any wasted words. It's appropriately sized for a simple tool with no parameters.

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

Completeness3/5

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

Given the tool's simplicity (0 parameters, no output schema), the description is minimally adequate. However, without annotations or an output schema, it lacks details on behavioral aspects like safety or return format, and doesn't address sibling tool differentiation, making it incomplete for optimal agent use.

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

Parameters4/5

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

The input schema has 0 parameters with 100% coverage, so no parameter documentation is needed. The description appropriately focuses on the tool's function without redundant parameter details, earning a high baseline score for this dimension.

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 tool's purpose with a specific verb ('List') and resource ('available log files'), and includes metadata as an output detail. However, it doesn't explicitly differentiate from sibling tools like 'query_logs' or 'aggregate_logs', which might also involve log file operations, preventing 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 provides no guidance on when to use this tool versus alternatives such as 'query_logs' or 'get_log_stats'. It lacks context about use cases, exclusions, or prerequisites, leaving the agent to infer usage from the tool name alone.

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

query_logsC

Search and filter log entries across log files

ParametersJSON Schema
NameRequiredDescriptionDefault
filesNoLog files to search (default: all files)
levelNoFilter by log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
moduleNoFilter by module name
functionNoFilter by function name
message_containsNoFilter by message content (case-insensitive)
start_timeNoStart time filter (ISO format)
end_timeNoEnd time filter (ISO format)
limitNoMaximum number of results

TDQS

C2.9/5.0
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Search and filter' implies a read-only operation, it doesn't specify whether this is safe, whether it requires authentication, how results are returned (e.g., pagination), or any rate limits. The description lacks critical behavioral context for a tool with 8 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 clearly states the tool's purpose without unnecessary words. It's appropriately sized and front-loaded, with every word earning its place.

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?

For a tool with 8 parameters, no annotations, and no output schema, the description is inadequate. It doesn't explain what the tool returns, how results are structured, or behavioral aspects like performance or limitations. The description should provide more context given the tool's complexity and lack of structured metadata.

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?

Schema description coverage is 100%, so the schema fully documents all 8 parameters. The description adds no parameter-specific information beyond what's in the schema, maintaining the baseline score of 3 where the schema does the heavy lifting.

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 tool's purpose as 'Search and filter log entries across log files', which specifies the verb (search/filter) and resource (log entries). It distinguishes from sibling tools like 'aggregate_logs' and 'get_log_stats' by focusing on searching/filtering rather than aggregation or statistics, though it doesn't explicitly mention these distinctions.

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 provides no guidance on when to use this tool versus alternatives like 'aggregate_logs' or 'get_log_stats'. It doesn't mention prerequisites, performance considerations, or typical use cases, leaving the agent to infer usage from the tool name alone.

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

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 4 tool updates
    • First observedaggregate_logs
    • First observedget_log_stats
    • First observedlist_log_files
    • First observedquery_logs

TDQS

B3.4/5.0
Disambiguation5/5

Each tool has a clearly distinct purpose with no overlap: list_log_files enumerates files, query_logs searches entries, aggregate_logs groups data, and get_log_stats provides statistics. The descriptions reinforce these boundaries, making tool selection unambiguous.

Naming Consistency5/5

All tools follow a consistent verb_noun pattern with snake_case (e.g., list_log_files, query_logs). The naming is predictable and readable, using clear verbs like 'list', 'query', 'aggregate', and 'get' that align with their actions.

Tool Count5/5

With 4 tools, this server is well-scoped for handling JSON logs. Each tool serves a distinct function in the log management workflow, from listing files to querying and analyzing data, without being overly sparse or bloated.

Completeness4/5

The toolset covers core log operations: listing files, querying entries, aggregating data, and getting statistics. A minor gap exists in lifecycle management (e.g., no tools for creating, updating, or deleting logs), but agents can likely work with the provided read/analyze functions.

Maintenance

ActivityInactive
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

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/mfreeman451/json-logs-mcp-server'

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