Building an AI-Powered Microsoft Entra ID commandline tool

Introduction

This blog post presents a Proof of Concept (PoC) solution that demonstrates how to build an intelligent AI tool capable of querying and analyzing Microsoft Entra ID environments using natural language. The solution combines modern AI capabilities with the Model Context Protocol (MCP) to create a powerful tool for identity management analysis - as part of the assessment process, review your or your customer tenant.

What Does This Solution Can Do?

The ai.entra.console is my .NET 8 console application that operates as an AI-powered agent for discovering, analyzing, and querying organizational identity infrastructure. Why console? Fast to deliver and make first tests and build prototypes before potentially moving to more complex interfaces or solutions.

It supports three main operational modes:

  1. AI-Driven Query Mode - Ask natural language questions about your Entra ID environment and receive intelligent, contextual answers
  2. Company Structure Discovery - Automatically discover and analyze organizational structure from Entra ID groups using LLM-powered batch analysis
  3. Interactive Agent Mode - Conversational AI assistant with direct access to Entra ID via MCP tools

Key Capabilities

  • Natural language querying of Entra ID data (users, groups, applications, devices).
  • Intelligent caching with vector embeddings for semantic search (Proof of Concept and experimental sandbox).
  • Token-optimized chunking for handling enterprise-scale datasets (50k+ users) - to test and review token usage and performance.
  • Dynamic metadata discovery without predefined schemas.
  • READ-ONLY operations ensuring tenant data safety.
  • Service Principal authentication and authorization, but also delegates to user context when needed - yes Lokka supports this!

Architecture Overview

demo

Tools and Libraries

Libraries/NuGet Packages

The solution leverages several key NuGet packages:

AI and Agent Framework

PackageVersionPurpose
Microsoft.Extensions.AI10.10.0AI service abstractions
Microsoft.Extensions.AI.OpenAI10.10.1OpenAI chat client integration
Microsoft.Agents.AI1.24.0Microsoft agent framework
Microsoft.Agents.AI.OpenAI1.24.0OpenAI integration for agents
Microsoft.Extensions.VectorData.Abstractions10.10.0Vector database abstractions

Model Context Protocol

PackageVersionPurpose
ModelContextProtocol2.0.0MCP client for Lokka integration

External Tools

  • Lokka MCP Server (@merill/lokka) - Node.js-based MCP server that bridges to Microsoft Entra ID via Graph API
  • OpenAI API - For chat completions and text embeddings

Model Context Protocol (MCP) Integration

MCP is the key technology that enables our AI agent to interact with Microsoft Entra ID. The integration works as follows:

How It Works

ConsoleApp→MCPClient→StdioClientTransport→npx@merill/lokka→GraphAPI

The application creates an MCP client that communicates with the Lokka server via standard I/O:

var mcpClientTransport = new StdioClientTransport(new StdioClientTransportOptions
{
    Command = "npx",
    Arguments = ["-y", "@merill/lokka"],
    EnvironmentVariables = new Dictionary<string, string>
    {
        { "TENANT_ID", lokkaSettings.TenantId },
        { "CLIENT_ID", lokkaSettings.ClientId },
        { "CLIENT_SECRET", lokkaSettings.ClientSecret }
    }
});
await using var mcpClient = await McpClient.CreateAsync(mcpClientTransport);

Authentication

Microsoft Entra ID Authentication

The solution uses Service Principal authentication with client credentials flow:

{
  "Lokka": {
    "TenantId": "<your-tenant-id>",
    "ClientId": "<your-client-id>",
    "ClientSecret": "<your-client-secret>"
  }
}

The service principal requires appropriate Microsoft Graph API permissions (typically User.Read.All or similar read permissions) to query Entra ID data - use https://permissions.factorlabs.pl to find relevant permissions.

AI Model Authentication

Currently, the solution uses GitHub Copilot API as an OpenAI compatible solution with an API key:

{
  "OpenAI": {
    "Host": "https://api.githubcopilot.com",
    "ApiKey": "<github-copilot-api-key>",
    "Model": "claude-sonnet-4"
  }
}

This provides access to powerful language models for:

  • Query analysis and understanding
  • Contextual answer generation
  • Organizational structure discovery
  • Text embeddings via text-embedding-3-small

Future: Microsoft Foundry Integration

While this PoC currently uses the GitHub Copilot OpenAI API key for AI model access, this can be seamlessly replaced with Microsoft Azure AI Foundry in future iterations.

Benefits of Azure AI Foundry

  • Enterprise-grade security - Integrated with Azure security and compliance features
  • Data residency - Keep your data within specific Azure regions
  • Unified billing - Consolidated with other Azure services
  • Model variety - Access to multiple AI models including Azure OpenAI, Llama, Mistral, and more
  • Private endpoints - Keep AI traffic within your virtual network

Migration Path

