Inferensys

Integration

AI Integration for Microsoft Sentinel KQL Queries

Use AI to assist SOC analysts in writing, optimizing, and explaining Kusto Query Language (KQL) queries for hunting, detection, and investigation within Microsoft Sentinel. Reduce query development time from hours to minutes.
Moody home-office setup in a converted highrise loft, analyst working late with multiple screens showing knowledge graph visualizations, city lights through large windows behind.
ARCHITECTURE FOR ANALYST PRODUCTIVITY

Where AI Fits into the Microsoft Sentinel KQL Workflow

Integrating AI directly into the Kusto Query Language (KQL) authoring and investigation loop reduces manual effort and accelerates threat detection.

AI integration targets three primary surfaces within the Microsoft Sentinel KQL workflow: the Logs query window, Analytics rule authoring, and Hunting notebooks. For an analyst writing a detection query, an AI co-pilot can translate a natural language request (e.g., "find users who logged in after hours from a new country") into a syntactically correct KQL snippet. It can also explain complex, existing queries from the community gallery or optimize them for performance by suggesting better use of operators like join or summarize. Within a hunting session, AI can propose new query hypotheses based on the MITRE ATT&CK framework and recent internal incidents, helping to explore data for subtle adversary behaviors that static rules might miss.

A production implementation wires a secure API gateway (like Azure API Management) between the Sentinel workspace and a governed LLM endpoint (e.g., Azure OpenAI Service). The integration passes sanitized query context, relevant table schemas (like SecurityEvent, SigninLogs, AzureActivity), and User-Defined Functions to the model. Crucially, it never sends raw log data. The system can be extended to create a KQL Assistant chatbot embedded in the Sentinel UI or Teams, allowing analysts to ask iterative follow-up questions to refine results. This shifts the workflow from memorizing KQL syntax to focusing on investigative logic, turning hours of manual query crafting into minutes of guided interaction.

Rollout requires governance to ensure reliability and safety. Implement a human-in-the-loop approval step for any AI-generated query before it's saved as a production analytics rule. Maintain an audit trail linking generated queries to the original user prompt and model version. Start with a pilot focused on incident investigation and hunting query generation, where the cost of a poorly formed query is lower, before expanding to automated detection rule authoring. This approach allows SOC teams to scale their most skilled analysts' knowledge while upleveling junior staff, directly impacting metrics like Mean Time to Query (MTTQ) and hunting coverage.

AI-ASSISTED KQL WORKFLOWS

Key Integration Surfaces in Microsoft Sentinel

AI for Proactive Threat Hunting

Integrate AI directly into the hunting experience to translate analyst hypotheses into executable KQL. Use natural language prompts like "find users who logged in after hours from new countries" to generate starter queries. AI can also analyze the results of hunting queries to suggest related entities, timeframes, or data sources (like Azure Activity or Microsoft 365 Defender logs) to investigate next.

Key Surfaces:

  • The Hunting blade in the Sentinel portal.
  • Notebooks (Jupyter) for advanced, multi-step investigative workflows.
  • Livestream queries for real-time monitoring.

Implementation: Deploy a co-pilot interface that sits alongside the hunting page, using the Sentinel REST API to run and refine generated queries. Cache and learn from successful hunts to improve future suggestions.

SOCIETY OF OPERATIONS

High-Value Use Cases for AI-Assisted KQL

Accelerate threat detection, investigation, and hunting in Microsoft Sentinel by integrating AI directly into the Kusto Query Language workflow. These patterns move beyond simple query generation to embed intelligence into the entire SOC analyst lifecycle.

01

Natural Language to KQL Translation

Analysts describe a hunt hypothesis in plain English (e.g., 'find users who logged in after hours from a new country and accessed sensitive SharePoint sites'), and an AI co-pilot generates the corresponding, syntactically correct KQL. This reduces the learning curve for junior analysts and lets senior hunters focus on strategy, not syntax.

Hours -> Minutes
Query drafting time
02

Query Optimization & Performance Tuning

