Skip to main content
Glama
pab1it0

adx-mcp-server

execute_query

Run Kusto Query Language queries on Azure Data Explorer databases to get results as dictionaries.

Instructions

Executes a Kusto Query Language (KQL) query against the configured Azure Data Explorer database and returns the results as a list of dictionaries.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The execute_query tool handler function. It takes a KQL query string, validates config, gets a Kusto client, executes the query, formats results, and returns a list of dictionaries.
    async def execute_query(query: str) -> List[Dict[str, Any]]:
        """Execute a KQL query against the configured ADX database."""
        logger.info("Executing KQL query", database=config.database, query_preview=query[:100])
    
        if not config.cluster_url or not config.database:
            logger.error("Missing ADX configuration")
            raise ValueError("Azure Data Explorer configuration is missing. Please set ADX_CLUSTER_URL and ADX_DATABASE environment variables.")
    
        try:
            client = get_kusto_client()
            result_set = client.execute(config.database, query)
            results = format_query_results(result_set)
            logger.info("Query executed successfully", row_count=len(results))
            return results
        except Exception as e:
            logger.error(
                "Query execution failed",
                error=str(e),
                exception_type=type(e).__name__,
                database=config.database
            )
            raise
  • The @mcp.tool decorator registers execute_query as an MCP tool with a description: 'Executes a Kusto Query Language (KQL) query against the configured Azure Data Explorer database and returns the results as a list of dictionaries.'
    @mcp.tool(description="Executes a Kusto Query Language (KQL) query against the configured Azure Data Explorer database and returns the results as a list of dictionaries.")
  • get_kusto_client() is a helper used by execute_query to create and configure a Kusto client with Azure credentials (WorkloadIdentityCredential or DefaultAzureCredential).
    def get_kusto_client() -> KustoClient:
        """
        Create and configure a Kusto client with appropriate Azure credentials.
    
        Prioritizes WorkloadIdentityCredential when running in AKS with workload identity,
        falls back to DefaultAzureCredential for other authentication methods.
    
        Returns:
            KustoClient: Configured Kusto client instance
        """
        tenant_id = os.environ.get('AZURE_TENANT_ID')
        client_id = os.environ.get('AZURE_CLIENT_ID')
        token_file_path = os.environ.get('ADX_TOKEN_FILE_PATH', '/var/run/secrets/azure/tokens/azure-identity-token')
    
        if tenant_id and client_id:
            logger.info(
                "Using WorkloadIdentityCredential",
                client_id=client_id,
                tenant_id=tenant_id,
                token_file_path=token_file_path
            )
            try:
                credential = WorkloadIdentityCredential(
                    tenant_id=tenant_id,
                    client_id=client_id,
                    token_file_path=token_file_path
                )
            except Exception as e:
                logger.warning(
                    "Failed to initialize WorkloadIdentityCredential, falling back",
                    error=str(e),
                    exception_type=type(e).__name__
                )
                credential = DefaultAzureCredential()
        else:
            logger.info("Using DefaultAzureCredential (missing WorkloadIdentity credentials)")
            credential = DefaultAzureCredential()
    
        try:
            kcsb = KustoConnectionStringBuilder.with_azure_token_credential(
                connection_string=config.cluster_url,
                credential=credential
            )
            client = KustoClient(kcsb)
            logger.debug("Kusto client initialized successfully", cluster_url=config.cluster_url)
            return client
        except Exception as e:
            logger.error(
                "Failed to create Kusto client",
                error=str(e),
                exception_type=type(e).__name__,
                cluster_url=config.cluster_url
            )
            raise
  • format_query_results() is a helper used by execute_query to format Kusto query results into a list of dictionaries with column names as keys.
    def format_query_results(result_set) -> List[Dict[str, Any]]:
        """
        Format Kusto query results into a list of dictionaries.
    
        Args:
            result_set: Raw result set from KustoClient
    
        Returns:
            List of dictionaries with column names as keys
        """
        if not result_set or not result_set.primary_results:
            logger.debug("Empty or null result set received")
            return []
    
        try:
            primary_result = result_set.primary_results[0]
            columns = [col.column_name for col in primary_result.columns]
    
            formatted_results = []
            for row in primary_result.rows:
                record = {}
                for i, value in enumerate(row):
                    record[columns[i]] = value
                formatted_results.append(record)
    
            logger.debug("Query results formatted", row_count=len(formatted_results), columns=columns)
            return formatted_results
        except Exception as e:
            logger.error(
                "Error formatting query results",
                error=str(e),
                exception_type=type(e).__name__
            )
            raise
  • validate_table_name() and validate_sample_size() are validation helpers used by other tools (not execute_query directly), but represent the schema validation pattern for the server's tools.
    def validate_table_name(table_name: str) -> str:
        """Validate a KQL table name to prevent injection attacks.
    
        Allows simple identifiers (my_table) and dot-qualified names (database.table).
        Rejects any characters that could enable KQL injection.
        """
        if not table_name or not table_name.strip():
            raise ValueError("Table name cannot be empty")
        table_name = table_name.strip()
        if not _TABLE_NAME_PATTERN.match(table_name):
            raise ValueError(
                f"Invalid table name: '{table_name}'. "
                "Table names must contain only letters, digits, underscores, "
                "and dots (for qualified names like 'database.table')."
            )
        return table_name
    
    def validate_sample_size(sample_size: int) -> int:
        """Validate sample_size is a positive integer."""
        if not isinstance(sample_size, int) or sample_size <= 0:
            raise ValueError(f"sample_size must be a positive integer, got: {sample_size}")
        return sample_size
Behavior2/5

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

No annotations are present, so the description must disclose behavioral traits. It only states that the tool returns a list of dictionaries but does not mention whether queries can modify data, rate limits, or pagination behavior. The lack of safety disclaimers is a gap.

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 sentence that immediately conveys the core action and result format. No unnecessary words or repetition.

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 simplicity of the tool (one parameter) and the presence of an output schema (not shown but indicated), the description covers the essential action. However, it lacks usage guidance and behavioral transparency, making it only minimally adequate.

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

Parameters2/5

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

The single parameter 'query' has no schema description (0% coverage). The description adds the phrase 'Kusto Query Language (KQL)' which clarifies the language but does not explain expected syntax, format, or examples. The value added beyond the schema is minimal.

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

Purpose5/5

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

The description clearly identifies the tool as executing a KQL query against Azure Data Explorer, with a specific verb ('executes') and resource ('KQL query'). It distinguishes itself from siblings like get_table_details by being the only tool that runs arbitrary queries.

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 list_tables or sample_table_data. There is no mention of prerequisites, safety considerations, or typical use cases.

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/pab1it0/adx-mcp-server'

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