Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions demos/remote-mcp-entra-id-oauth/.dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
ENTRA_CLIENT_ID=<your client id>
ENTRA_CLIENT_SECRET=<your client secret>
ENTRA_TENANT_ID=<your tenant id>
COOKIE_ENCRYPTION_KEY=any_random_string_here
271 changes: 271 additions & 0 deletions demos/remote-mcp-entra-id-oauth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,271 @@
# Model Context Protocol (MCP) Server + Microsoft Entra ID OAuth

This is a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) server that supports remote MCP connections, with Microsoft Entra ID (formerly Azure AD) OAuth built-in.

You can deploy it to your own Cloudflare account, and after you create your own Azure AD OAuth application, you'll have a fully functional remote MCP server that you can build off. Users will be able to connect to your MCP server by signing in with their Microsoft account.

You can use this as a reference example for how to integrate other OAuth providers with an MCP server deployed to Cloudflare, using the [`workers-oauth-provider` library](https://github.com/cloudflare/workers-oauth-provider).

The MCP server (powered by [Cloudflare Workers](https://developers.cloudflare.com/workers/)):

* Acts as OAuth _Server_ to your MCP clients
* Acts as OAuth _Client_ to your _real_ OAuth server (in this case, Microsoft Entra ID)

## Getting Started

Clone the repo & install dependencies: `npm install`

### For Production

Create a new Azure AD Application:
1. Go to [Azure Portal](https://portal.azure.com) → Azure Active Directory → App registrations
2. Click **New registration**
3. Configure:
- **Name**: `MCP Entra ID OAuth Server`
- **Supported account types**: Choose based on your needs
- **Redirect URI**:
- Type: `Web`
- URI: `https://mcp-entra-id-oauth.<your-subdomain>.workers.dev/callback`
- Also add: `http://localhost:8788/callback` (development)

4. After registration, note down:
- **Application (client) ID**
- **Directory (tenant) ID**

5. Create a client secret:
- Go to **Certificates & secrets** → **New client secret**
- Copy the secret value immediately (you won't see it again)

6. Configure API permissions:
- Go to **API permissions** → **Add a permission** → **Microsoft Graph** → **Delegated permissions**
- Add:
- `User.Read` (sign in and read user profile)
- `User.Read.All` (read all users' profiles)
- `People.Read` (read relevant people list)
- Click **Grant admin consent** for your organization

> **💡 Pro Tip**: The code uses `https://graph.microsoft.com/.default` scope, which dynamically requests all pre-consented permissions. To add new tools (like calendar access), just add the permission in Azure Portal (e.g., `Calendars.Read`) and grant consent - no code changes needed!

7. Set secrets via Wrangler:
```bash
wrangler secret put ENTRA_CLIENT_ID
wrangler secret put ENTRA_CLIENT_SECRET
wrangler secret put ENTRA_TENANT_ID
wrangler secret put COOKIE_ENCRYPTION_KEY # add any random string here e.g. openssl rand -hex 32
```

> [!IMPORTANT]
> When you create the first secret, Wrangler will ask if you want to create a new Worker. Submit "Y" to create a new Worker and save the secret.

#### Set up a KV namespace
- Create the KV namespace:
`wrangler kv namespace create "OAUTH_KV"`
- Update the Wrangler file with the KV ID

#### Deploy & Test
Deploy the MCP server to make it available on your workers.dev domain
`wrangler deploy`

Test the remote server using [Inspector](https://modelcontextprotocol.io/docs/tools/inspector):

```
npx @modelcontextprotocol/inspector@latest
```
Enter `https://mcp-entra-id-oauth.<your-subdomain>.workers.dev/mcp` and hit connect. Once you go through the authentication flow, you'll see the Tools working.

You now have a remote MCP server deployed!

### Access the remote MCP server from Claude Desktop

Open Claude Desktop and navigate to Settings -> Developer -> Edit Config. This opens the configuration file that controls which MCP servers Claude can access.

Replace the content with the following configuration. Once you restart Claude Desktop, a browser window will open showing your OAuth login page. Complete the authentication flow to grant Claude access to your MCP server. After you grant access, the tools will become available for you to use.

```json
{
"mcpServers": {
"entra-id": {
"command": "npx",
"args": [
"mcp-remote",
"https://mcp-entra-id-oauth.<your-subdomain>.workers.dev/mcp"
]
}
}
}
```

Once the Tools (under 🔨) show up in the interface, you can ask Claude to use them. For example: "Could you get my user profile from Microsoft Graph?". Claude should invoke the tool and show the result generated by the MCP server.

### For Local Development

If you'd like to iterate and test your MCP server, you can do so in local development. This will require you to create another OAuth App in Azure AD:
- For the Homepage URL, specify `http://localhost:8788`
- For the Authorization callback URL, specify `http://localhost:8788/callback`
- Note your Client ID and generate a Client secret.
- Create a `.dev.vars` file in your project root with:
```
ENTRA_CLIENT_ID=your_development_azure_ad_client_id
ENTRA_CLIENT_SECRET=your_development_azure_ad_client_secret
ENTRA_TENANT_ID=your_tenant_id
COOKIE_ENCRYPTION_KEY=any_random_string_here
```

#### Develop & Test
Run the server locally to make it available at `http://localhost:8788`
`wrangler dev`

To test the local server, enter `http://localhost:8788/mcp` into Inspector and hit connect. Once you follow the prompts, you'll be able to "List Tools".

#### Using Claude and other MCP Clients

When using Claude to connect to your remote MCP server, you may see some error messages. This is because Claude Desktop doesn't yet support remote MCP servers, so it sometimes gets confused. To verify whether the MCP server is connected, hover over the 🔨 icon in the bottom right corner of Claude's interface. You should see your tools available there.

#### Using Cursor and other MCP Clients

To connect Cursor with your MCP server, choose `Type`: "Command" and in the `Command` field, combine the command and args fields into one (e.g. `npx mcp-remote https://<your-worker-name>.<your-subdomain>.workers.dev/mcp`).

Note that while Cursor supports HTTP+SSE servers, it doesn't support authentication, so you still need to use `mcp-remote` (and to use a STDIO server, not an HTTP one).

You can connect your MCP server to other MCP clients like Windsurf by opening the client's configuration file, adding the same JSON that was used for the Claude setup, and restarting the MCP client.

## How does it work?

#### OAuth Provider
The OAuth Provider library serves as a complete OAuth 2.1 server implementation for Cloudflare Workers. It handles the complexities of the OAuth flow, including token issuance, validation, and management. In this project, it plays the dual role of:

- Authenticating MCP clients that connect to your server
- Managing the connection to Microsoft Entra ID's OAuth services
- Securely storing tokens and authentication state in KV storage

#### Durable MCP
Durable MCP extends the base MCP functionality with Cloudflare's Durable Objects, providing:
- Persistent state management for your MCP server
- Secure storage of authentication context between requests
- Access to authenticated user information via `this.props`
- Support for conditional tool availability based on user identity

#### MCP Remote
The MCP Remote library enables your server to expose tools that can be invoked by MCP clients like the Inspector. It:
- Defines the protocol for communication between clients and your server
- Provides a structured way to define tools
- Handles serialization and deserialization of requests and responses
- Supports both Streamable HTTP (recommended) and Server-Sent Events (SSE) protocols for client communication

## Transport Protocol Migration

This example has been updated to support the new **Streamable HTTP** transport protocol, which replaces the deprecated Server-Sent Events (SSE) protocol. The server now exposes both endpoints:

- `/mcp` - **Recommended**: Uses the new Streamable HTTP protocol
- `/sse` - **Deprecated**: Legacy SSE protocol (maintained for backward compatibility)

All new integrations should use the `/mcp` endpoint. The SSE endpoint will be removed in a future version.

## Available Tools

1. **`add`** - Add two numbers (simple test tool)
2. **`getUserProfile`** - Get the authenticated user's Microsoft Graph profile
3. **`searchPeople`** - Search for people in your organization (requires People.Read permission)
4. **`listUsers`** - List users in the organization (requires User.Read.All permission)

## Adding New Tools

Thanks to the `.default` scope used in the OAuth flow, adding new tools is straightforward:

1. **Add permission in Azure Portal**:
- Go to your app → API permissions
- Add the required permission (e.g., `Calendars.Read` for calendar access)
- Grant admin consent

2. **Add tool in code** ([`src/index.ts`](src/index.ts)):

```typescript
this.server.tool(
"getCalendarEvents",
"Get upcoming calendar events",
{
days: z.number().optional().default(7).describe("Number of days to look ahead"),
},
async ({ days }) => {
const client = Client.init({
authProvider: (done) => {
done(null, this.props!.accessToken);
},
});

try {
const events = await client
.api('/me/calendar/events')
.filter(`start/dateTime ge '${new Date().toISOString()}'`)
.top(10)
.get();

return {
content: [{ text: JSON.stringify(events, null, 2), type: "text" }],
};
} catch (error) {
return {
content: [{
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
type: "text"
}],
isError: true,
};
}
}
);
```

3. **Deploy**: `npm run deploy`

That's it! No scope changes needed in the OAuth flow since `.default` dynamically requests all pre-consented permissions.

## Security Notes

- ✅ Client secret is stored as a Cloudflare Workers secret (never exposed to clients)
- ✅ OAuth state parameter prevents CSRF attacks
- ✅ HMAC-signed cookies for approval dialog persistence
- ✅ Access tokens are encrypted in the MCP session token
- ✅ All communication over HTTPS
- ✅ Approval dialog shows client information before authorization

## Troubleshooting

### "Failed to fetch access token"
- Check that client secret is correct and not expired in Azure Portal
- Verify redirect URI matches exactly (including protocol and port)
- Ensure ENTRA_TENANT_ID is correct

### "User.Read.All permission denied"
- Ensure admin consent was granted in Azure Portal
- Check that the user has appropriate permissions in Azure AD
- Verify the permission was added as a **Delegated** permission, not Application permission

### "Invalid tenant"
- Verify ENTRA_TENANT_ID is correct in your secrets
- For multi-tenant apps, you can use `common` as tenant ID
- Make sure the tenant ID matches the one shown in Azure Portal

### Connection issues in Claude Desktop
- Restart Claude Desktop after updating the configuration
- Check that the Worker URL is correct and accessible
- Verify that all secrets are set correctly using `wrangler secret list`

## Architecture

This implementation follows the standard OAuth 2.0 Authorization Code Flow:

1. **User opens MCP client** → Client tries to connect to your MCP server
2. **Server initiates OAuth** → Shows approval dialog with client information
3. **User approves** → Redirects to Microsoft login page
4. **User authenticates** → Microsoft redirects back with authorization code
5. **Server exchanges code** → Uses client secret to get access token from Microsoft
6. **Server fetches user info** → Calls Microsoft Graph to get user profile
7. **Token issued** → MCP client receives encrypted token with user context
8. **Tools available** → Client can now call Microsoft Graph tools with delegated permissions

The Cloudflare Worker acts as a **confidential client** (server-side application) that:
- Securely stores the client secret
- Handles the complete OAuth flow
- Exchanges authorization codes for access tokens
- Makes Microsoft Graph API calls on behalf of the authenticated user
Loading