AI analyzes existing, slow-running KQL queries for hunting or detection rules. It suggests optimizations like adding time filters, improving joins, leveraging materialized views, or restructuring where clauses to reduce execution time and cost. This directly impacts the efficiency of scheduled analytics rules and ad-hoc investigations.

Batch -> Real-time
Feasible query scope
03

Interactive Query Explanation & Debugging

When a complex query returns unexpected results or an error, an AI assistant can explain the query logic step-by-step, identify likely issues in extend or project statements, and suggest fixes. This turns debugging from a solitary, time-consuming task into a guided conversation, speeding up development of custom detection content.

1 sprint
Detection rule development
04

Context-Aware Query Enrichment

AI enhances basic KQL by automatically joining relevant tables based on the investigation context. For example, a query searching for a suspicious process automatically incorporates joins to IdentityInfo, DeviceInfo, and ThreatIntelligenceIndicator tables to pull in user, asset, and IOC context without the analyst manually writing the complex joins.

Same day
Investigation depth
05

Hunting Hypothesis Generation

Based on ingested threat intelligence (e.g., new MITRE ATT&CK techniques) or internal incident trends, AI proposes specific hunting hypotheses and drafts the core KQL query skeletons. Analysts review, refine, and execute. This systematically expands hunting coverage and ensures the SOC proactively looks for emerging threats.

Hours -> Minutes
Campaign discovery
06

KQL-to-Narrative Summarization

After a hunting query returns results, AI analyzes the output data and generates a concise, plain-language summary of what was found (e.g., '10 instances of suspicious PowerShell execution observed on 3 servers, with network connections to a high-risk IP'). This accelerates reporting and handoff to incident response teams.

SOC OPERATIONS

Example AI-Assisted KQL Workflows

These workflows illustrate how AI agents can be embedded into the Microsoft Sentinel analyst workflow to accelerate KQL creation, optimization, and investigation. Each flow connects to Sentinel's APIs, Log Analytics workspace, and the analyst's interface to reduce manual effort and cognitive load.

Trigger: An analyst types a natural language question into a chat interface (e.g., a Teams bot, a custom dashboard widget, or a Copilot pane within the Sentinel UI).

Context/Data Pulled: The AI agent receives the query (e.g., "Show me all failed logins for service accounts from external IPs in the last 24 hours") and the analyst's Entra ID context to understand their permissions and default workspace.

Model or Agent Action:

  1. The agent uses an LLM with few-shot prompting to translate the request into a valid KQL query.
  2. It validates the query structure and references known table schemas (e.g., SigninLogs, AzureActivity).
  3. It returns the KQL and a brief explanation.

System Update or Next Step:

kql
// AI-Generated Query
SigninLogs
| where TimeGenerated > ago(24h)
| where ResultType != "0" // Non-successful logins
| where AccountType == "ServicePrincipal" // Service accounts
| where IPAddress has_any ("external_threat_intel_feed") // Simplified external IP check
| project TimeGenerated, UserPrincipalName, IPAddress, ResultType, ResultDescription, AppDisplayName

The query is presented to the analyst with a "Run in Sentinel" deep link button. The analyst can review, modify, and execute it immediately.

Human Review Point: The analyst must review and approve the generated KQL before execution. The agent logs the original request, generated query, and analyst ID for audit and model feedback.

PRODUCTION-READY KQL ASSISTANCE

Implementation Architecture: Data Flow and Guardrails

A secure, governed architecture for integrating AI-powered KQL assistance directly into the Microsoft Sentinel analyst workflow.

The integration connects to Microsoft Sentinel's Log Analytics Workspace API and Azure OpenAI Service (or your preferred LLM endpoint) via a secure, containerized middleware layer. An analyst's natural language request (e.g., "find failed logins for service accounts in the last 24 hours") is captured from a custom Sentinel workbook or a Teams copilot interface. This request, along with critical context like the relevant Log Analytics workspace ID, table schemas (e.g., SigninLogs, SecurityEvent), and a query history token, is sent to the orchestration service. The service first validates the analyst's RBAC permissions against the target workspace and tables before proceeding.

