infrastructure / AI systems

From VM to Platform: Re-Architecting a Production MCP Server on Azure App Service

A follow-up to an earlier project that took a local AI-data-access prototype and hardened it into a team-shared service on a single Linux VM. This project takes that same production service and re-platforms it onto fully Terraform-managed, CI/CD-deployed Azure infrastructure — with zero downtime, stronger per-user security, and proper observability — while the original VM kept serving real traffic throughout the entire migration.

The problem

The original service worked and was trusted by its small pilot team, but it carried real operational risk as the company looked to scale it to a larger pilot group and roll it out through its broader AI roadmap:

  • Everything was deployed by hand — Portal clicks, SSH, and a custom shell script with no automated testing, no safe rollback, and no separation between a space to test changes and the system real users depended on.
  • Every database query ran under one shared machine identity. There was no way to tell which specific person asked for what, and no way to enforce that different people should see different data.
  • Secrets lived in a flat configuration file on disk, not a managed secrets store.
  • The only audit trail was a brittle, custom-built logging pipeline assembled from first principles.

The task: move this service onto infrastructure that could be version-controlled, tested before release, and audited properly — without taking it offline, and without asking the existing pilot users to notice anything had changed until it was actually time to cut over.

Architecture

GitHub (source of truth)
    │
    ├── Terraform (/infra)       → provisions every Azure/Entra resource
    └── Application code (/app)  → deployed via CI/CD on every push

         Git push → develop branch         Git push → main branch
                │                                  │
                ▼                                  ▼
       Dev App Service                     Prod App Service
       (own Managed Identity)              (own Managed Identity)
                │                                  │
                ▼                                  ▼
          Synapse (Test path)                Synapse (Prod path)
          — queries run as the signed-in user via OAuth On-Behalf-Of,
            not a shared service identity, on either environment

   Shared across environments:
     - Dedicated Key Vault per environment (no flat secret files)
     - Application Insights (structured telemetry, replacing the
       original custom logging pipeline)
     - The same Entra OAuth gate end users already relied on

Two design decisions mattered most:

  • Full Dev/Prod isolation, not a shared environment. Separate App Services, separate Entra app registrations, separate Key Vaults, separate deployment identities — a mistake or a bad test query in Dev could never touch Prod, by construction, not by convention.
  • Per-user database identity, not a shared one. Rather than carrying the original shared-identity model forward, the migration was used as the opportunity to implement OAuth On-Behalf-Of (OBO): each person's own Entra identity is exchanged for a database-scoped token, so Synapse enforces each individual's own existing permissions — not one blanket grant for every user of the tool.

What I actually did

Built the entire new environment as Terraform, treating the shared, pre-existing resource groups the VM-era infrastructure sat in as strictly read-only data sources — the new resources were additive, never touching anything already relied on by other teams. This included dedicated Entra app registrations (separated cleanly from the deployment-only identities used by CI/CD), Key Vaults, App Services, and Application Insights instances, one full set per environment.

Designed and shipped Git-based CI/CD: a push to a test branch auto-deploys to Dev; promotion to the production branch requires an explicit, reviewed Pull Request and a deliberate, manually-triggered deploy to Prod — a conscious design choice after discovering the organization's current GitHub plan doesn't technically enforce either branch protection or approval gates, and building the safest available substitute rather than assuming a setting worked without verifying it directly.

Diagnosed and fixed three distinct, non-obvious production bugs surfaced only through real end-to-end testing, each with a different root cause:

  • A GitHub Actions deployment identity that failed authentication with a cryptic Azure error — traced to the organization having a newer, undocumented OIDC token format enabled, found by reading the exact rejected value out of the raw error response rather than trusting the standard documented format.
  • A fully "successful" deployment that nonetheless returned Internal Server Error on every request — a WSGI/ASGI protocol mismatch between the web server and the application framework, invisible from the deploy logs and only surfaced by actually exercising a live request.
  • A second authentication failure during OAuth testing — an Entra application identifier configured with a human-readable name instead of the client-ID-based convention the OAuth library actually expected, found by comparing against the exact working configuration of the system being replaced rather than a generic reference example.

Implemented the OAuth On-Behalf-Of token exchange end-to-end: added the required delegated database permission and admin consent to each environment's app registration, then worked with the service's original developer to switch the database connection logic itself from the shared machine identity to the newly-exchanged per-user token — fully removing the shared-identity fallback once the new path was proven working against real data under a real individual account.

