Skip to main content
Glama
b0ttle-neck

mcp-steampipe

by b0ttle-neck

run_steampipe_query

Execute SQL queries via Steampipe CLI and retrieve results as JSON. Designed for integration with MCP, enabling data retrieval and analysis from Steampipe.

Instructions

Executes a SQL query using the Steampipe CLI and returns the results as a JSON string.

Args: query: The SQL query to execute via Steampipe (e.g., "select login from github_user limit 1"). Ensure the query is valid Steampipe SQL.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes

Implementation Reference

  • The main handler function for the 'run_steampipe_query' tool. It executes Steampipe SQL queries using subprocess, captures JSON output, parses it, and returns formatted JSON or error messages. Registered via @mcp.tool() decorator.
    @mcp.tool()
    def run_steampipe_query(query: str) -> str:
        """
        Executes a SQL query using the Steampipe CLI and returns the results as a JSON string.
    
        Args:
            query: The SQL query to execute via Steampipe (e.g., "select login from github_user limit 1").
                   Ensure the query is valid Steampipe SQL.
        """
        logger.info(f"Received request to run Steampipe query: {query}")
        command = ["steampipe", "query", query, "--output", "json"]
    
        try:
            # Execute the command
            # Set timeout to prevent hanging indefinitely (e.g., 60 seconds)
            result = subprocess.run(
                command,
                capture_output=True,
                text=True,
                check=False, # Don't raise exception on non-zero exit code, handle manually
                timeout=60
            )
    
            # Log stdout/stderr regardless of success for debugging
            if result.stdout:
                logger.info(f"Steampipe stdout:\n{result.stdout[:500]}...") # Log truncated stdout
            if result.stderr:
                logger.warning(f"Steampipe stderr:\n{result.stderr}")
    
            # Check if the command executed successfully
            if result.returncode != 0:
                error_message = f"Steampipe query failed with exit code {result.returncode}."
                if result.stderr:
                    error_message += f"\nError details: {result.stderr}"
                logger.error(error_message)
                # Return the error message to Claude so it knows what went wrong
                return f"Error: {error_message}"
    
            # Attempt to parse the JSON output
            try:
                # Steampipe might return multiple JSON objects (one per row) or a single JSON array
                # Handle potential multiple JSON objects streamed line by line
                lines = result.stdout.strip().splitlines()
                if not lines:
                     logger.info("Steampipe returned no output.")
                     return "[]" # Return empty JSON array if no output
    
                # Try parsing as a single JSON array first (common case)
                try:
                    parsed_json = json.loads(result.stdout)
                    output_string = json.dumps(parsed_json, indent=2)
                    logger.info("Successfully parsed Steampipe output as single JSON object/array.")
                    return output_string
                except json.JSONDecodeError:
                     # If single parse fails, try parsing line by line
                    logger.warning("Failed to parse stdout as single JSON, attempting line-by-line parsing.")
                    parsed_objects = []
                    for line in lines:
                        try:
                            parsed_objects.append(json.loads(line))
                        except json.JSONDecodeError as json_err_line:
                            logger.error(f"Failed to parse line: {line}. Error: {json_err_line}")
                            # Decide how to handle line parse errors, maybe return partial results or error
                    if not parsed_objects:
                         logger.error("Failed to parse any lines from Steampipe output.")
                         return "Error: Failed to parse Steampipe JSON output."
                    output_string = json.dumps(parsed_objects, indent=2)
                    logger.info("Successfully parsed Steampipe output line-by-line.")
                    return output_string
    
            except json.JSONDecodeError as json_err:
                error_message = f"Failed to parse Steampipe output as JSON. Error: {json_err}. Raw output: {result.stdout}"
                logger.error(error_message)
                return f"Error: {error_message}" # Return error and raw output for debugging
    
        except subprocess.TimeoutExpired:
            error_message = "Steampipe query timed out after 60 seconds."
            logger.error(error_message)
            return f"Error: {error_message}"
        except FileNotFoundError:
            error_message = "Steampipe command not found. Make sure it's installed and in your system PATH."
            logger.error(error_message)
            return f"Error: {error_message}"
        except Exception as e:
            error_message = f"An unexpected error occurred while running Steampipe: {e}"
            logger.exception(error_message) # Log full traceback
            return f"Error: {error_message}"
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 that the tool executes a query and returns JSON results, but lacks critical details such as execution timeouts, error handling, authentication requirements, or rate limits. This leaves significant gaps in understanding how the tool behaves in practice.

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 concise, with no wasted words. It starts with a clear purpose statement, followed by a labeled 'Args' section with a bullet point for the single parameter. Each sentence adds value, making it easy to scan and understand quickly.

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 (executing SQL queries with potential side effects) and the lack of annotations and output schema, the description is moderately complete. It covers the basic purpose and parameter semantics but misses behavioral details like error responses, performance considerations, or output structure, which are important for a query execution tool.

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 description adds meaningful context beyond the input schema, which has 0% description coverage. It explains that the 'query' parameter is 'The SQL query to execute via Steampipe' and provides an example, clarifying that it must be 'valid Steampipe SQL.' This compensates well for the schema's lack of detail, though it doesn't cover all potential edge cases.

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: 'Executes a SQL query using the Steampipe CLI and returns the results as a JSON string.' It specifies the verb ('executes'), resource ('SQL query'), and output format ('JSON string'). However, with no sibling tools mentioned, there's no explicit differentiation from alternatives, 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 minimal usage guidance. It includes an example query but does not specify when to use this tool versus other methods (e.g., direct database access or other query tools). There is no mention of prerequisites, error conditions, or typical use cases beyond the basic example.

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/b0ttle-neck/mcp-steampipe'

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