README.md•15.5 kB
# Model Context Protocol (MCP) Server + Microsoft Entra ID OAuth + Todo Management
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 and **comprehensive Microsoft To Do task management capabilities**.
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 and manage their To Do lists, create tasks, set reminders, and more.
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 OAuth Todo Server`
- **Supported account types**:
- For **multi-tenant** support (recommended): Choose **"Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts"**
- For single organization only: Choose **"Accounts in this organizational directory only"**
- **Redirect URI**:
- Type: `Web`
- URI: `https://remote-mcp-entra-oauth-todo.<your-subdomain>.workers.dev/callback`
- Also add: `http://localhost:8789/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)
- `Tasks.ReadWrite` (read and write user's tasks)
- 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 or permissions, just add them in Azure Portal 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 # Use 'common' for multi-tenant, or your specific tenant ID
wrangler secret put COOKIE_ENCRYPTION_KEY # add any random string here e.g. openssl rand -hex 32
wrangler secret put DEFAULT_TIMEZONE # optional, defaults to Europe/London
```
> [!IMPORTANT]
> **Multi-Tenant Configuration**: When setting `ENTRA_TENANT_ID`:
> - Use `common` - Allows both work/school accounts AND personal Microsoft accounts (recommended for multi-tenant)
> - Use `organizations` - Allows only work/school accounts (Azure AD), not personal accounts
> - Use `consumers` - Allows only personal Microsoft accounts
> - Use your specific tenant ID - Only users from that specific tenant
>
> For multi-tenant apps, using `common` ensures tokens are issued in the user's home tenant context, allowing access to their personal resources (like To Do lists) even if they're guest users in other tenants.
> [!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.
**Timezone Configuration:**
- Set `DEFAULT_TIMEZONE` to your preferred timezone (e.g., `Asia/Tokyo`, `America/New_York`, `Europe/London`)
- This timezone is used for all task due dates and reminders unless overridden
- Users can still specify a different timezone per task if needed
- If not set, defaults to `Europe/London`
#### 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://remote-mcp-entra-oauth-todo.<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-todo": {
"command": "npx",
"args": [
"mcp-remote",
"https://remote-mcp-entra-oauth-todo.<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?"
- "Show me all my todo lists"
- "Create a new task in my work list with a due date of next Friday"
- "What tasks do I have due this week?"
### 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:8789`
- For the Authorization callback URL, specify `http://localhost:8789/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=common # Use 'common' for multi-tenant, or your specific tenant ID
COOKIE_ENCRYPTION_KEY=any_random_string_here
DEFAULT_TIMEZONE=Europe/London
```
#### Develop & Test
Run the server locally to make it available at `http://localhost:8789`
`wrangler dev`
To test the local server, enter `http://localhost:8789/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
### User Profile
- **`getUserProfile`** - Get the authenticated user's Microsoft Graph profile
### Todo List Management
- **`listTodoLists`** - Get all todo task lists for the authenticated user
- **`createTodoList`** - Create a new task list with a specified name
- **`updateTodoList`** - Update an existing task list's name
- **`deleteTodoList`** - Delete a task list
### Task Management
- **`listTasks`** - Get all tasks from a specific todo list
- **`getTask`** - Get detailed information about a specific task
- **`createTask`** - Create a new task with optional properties:
- Title (required)
- Body/description
- Due date and time
- Reminder date and time
- Importance level (low, normal, high)
- Categories/tags
- Timezone for dates
- **`updateTask`** - Update any task properties:
- Title
- Body/description
- Status (notStarted, inProgress, completed, waitingOnOthers, deferred)
- Importance level
- Due date and time
- Reminder settings
- Categories
- **`deleteTask`** - Delete a task from a list
### Simple Test Tool
- **`add`** - Add two numbers (for testing the MCP connection)
## Usage Examples
Ask Claude to help you with tasks like:
- "Show me all my todo lists"
- "Create a new list called 'Shopping'"
- "Add a task 'Buy groceries' to my Shopping list with a due date of tomorrow at 5pm"
- "What tasks do I have in my Work list?"
- "Update the task 'Call client' to be high importance and due Friday"
- "Mark the 'Submit report' task as completed"
- "Set a reminder for my 'Team meeting prep' task for tomorrow at 9am"
- "Delete all completed tasks from my Personal list"
## 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
- The `Tasks.ReadWrite` permission is already included for todo functionality
- Grant admin consent if not already done
2. **Add tool in code** ([`src/index.ts`](src/index.ts)):
```typescript
this.server.tool(
"getTodoTaskList",
"Get details of a specific todo task list",
{
listId: z.string().describe("The ID of the todo list to retrieve"),
},
async ({ listId }) => {
const client = Client.init({
authProvider: (done) => {
done(null, this.props!.accessToken);
},
});
try {
const taskList = await client
.api(`/me/todo/lists/${listId}`)
.get();
return {
content: [{ text: JSON.stringify(taskList, 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
### "Tasks.ReadWrite 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, use `common` as tenant ID to support both work/school and personal accounts
- Use `organizations` for work/school accounts only, or `consumers` for personal accounts only
- Make sure the tenant ID matches the one shown in Azure Portal if using a specific tenant
- **Important for guest users**: If users are guests in your tenant but trying to access their personal resources (like To Do), you must use `common` so tokens are issued in their home tenant context
### 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`
### Timezone issues with tasks
- Verify DEFAULT_TIMEZONE is set correctly in your secrets
- Use standard timezone names (e.g., `America/New_York`, not `EST`)
- You can override the default timezone per task by specifying it in the tool parameters
## 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
## License
MIT