Weldon Web

Advanced Auth: Dynamic Discovery for MCP Servers

Updated #Azure#OAuth 2.0#Authentication

Dynamic Discovery for MCP Servers

Your AI agent finds your MCP server. It tries to connect. It gets rejected.

How does the agent know where to go to get the right token? Hardcoding tenant IDs into every single client configuration is a scaling nightmare.

The modern solution is dynamic discovery using RFC 9728. You configure your gateway to tell the agent exactly how to authenticate.

The 401 Unauthorized Handshake

When an agent hits your APIM endpoint without a valid Entra JWT, your gateway intercepts the request.

Instead of just slamming the door with a generic 401 error, APIM triggers your custom mcp-error-handling policy fragment. This fragment intercepts the failure and shapes the response into a structured JSON-RPC error that the agent actually understands.

Returning RFC 9728 Metadata

You guide the agent to the auth server using the HTTP headers.

Inject a structured WWW-Authenticate header into your 401 response. This tells the client exactly where to find your authorization metadata.

WWW-Authenticate: Bearer resource_metadata="https://{host}/.well-known/oauth-protected-resource"
 

Setting Up the .well-known Endpoint

You have to host that metadata document.

Configure the /.well-known/oauth-protected-resource endpoint on your APIM custom domain. When the agent fetches this URL, return a static JSON document pointing directly to your specific Microsoft Entra ID authorization server and tenant. The agent reads it, negotiates the token, and comes back with the right credentials.

See the code here https://github.com/jackweldonweb/apim-mcp-terraform, check license for usage information.