Skip to main content
Glama

search_splunk

Execute Splunk search queries to retrieve log data and analytics results. Specify time ranges and result limits to analyze security events, system performance, or operational data.

Instructions

Execute a Splunk search query and return the results.

Args:
    search_query: The search query to execute
    earliest_time: Start time for the search (default: 24 hours ago)
    latest_time: End time for the search (default: now)
    max_results: Maximum number of results to return (default: 100)
    
Returns:
    List of search results

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
search_queryYes
earliest_timeNo-24h
latest_timeNonow
max_resultsNo

Implementation Reference

  • The main handler function decorated with @mcp.tool() that executes Splunk search queries, handles parameters, connects to Splunk, runs the job, and returns results. This serves as both the handler and registration point.
    @mcp.tool()
    async def search_splunk(search_query: str, earliest_time: str = "-24h", latest_time: str = "now", max_results: int = 100) -> List[Dict[str, Any]]:
        """
        Execute a Splunk search query and return the results.
        
        Args:
            search_query: The search query to execute
            earliest_time: Start time for the search (default: 24 hours ago)
            latest_time: End time for the search (default: now)
            max_results: Maximum number of results to return (default: 100)
            
        Returns:
            List of search results
        """
        if not search_query:
            raise ValueError("Search query cannot be empty")
        
        # Prepend 'search' if not starting with '|' or 'search' (case-insensitive)
        stripped_query = search_query.lstrip()
        if not (stripped_query.startswith('|') or stripped_query.lower().startswith('search')):
            search_query = f"search {search_query}"
        
        try:
            service = get_splunk_connection()
            logger.info(f"🔍 Executing search: {search_query}")
            
            # Create the search job
            kwargs_search = {
                "earliest_time": earliest_time,
                "latest_time": latest_time,
                "preview": False,
                "exec_mode": "blocking"
            }
            
            job = service.jobs.create(search_query, **kwargs_search)
            
            # Get the results
            result_stream = job.results(output_mode='json', count=max_results)
            results_data = json.loads(result_stream.read().decode('utf-8'))
            
            return results_data.get("results", [])
            
        except Exception as e:
            logger.error(f"❌ Search failed: {str(e)}")
            raise
  • Helper function used by search_splunk to establish a connection to the Splunk service supporting both username/password and token authentication.
    def get_splunk_connection() -> splunklib.client.Service:
        """
        Get a connection to the Splunk service.
        Supports both username/password and token-based authentication.
        If SPLUNK_TOKEN is set, it will be used for authentication and username/password will be ignored.
        Returns:
            splunklib.client.Service: Connected Splunk service
        """
        try:
            if SPLUNK_TOKEN:
                logger.debug(f"🔌 Connecting to Splunk at {SPLUNK_SCHEME}://{SPLUNK_HOST}:{SPLUNK_PORT} using token authentication")
                service = splunklib.client.connect(
                    host=SPLUNK_HOST,
                    port=SPLUNK_PORT,
                    scheme=SPLUNK_SCHEME,
                    verify=VERIFY_SSL,
                    token=f"Bearer {SPLUNK_TOKEN}"
                )
            else:
                username = os.environ.get("SPLUNK_USERNAME", "admin")
                logger.debug(f"🔌 Connecting to Splunk at {SPLUNK_SCHEME}://{SPLUNK_HOST}:{SPLUNK_PORT} as {username}")
                service = splunklib.client.connect(
                    host=SPLUNK_HOST,
                    port=SPLUNK_PORT,
                    username=username,
                    password=SPLUNK_PASSWORD,
                    scheme=SPLUNK_SCHEME,
                    verify=VERIFY_SSL
                )
            logger.debug(f"✅ Connected to Splunk successfully")
            return service
        except Exception as e:
            logger.error(f"❌ Failed to connect to Splunk: {str(e)}")
            raise
  • splunk_mcp.py:47-52 (registration)
    Initialization of the FastMCP server instance where tools like search_splunk are registered via decorators.
    mcp = FastMCP(
        "splunk",
        description="A FastMCP-based tool for interacting with Splunk Enterprise/Cloud through natural language",
        version="0.3.0",
        host="0.0.0.0",  # Listen on all interfaces
        port=FASTMCP_PORT
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 states the tool executes a search and returns results, but lacks details on permissions required, rate limits, whether it's read-only or has side effects, response format, or error handling. For a tool with 4 parameters and no annotation coverage, this is a significant gap 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.

Conciseness5/5

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

The description is well-structured and appropriately sized. It starts with a clear purpose statement, followed by a bulleted list of args with explanations and defaults, and ends with return information. Every sentence earns its place by adding value, with no redundant or verbose content, making it easy to parse and understand.

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 complexity (4 parameters, no annotations, no output schema), the description is partially complete. It covers parameter semantics well but lacks behavioral context like permissions or rate limits, and without an output schema, it doesn't detail the structure of the 'List of search results'. This leaves gaps for an AI agent to fully understand tool behavior and outputs.

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

Parameters5/5

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

The description adds substantial meaning beyond the input schema, which has 0% description coverage. It explains each parameter's purpose: 'search_query' as the query to execute, 'earliest_time' and 'latest_time' as time bounds with defaults, and 'max_results' as a limit. This compensates fully for the schema's lack of descriptions, providing clear semantics for all parameters.

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: 'Execute a Splunk search query and return the results.' This specifies the verb ('execute') and resource ('Splunk search query'), making it understandable. However, it doesn't explicitly differentiate this tool from potential siblings like 'list_saved_searches' or 'get_indexes_and_sourcetypes', which might also involve search-related operations, 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 provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'list_saved_searches' for retrieving pre-defined searches or 'get_indexes_and_sourcetypes' for exploring data sources, nor does it specify prerequisites or contexts for executing searches. This lack of comparative information limits its utility for an AI agent in selecting the right tool.

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

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/livehybrid/splunk-mcp'

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