The core AI step uses a carefully engineered system prompt that includes Sentinel-specific KQL syntax rules, common function patterns (join, summarize, where), and instructions to avoid resource-intensive operations like unbounded search or full-table scans. The generated KQL is then executed in a read-only, time-bound sandbox against a recent sample of the target log data. The results are analyzed to validate the query's basic syntax and return a non-error status. A confidence score is calculated based on schema alignment and execution success. The final output to the analyst is a three-part package: 1) the annotated KQL query, 2) a plain-English explanation of what the query does, and 3) a warning if the query might be computationally expensive, based on estimated data scan volume.

All interactions are logged as custom tables within a dedicated Sentinel governance workspace, capturing the original request, the generated KQL, the confidence score, user ID, timestamp, and workspace context. This creates a full audit trail for compliance and allows SOC leads to review and refine AI performance. Rollout follows a phased approach: starting in a monitor-only mode where queries are suggested but not auto-executed, progressing to a supervised phase with analyst approval required before running in production workspaces. This architecture ensures AI assists the investigation loop without compromising security, performance, or compliance. For related patterns on operationalizing AI findings, see our guide on AI Integration for Microsoft Sentinel Incident Summaries.

AI-ASSISTED KQL WORKFLOWS

Code and Payload Examples

Translating Analyst Intent into Queries

Use an LLM to convert a plain English request into a syntactically correct KQL query. This pattern is ideal for hunting or ad-hoc investigation where analysts know what they're looking for but not the exact schema or KQL functions.

Example Python API call to an LLM service:

python
import openai

def generate_kql_from_natural_language(prompt: str, log_schema_hint: str) -> str:
    system_prompt = f"""You are a KQL expert for Microsoft Sentinel. Given a user's request and a hint about the relevant log table schema, generate a valid Kusto Query Language query.
    Schema Hint: {log_schema_hint}
    Return ONLY the KQL query, no explanations."""
    
    response = openai.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": prompt}
        ],
        temperature=0.1
    )
    return response.choices[0].message.content

# Example usage
user_request = "Find all failed logins for service accounts in the last 24 hours where the source IP is not from our corporate VPN range."
schema_hint = "Table: SigninLogs | Columns: TimeGenerated, Identity, ResultType, IPAddress, Location"
query = generate_kql_from_natural_language(user_request, schema_hint)
print(query)

The generated query might look like: SigninLogs | where TimeGenerated > ago(24h) | where ResultType != "0" | where Identity has "svc_" | where not(ipv4_is_in_range(IPAddress, "10.0.0.0/8"))

AI-ASSISTED KQL WORKFLOWS

Realistic Time Savings and Operational Impact

How AI integration shifts analyst effort from manual query construction to strategic investigation, measured in time saved and workflow improvements.

Workflow StageBefore AIAfter AINotes

Initial Query Drafting

30-60 minutes of manual SPL/KQL translation

2-5 minutes of natural language description

Analyst describes intent; AI generates multiple query options with explanations.

Query Optimization & Debugging

15-45 minutes of trial, error, and performance tuning

Instant syntax correction and performance suggestions

AI reviews query for common pitfalls, suggests indexes, and optimizes time ranges.

Hunting Hypothesis Exploration

Hours to days for manual data exploration across tables

Minutes to generate and test related query variations

AI suggests related data sources (e.g., IdentityLogonEvents, AzureActivity) based on initial hunt premise.

Incident Investigation Context

Manual cross-referencing of entity data across multiple KQL queries

Single natural language question to summarize entity activity

Ask 'What did this user account do in the last 24 hours?' to get a synthesized timeline from relevant tables.

Query Documentation & Knowledge Transfer

Ad-hoc notes or uncommented queries saved privately

Auto-generated comments, purpose statements, and parameter explanations

AI appends inline documentation to saved queries, improving SOC-wide knowledge sharing.

New Data Source Onboarding

Hours of schema review and manual ASIM mapping

Assisted mapping with schema inference and KQL snippet generation

AI accelerates initial query development for new log connectors by suggesting common field mappings.

False Positive Triage

Manual review of query logic and result sampling to identify noise

AI-assisted analysis of query results to highlight common false positive patterns