Found and fixed a subtle session-persistence bug during that same testing cycle: every deploy was silently logging out every connected user. Root-caused to session state being written to a path that Azure's own platform explicitly does not persist across restarts — confirmed directly by inspecting the platform's own startup diagnostics rather than guessing — and resolved by redirecting that state to the one path that does survive a restart.

Replaced the original custom logging pipeline with Application Insights, catching and correcting an easy-to-miss Terraform behavior along the way: the modern "workspace-based" telemetry model actually keys long-term data retention off a different, underlying resource than the one most documentation and UI surfaces point to — confirmed by testing the actual applied configuration rather than trusting the field that looked right.

Caught a real, self-induced near-miss before it reached production: a Terraform refactor that would have silently wiped a working, already-fixed Entra configuration value, visible only by reading the full planned change set line-by-line before applying it rather than skimming the summary — exactly the discipline that caught it in time.

Ran the final cutover with a defined rollback point: verified every environment end-to-end — authentication, catalog logic, and now-per-user database access — against both Dev and Prod independently before repointing the live connector away from the original VM, then decommissioned the VM only after a confirmed stable validation window.

Enabling the team to own the new workflow

A migration like this only succeeds if the team actually adopts the new process day-to-day — infrastructure nobody uses correctly isn't actually an improvement. Wrote a complete onboarding guide for the service's original developer and the broader pilot stakeholders covering the new architecture, the full Git-based deployment flow end-to-end, and exactly how to connect and test against the new environment — then personally led a live walkthrough: pushing a real change, watching the pipeline deploy it automatically, and verifying it worked through a live conversation with the AI assistant, in front of the team, rather than just describing the process abstractly.

Deliberately handed full ownership of the production deployment step to the service's original developer rather than keeping it as a dependency on me — including a clear, written reference for the complete promotion flow from test to production, so the team wasn't permanently reliant on one person to ship their own changes.

Access control and governance

Closed a real access-control gap discovered mid-migration: the newly created applications had no membership restriction at all, unlike the original service, which gated access through a dedicated security group. Fixed this by requiring explicit group assignment before sign-in is even possible, synced from the organization's existing on-premises identity system rather than managed ad hoc in the cloud directory — consistent with how the organization governs every other application, not a one-off exception for this service.

Extended the same group-based model to govern read access to the new structured logs, so visibility into usage and audit data scales automatically as the pilot group grows, without needing a repeated manual request for every new person added.

Working within real organizational constraints

Not every constraint on a project is technical. Discovered partway through that the organization's current source-control plan doesn't actually enforce either of the two standard safety mechanisms typically relied on before a production deployment — confirmed this directly rather than assuming a configured setting was working, then designed the safest available interim process given that real limitation, and raised the underlying licensing gap to leadership as a concrete, evidence-backed recommendation rather than quietly working around it indefinitely.

The database-level access change this project required also depended on a specific data-platform owner who was unexpectedly unavailable for an extended period. Rather than letting the whole migration stall, independently verified exactly what could and couldn't be done without that person — including directly testing, and ruling out, whether elevated permissions already held elsewhere in the organization could substitute — before escalating with a precise, well-documented account of the actual blocker, which kept the request moving even in their absence.

Security posture

The system now enforces least privilege at every layer, strictly tighter than the original design: a user still can't reach the service at all without passing the same Entra login check as before, but once inside, the database itself now sees and enforces that specific person's own permissions rather than one shared identity's broad access. Every secret lives in a dedicated, per-environment Key Vault rather than a flat file. Every deployment identity is scoped to deploy code to exactly one specific environment and nothing else — a compromised Dev deployment credential has no path to Prod, and vice versa.

Infrastructure as code

A representative excerpt — the per-user database access permission and its automatic admin consent, the piece that makes the On-Behalf-Of flow actually work:

locals {
  # Azure SQL Database's well-known, tenant-independent application ID
  azure_sql_resource_app_id             = "022907d3-0f1b-48f7-badc-1ba6abab6d66"
  azure_sql_user_impersonation_scope_id = "c39ef2d1-04ce-46dc-8a4e-b2be68d48adf"
}

data "azuread_service_principal" "azure_sql" {
  client_id = local.azure_sql_resource_app_id
}

resource "azuread_application" "mcp_server" {
  display_name     = "governed-data-agent-prod"
  sign_in_audience = "AzureADMyOrg"

  required_resource_access {
    resource_app_id = local.azure_sql_resource_app_id
    resource_access {
      id   = local.azure_sql_user_impersonation_scope_id
      type = "Scope"
    }
  }

  # identifier_uris deliberately omitted here and managed via a separate
  # azuread_application_identifier_uri resource instead -- the OAuth
  # library this service depends on expects the identifier URI to match
  # the app's own client ID exactly, which isn't knowable until after
  # the application itself is created.
}