The migration would involve:

  1. Deploying models to Azure AI Foundry
  2. Updating the OpenAI client configuration to point to your Foundry endpoint
  3. Using Azure Managed Identity instead of API keys for authentication
{
  "OpenAI": {
    "Host": "https://<your-foundry-instance>.azure.com",
    "ApiKey": "<foundry-api-key-or-managed-identity>",
    "Model": "gpt-4o"
  }
}

Key Implementation Highlights

Vector Database for Intelligent Caching

The solution implements an in-memory vector database that stores organization data with OpenAI embeddings, enabling semantic search across cached data:

// Store data with embeddings
await vectorDbService.StoreDataChunkAsync(data, graphPath, chunkInfo);

// Search semantically
var results = await vectorDbService.SearchAsync(query, topK: 5);

Token-Optimized Chunking

Enterprise environments can have tens of thousands of users and groups. The DataChunkingService intelligently splits large responses:

  • Maximum 100 items per chunk
  • Extracts only key properties
  • Creates aggregate summaries
  • Respects token budgets (default: 2000 tokens per chunk)

Query Pipeline

The EntraQueryPipeline orchestrates a 4-step process:

  1. Analyze - LLM determines required Graph API paths
  2. Check Cache - Semantic search in vector DB
  3. Fetch Data - Dynamic retrieval via MCP if needed
  4. Generate Answer - Context-aware response generation

Demo & results

Chatbot Demo

Question: Is Artiom in the tenant? Show me all details. demo

Company Structure Discovery

For a Demo Entra ID tenant I created groups with a naming convention like: Demo01.Budapest-Production-Interns so show location/city branch and details (like intern) with a single system prompt and Lokka MCP the response is below:

#T##h#eDOG****evoePGENperorlxeaDDDDDrggiottrePLePLePLePLePLaarmbewtmuomuomuomuomuolnaaaromorcorcorcorcorcaliprlnre0pa0pa0pa0pa0panzhyakn1ot1ot1ot1ot1otdSaiOlt.si.si.si.si.sittcLpIWeoWeoGeoBeoWeo3rioeAn(r:nr:nl:nu:nr:nuoDcrcf8o:o:o:d:o:mcniaacrcDcLbGaRcDotstteaileWloWalGpoBleWruotiisstapracrloleluaprerproostewaowao-bosedwaoeeinn*rm-rc-tcPabt-a-rcrbss*usStlPilrla-spLtlau**:c)amaroaolPpeomatt**t:lewonwddresgewei::Guend-ueoctinsourstuscpdistnBCee-acptauftaaues*Wlteirciilsdnt*oicottccat:rgoinmisgaprakrnfeog-reanGeoinnrWomsldlruct-oouutiospaIurplzcbdlnpkt(eoafetefiHdnlopgefro-utrarrosrnnmrVronragaaPStusLtancNampPoiratlergoygoaeneoin)ercstndsa,mcacutlemewlociDnasomtccrtnsrgpisoeakraomswgaeosnwpdienrusoaetmdspiirnnhennkyndafgte(ltitoerwGosrarsiecatslntratrpPlsahmtiertaiebcoPaanoauidrtsynctfuopm)-heicdBea,sdctuuctplicdirWeoIlotafirccTonipixoiacoeccftsaonssliietptltacorieeorwnvormlcuiinapoac(mctlcttPpeioaiuolsoytorleneineamseonesncdno)tomarbtgiianonininzgatgieoong-rwaipdheicallocations(Budapest,Dresden,Wroclaw)andfunctionaldepartments(Sales,Production,Logistics,Finance,HR,IT).Thestructureincludeshierarchicalroledistinctions(Workers,Managers,Interns)andsupportsbothinternalworkforceandexternalcontractors/consultantsacrossalllocations.

Conclusion

This PoC demonstrates the power of combining AI agents with the Model Context Protocol to create intelligent, natural language interfaces for enterprise identity management. The modular architecture allows for easy extension and the planned migration path to Microsoft Azure AI Foundry ensures enterprise readiness.

The solution showcases modern .NET capabilities, including:

  • Microsoft.Extensions.AI abstractions for AI service integration
  • MCP for standardized tool communication
  • In-memory vector databases for semantic caching
  • Token-aware processing for an enterprise scale
  • Still, Libraries for C# are in preview but show great promise for future development

The natural language interface, combined with AI agents and the Model Context Protocol, provides a flexible and powerful way to interact with enterprise identity data, making complex queries and operations more accessible and efficient.

Next Steps

  • Map Entra ID end to end in a canvas - visualize the relationships and dependencies between different identity components. We can start with Custom Policies and expand to other areas like users, groups, and applications. Like azure-resource-group-map from awesome-copilot link to repo with plugins/azure-resource-group-map.
  • Bigger focus to Organization structure and hierarchy within Entra ID, ensuring that all organizational units and their relationships are accurately represented and managed.
  • PIM (Privileged Identity Management) integration to manage and monitor privileged accounts and roles within Entra ID. As canvas? Visualize the relationships and dependencies of privileged roles and their assignments within the organizational structure.

PS> This is a Proof of Concept solution.

Resources