AI flags results that match known benign patterns (e.g., scheduled tasks, scanner IPs) for faster rule tuning.

ARCHITECTING FOR PRODUCTION

Governance, Security, and Phased Rollout

Integrating AI into a mission-critical SIEM like Microsoft Sentinel requires a deliberate approach to security, access control, and incremental adoption.

A production-ready integration is built on a secure, auditable architecture. This typically involves deploying a dedicated Azure AI service (like Azure OpenAI) within your tenant, ensuring all data processing and model inference occurs within your Azure boundary. The integration layer—often an Azure Function or Logic App—should authenticate to Sentinel using a managed identity with the principle of least privilege, scoped to specific Log Analytics workspaces and granted only the Microsoft.OperationalInsights/workspaces/query/read permission. All AI-generated KQL should be logged to a dedicated Sentinel table for audit, allowing SOC managers to review query usage, model performance, and analyst interactions.

Rollout should follow a phased, risk-managed path to build trust and refine workflows.

  • Phase 1: Analyst Copilot (Read-Only) – Deploy the AI assistant in a sidecar interface, allowing analysts to request KQL explanations, optimizations, and hunting hypotheses. All generated queries are manually reviewed, copied, and executed by the analyst. This phase validates utility and builds familiarity without any automated execution.
  • Phase 2: Supervised Generation – Integrate the assistant directly into the Sentinel Logs query window via a custom workbook or Azure portal extension. Analysts can generate and modify queries in-place, but execution still requires a manual click. Implement a feedback loop where analysts can flag unhelpful or incorrect queries to fine-tune the underlying prompts.
  • Phase 3: Automated Playbook Integration – For mature, high-confidence use cases (e.g., auto-generating a standard investigation query for a specific alert type), embed the AI step into a Sentinel Automation Rule or Logic App playbook. These automated queries should always be executed in a project-limited, time-bound sandbox and their results should trigger a manual approval step before any containment action is taken.

Governance is critical for maintaining control and compliance. Establish a lightweight review board—typically the SOC lead, a senior threat hunter, and a cloud architect—to approve new AI-generated query templates before they are promoted to automated playbooks. Implement content filters on the AI service to prevent the generation of destructive or data-exfiltrating KQL commands. Finally, continuously monitor the integration's cost (AI tokens, Azure Function executions) and performance (query accuracy, analyst time saved) against predefined benchmarks to justify ongoing investment and guide further expansion into other Sentinel surfaces like Analytics Rules or Watchlist management.

MICROSOFT SENTINEL KQL

Frequently Asked Questions

Practical questions for SOC leaders and architects evaluating AI to accelerate Kusto Query Language (KQL) workflows within Microsoft Sentinel.

Analysts describe a hunt or detection need in plain language, and an AI agent generates a syntactically valid KQL query.

Typical workflow:

  1. Trigger: An analyst types a request into a chat interface or a dedicated Sentinel workbook pane: "Find all Azure AD sign-ins from new countries for service principals in the last 48 hours."
  2. Context Pull: The AI system retrieves the relevant table schemas (SigninLogs, AADServicePrincipalSignInLogs) and common query patterns from a knowledge base.
  3. Agent Action: A language model (like GPT-4) generates a draft KQL query, applying best practices for time range filtering and performance.
  4. Output & Review: The query is presented to the analyst with inline explanations of key clauses. The analyst can then run, test, and refine the query directly in Sentinel.

Example AI-Generated Query Snippet:

kql
SigninLogs
| where TimeGenerated > ago(48h)
| where ConditionalAccessStatus == "success"
| where LocationDetails.country != "United States" // Example baseline country
| join kind=inner (
    AADServicePrincipalSignInLogs
    | where TimeGenerated > ago(48h)
    | project ServicePrincipalId, AppDisplayName, TimeGenerated
) on $left.AppId == $right.ServicePrincipalId
| summarize AttemptCount=count(), DistinctUsers=dcount(UserPrincipalName) by AppDisplayName, LocationDetails.country
| order by AttemptCount desc

Governance: All generated queries should be logged for review, and final execution remains under analyst control.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.