resource "azuread_application_identifier_uri" "mcp_server" {
  application_id = azuread_application.mcp_server.id
  identifier_uri = "api://${azuread_application.mcp_server.client_id}"
}

resource "azuread_service_principal_delegated_permission_grant" "mcp_server_sql" {
  service_principal_object_id          = azuread_service_principal.mcp_server.object_id
  resource_service_principal_object_id = data.azuread_service_principal.azure_sql.object_id
  claim_values                         = ["user_impersonation"]
}

Notable issues along the way

undocumented OIDC token format
A deployment identity rejected every login attempt with a generic "resource not found" error. The organization's GitHub setup used a newer token format embedding internal numeric IDs that standard documentation doesn't describe — found only by reading the literal value Azure rejected, not by trusting the documented pattern.
a transport-layer mismatch invisible in the deploy log
A deployment reported fully successful, yet the live service failed every single request. The web server and the application framework were speaking two different, incompatible versions of the same underlying protocol — a one-line startup configuration fix once correctly diagnosed, but invisible without actually exercising a live request.
an identity convention mismatch
A newly created Entra application used a clean, human-readable identifier instead of the client-ID-based convention its own OAuth library silently expected. Found by comparing directly against the exact configuration of the working system being replaced, rather than a generic reference example.
a platform storage assumption that broke every user's session
Every deployment was silently logging out every connected user. The responsible library was writing session state to a path the hosting platform explicitly does not persist across restarts — confirmed directly against the platform's own startup diagnostics.
a Terraform refactor that would have silently undone a working fix
Moving a configuration value to a more correct, separately-managed resource caused Terraform to plan wiping that same value back to empty, due to how the two resources' ownership of that field interacted. Caught only by reading the full planned change set before applying it.

Skills demonstrated

Terraform · Azure App Service · Microsoft Entra ID · OAuth 2.0 On-Behalf-Of flow · Azure Key Vault · Azure Synapse Analytics · GitHub Actions · CI/CD pipeline design · OIDC federated identity · Application Insights · Log Analytics / KQL · Python (FastMCP) · zero-downtime migration planning · incident diagnosis · infrastructure security review · access governance design · technical enablement and documentation · stakeholder communication · cross-team coordination

Full system diagram

A more detailed view of how a request actually flows through the new system, end to end:

CLIENT SIDE
  Team Member → asks question → AI Assistant

IDENTITY & ACCESS — MICROSOFT ENTRA ID
  Security Group (synced from on-prem identity)
  OAuth 2.0 App Registration (one per environment)
       │  HTTPS request via Custom Connector
       ▼
AZURE APP SERVICE (one per environment, fully isolated)
  ┌─────────────────────────────────────────────┐
  │  ASGI Server Process                         │
  │  MCP Framework + OAuth Provider              │
  │  validates token, then exchanges it          │
  │  (On-Behalf-Of) for a database-scoped token  │
  │  tied to THAT SPECIFIC USER                  │
  └─────────────────────────────────────────────┘
       │
       ├── LOCAL TOOLS (no database contact)
       │     catalog search · query-contract matching
       │     SQL validation · draft review queue
       │
       └── DATA TOOL (per-user identity, not shared)
             governed, read-only query execution
                   │
                   ▼
AZURE SYNAPSE ANALYTICS
  Dedicated SQL Pool — enforces THIS USER's own
  existing permissions, same as if they queried it directly

OBSERVABILITY (per environment)
  Application Insights + Log Analytics workspace
  structured per-call record: user, tool, timing,
  SQL, match confidence — queryable by the team directly

DEPLOYMENT (separate identity, separate trust path)
  GitHub Actions → OIDC federated credential
  → scoped to deploy code to exactly one environment,
    nothing else, no stored secret anywhere

The two identity checks remain deliberately separate, as in the original design — a human login gates access at the top, and the database now enforces that same specific human's own permissions at the bottom, rather than a shared machine identity standing in for everyone.

Outcome

The service now runs on fully version-controlled, Terraform-managed infrastructure with a tested Git-based deployment pipeline, proper per-environment isolation, and database access that reflects each individual user's own permissions rather than one shared identity. The migration completed with no unplanned downtime, and the original VM was decommissioned only once the new platform had been independently verified end-to-end and allowed to prove itself stable in production.

Previous
Previous

Multi-Region AWS Architecture Mapping & Systems Audit

Next
Next

Multi-Cloud Terraform CI/CD Governance Pipeline