Running Microsoft 365 administration through the Entra ID portal or PowerShell works, but it's slow, error-prone, and requires specialized knowledge that not every IT technician has. I wanted a solution where a technician could type "Create a new user named Sarah Chen in Engineering with a Business Basic license" and have it just work — with full audit logging, mandatory confirmation before any changes, and automated weekly security reports delivered to Teams and email.
01 // The Challenge
Small and mid-sized businesses rarely have dedicated Microsoft 365 administrators. The technicians managing user accounts, password resets, MFA enforcement, and license assignments are often the same people handling helpdesk tickets, network issues, and everything else. They need to switch between the Entra ID portal, Exchange admin center, and PowerShell — each with its own interface, terminology, and quirks.
The goal was to build a single conversational interface that handles all common M365 user-management tasks while enforcing security best practices automatically. Every write action requires explicit human confirmation. Every action is logged for compliance. And a weekly security report runs all 8 checks without anyone having to remember to do it.
02 // Architecture Overview
Microsoft Teams / Web Chat
↓
Bot Framework / REST API
↓
LLM Orchestration (LiteLLM)
Tool Calling + Structured Output
↓
Tool Executor
Routes tool calls → Graph API
Audit logging on every operation
↓
Microsoft Graph API
Entra ID · Exchange Online
The LLM layer is provider-agnostic through LiteLLM — the deployment uses xAI's Grok, but swapping to Anthropic Claude, OpenAI, or Azure OpenAI takes only a few settings and no code changes: LLM_PROVIDER, that provider's API key and LLM_MODEL, with AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_DEPLOYMENT in place of the model for Azure OpenAI.
03 // Technology Stack
- Backend — Python 3.11 on Azure App Service (Linux, B1 tier).
- LLM Orchestration — LiteLLM with xAI Grok (
grok-4-1-fast-reasoning). - Microsoft Graph SDK — msgraph-sdk v1.x with Kiota-based RequestConfiguration objects.
- Bot Framework — botbuilder-core for Microsoft Teams integration.
- Web Framework — aiohttp for the async REST API and web chat.
- Audit Storage — Azure Cosmos DB (session history and action audit logs).
- Scheduled Reports — Azure Functions timer trigger (weekly Monday 8 AM UTC).
- Authentication — managed identity with least-privilege Graph API application permissions; Entra ID sign-in for the web chat.
- Security — IP-restricted App Service with Azure Bot Service tag allowlist.
04 // Tool Inventory · 19 Showcase · 27 Production
M365 Guardian exposes its tools to the LLM through function calling: 19 in the public showcase repo, 27 in the production engine. Each tool maps to one or more Microsoft Graph or Exchange Online operations, and every call is logged to Cosmos DB with the requesting technician's identity.
Read operations — searching users or listing every user, getting detailed user profiles (MFA status, sign-in activity, group memberships), listing available licenses, checking mailbox provisioning status, querying Guardian's own audit log, and generating the weekly security report, which it can also show right in the conversation.
Write operations — none of which run without a human Approve (see 05) — include creating users, updating properties, deleting accounts, resetting passwords, enforcing MFA, assigning and removing licenses, managing group memberships, managing shared mailboxes and distribution groups, bulk operations on up to 50 users, and emailing the report.
Added in production — one-step offboarding (disable the account, revoke its sign-in sessions, convert the mailbox to shared, then remove licenses and groups); a search of the tenant's Entra ID directory audit log; listing a user's inbox rules and disabling or deleting a malicious one, the cleanup step for business email compromise (BEC); turning Security Defaults on or off, for tenant-wide MFA on tenants without Entra ID P1; listing shared mailboxes and distribution groups with who has access and who is a member; and Exchange message trace.
05 // The Confirmation Flow · Security by Design
The core safety mechanism is a two-layer confirmation gate, enforced by the server rather than just requested in the prompt. When a technician asks for any write, the model can only propose it: the server makes no change, stores the exact action, and shows a structured summary of precisely what will change as plain text, with every target and value spelled out and passwords never shown. Then a human has to approve it. The Approve / Cancel buttons in the web chat, or the Adaptive Card in Teams, carry a token the server minted for that one action and checks in code, and only an exact approve or cancel decision from them counts, so a prompt-injected model can't approve its own change.
In Teams, while an approval is pending, a typed one-word reply also decides: "approve", "yes", "ok" and similar words approve; "cancel", "no", "stop" and similar words cancel; any other message runs nothing. An approved change runs exactly once, and it is the stored action that runs, not whatever the model says next. Proposing a new change withdraws the older one, and pending approvals expire after 10 minutes, so no stale approval is left live. The bot's replies about an approval report only what really happened: no "Done" or "Cancelled" unless it is so, and a bulk run that partly failed says how many users succeeded.
┌─────────────────────────────────────────┐
│ M365 GUARDIAN — ACTION SUMMARY │
├─────────────────────────────────────────┤
│ Action: Create user │
│ Target: sarah.chen@contoso.com │
│ Changes: │
│ • Display name: Sarah Chen │
│ • Department: Engineering │
│ • License: Microsoft 365 Business │
│ • Password: generated (not shown) │
│ • Change at first sign-in: Yes │
└─────────────────────────────────────────┘
┌─────────────────────────────────────────┐
│ Teams card / web buttons │
│ [ Approve ] [ Cancel ] │
└─────────────────────────────────────────┘
⚠ Nothing runs until a human approves. In Teams,
a one-word reply such as approve / yes / ok
or cancel / no / stop also decides.
06 // Weekly Security Report · 8 Automated Checks
- 01 · MFA Compliance Gaps — users without any registered MFA method.
- 02 · License Optimization — SKUs with significant unused capacity.
- 03 · Privileged Access Hygiene — permanent Global Admin and privileged-role holders.
- 04 · Guest & External Access — stale or unnecessary guest accounts.
- 05 · Legacy Authentication — whether legacy authentication is blocked.
- 06 · Exchange Online Best Practices — external forwarding, from inbox rules and at the mailbox level.
- 07 · Conditional Access Gaps — policy coverage.
- 08 · Password & Auth Hygiene — domains that still make passwords expire; Microsoft's guidance is to drop forced expiry and rely on MFA and banned-password protection.
Two earlier checks, suspicious sign-ins and dormant accounts, were dropped because they need Entra ID P1/P2 and returned nothing usable on the small-business tenants Guardian targets; the MFA check now falls back to a per-user lookup on tenants without premium licensing. Tenant-wide checks page through the whole directory, and a check that can't run is flagged as unavailable, with the reason, instead of passing as OK.
Each check returns a severity (Critical, Warning, or OK), a finding count and the top 5 affected items, plus a remediation command where one applies. The weekly run emails the report as HTML, where those commands appear as "Fix with M365 Guardian" action links that open the chatbot with the command pre-filled. When a Teams conversation is configured, the bot also posts a plain-text version of the report there, without the fix links. In chat, a technician can have the report shown right in the conversation or emailed on request.
07 // Azure Deployment
- App Service (B1 Linux) — hosts the bot endpoint and web chat on Python 3.11.
- Cosmos DB —
sessionsfor owner-scoped conversation state (30-day TTL),audit_logsfor action history (1-year TTL). - Azure Bot Service — registration bridging Teams to the App Service; the bot runs as a user-assigned managed identity, so it holds no password.
- Azure Function App — timer trigger for the weekly report (Monday 8 AM UTC CRON).
- Entra ID Role — the service principal requires the Helpdesk Administrator directory role for password-reset operations, in addition to Graph API application permissions.
The App Service uses Azure platform-level access restrictions, allowing only specific IPs and the Azure Bot Service tag, with all other traffic denied. In production nothing secret sits in app settings: the app reaches Microsoft Graph and Cosmos DB through managed identity, the web sign-in is secretless through Workload Identity Federation, and any secret that remains (such as the LLM API key) is read from Key Vault at startup. Environment variables hold secrets only for local development; nothing is hardcoded. Deployment requires SCM_DO_BUILD_DURING_DEPLOYMENT=true so Azure's Oryx build system installs Python dependencies during deployment.
08 // Production Hardening
- Exchange Online sidecar — shared mailboxes and distribution groups aren't in Microsoft Graph, so a small Exchange Online PowerShell sidecar with a narrow set of operations handles them, reached over managed identity with no shared key. Without it, those tools say so instead of faking success.
- Observability — traces, metrics and request-correlated logs go to Application Insights through OpenTelemetry, from the incoming request through every Graph and LLM call.
- Durable sessions — conversation history lives in Cosmos DB, scoped to its owner, so it survives restarts and no one reads or writes another user's session. If a session can't be read cleanly, the store leaves it alone rather than restoring, overwriting or wiping it.
- HTTP edge — OAuth state on sign-in, an Origin check on chat and approval requests, security headers, and per-user rate limiting, which is available and configurable but off unless set.
- Output and history — bot output is escaped before the web chat renders it, and passwords are scrubbed from stored history.
- Operators allowlist — available and configurable, off unless set: once set, only listed operators can request or approve a change, in the web chat and in Teams.
- Honest results — a failed or unreadable result shows up as unavailable or unknown, not as a success and not as a clean bill of health.
- CI gate — lint, type checks and the test suite run on every change, with an 85% coverage floor.
09 // Web Chat & Teams
10 // LLM Provider Flexibility
PROVIDER LLM_PROVIDER REQUIRED ENV VAR
──────────────────── ───────────── ──────────────────────
xAI / Grok (current) xai XAI_API_KEY
Anthropic Claude anthropic ANTHROPIC_API_KEY
Azure OpenAI azure_openai AZURE_OPENAI_API_KEY
AZURE_OPENAI_ENDPOINT
AZURE_OPENAI_DEPLOYMENT
OpenAI openai OPENAI_API_KEY
LLM_MODEL picks the model for each provider; Azure OpenAI uses AZURE_OPENAI_DEPLOYMENT instead.
11 // Results
12 // Conclusion
M365 Guardian proves that an LLM-powered administration tool can be both powerful and safe. The PoC validated all three target scenarios — user creation with mailbox provisioning, password reset with MFA enforcement, and automated weekly security reporting — running against a live Microsoft 365 tenant with 20 test users. The combination of natural-language understanding, mandatory confirmation gates, and full audit logging creates a system that's faster than the admin portal, more accessible than PowerShell, and more auditable than either.
Showcase repo public; production engine private, available under license. The showcase at github.com/marky224/m365-guardian is source-available and proprietary (all rights reserved): it presents the application source and engineering approach, while the deployment recipe is kept private.