Advanced Agent
Security
Master OAuth 2.1 authentication patterns for MCP servers. Learn from a working demo, then secure your own AI agents with enterprise-grade authentication.
Start Your Security Journey
Phase 1: Study and deploy a working OAuth 2.1 authentication demo
Phase 2: Apply these patterns to secure your own rolldice MCP server
Required Knowledge:
- • Basic understanding of OAuth 2.1 and authentication flows
- • Familiarity with Google Cloud Console
- • Experience with environment variables
- • Basic Git and deployment knowledge
Required Setup:
- • Google account for Google Cloud Console
- • Node.js 22+ and pnpm installed
- • Code editor (VS Code recommended)
- • Basic familiarity with MCP concepts
Before implementing OAuth 2.1 authentication for MCP servers, familiarize yourself with the official Model Context Protocol authorization specification:
The MCP specification defines OAuth 2.1-based authorization for HTTP transports, enabling secure client-server authentication. Key requirements include:
• Authorization Flow: MCP servers act as OAuth 2.1 resource servers, MCP clients as OAuth clients, with separate authorization servers handling user authentication
• Discovery Mechanisms: Servers must implement OAuth 2.0 Protected Resource Metadata (RFC9728) and support Authorization Server Metadata (RFC8414) or OpenID Connect Discovery
• Security Requirements: HTTPS mandatory, PKCE required for authorization code protection, token audience validation enforced
• Communication Security: All authorization endpoints must use HTTPS, redirect URIs limited to localhost or HTTPS, secure token storage required
• Token Handling: Bearer tokens in Authorization headers, audience-specific validation, no token passthrough to prevent confused deputy attacks
Phase 1: Study Authentication Patterns
- • Fork and study a working OAuth 2.1 MCP authentication demo
- • Set up Google Cloud Console and API keys
- • Deploy and test the authentication flow
- • Understand the MCP authentication architecture
- • Configure with VS Code and Claude Desktop
Phase 2: Apply to Your Projects
- • Apply authentication patterns to rolldice MCP server
- • Implement secure endpoints alongside public ones
- • Add user profile and personalization features
- • Deploy and test production authentication
- • Production security best practices
Start by forking and studying a complete MCP authentication demo that implements OAuth 2.1 with Google Auth. This working example will teach you the authentication patterns before applying them to your own projects.
1. Fork the Authentication Demo
Fork the MCP authentication demo repository to your GitHub account.
2. Clone and Examine the Code
Clone your forked repository and examine the authentication implementation.
# Clone your forked repository
git clone https://github.com/YOUR_USERNAME/mcp-auth-demo.git
cd mcp-auth-demo
# Install dependencies
pnpm install
# Note: Replace YOUR_USERNAME with your actual GitHub username
# Original repository: https://github.com/gocallum/mcp-auth-demo.git
3. Study the Key Files
Examine these critical files to understand the OAuth 2.1 implementation:
app/api/[transport]/route.ts
Main MCP transport handler with authentication
lib/auth.ts
OAuth 2.1 authentication utilities
lib/hello.ts
Protected MCP resource implementation
Configure Google Cloud Console to provide OAuth 2.1 authentication for your MCP server. This includes creating OAuth credentials and setting up the consent screen.
1. Access Google Cloud Console
Sign in to Google Cloud Console and create or select a project for your MCP authentication.
2. Enable APIs and Create Credentials
Enable the Google+ API and create OAuth 2.0 client credentials for web application.
• Application type: Web application
• Authorized redirect URIs: Include your deployment URL + /api/auth/callback
• Scopes: openid, profile, email
Configure your local environment with the Google OAuth credentials and test the authentication demo locally before deploying to production.
1. Configure Environment Variables
Create a .env.local
file with your Google OAuth credentials.
2. Test Locally
Start the development server and test the authentication flow locally.
# Start the development server
pnpm dev
# The app will be available at http://localhost:3000
# Test the authentication by visiting the app and signing in
3. Verify Local Authentication
Test that OAuth 2.1 authentication works locally by accessing http://localhost:3000 and trying the MCP endpoints.
• OAuth login redirects to Google authentication
• Successful authentication returns to your app
• MCP endpoints respond correctly after authentication
• Discovery endpoints are accessible at /.well-known/oauth-* paths
Deploy your authentication demo to Vercel and configure the production environment variables to enable OAuth 2.1 authentication in production.
1. Deploy to Vercel
Deploy your forked repository to Vercel for production testing.
2. Configure Production Environment Variables
In your Vercel project settings, add the same environment variables from your local .env.local file.
•
GOOGLE_CLIENT_ID
- Your Google OAuth client ID•
GOOGLE_CLIENT_SECRET
- Your Google OAuth client secretNavigate to your Vercel project → Settings → Environment Variables to add these values.
3. Update Google OAuth Redirect URIs
Return to Google Cloud Console and add your production URL to the authorized redirect URIs.
• https://your-app-name.vercel.app/api/auth/callback
• Keep your localhost URL for local development
4. Test Production MCP Connection
Configure your MCP clients to test the production deployment.
Configure MCP Clients for Production Testing
Test your deployed authentication demo with production endpoints.
VS Code MCP Extension
Configure VS Code to connect to your MCP server.
{
"servers": {
"mcp-auth-demo": {
"type": "http",
"url": "https://mcp-auth-demo-rust.vercel.app/api/mcp"
},
"mcp-auth-demo-local": {
"type": "http",
"url": "http://localhost:3000/api/mcp"
}
}
}
The MCP extension will handle the OAuth 2.1 authentication flow automatically.
Claude Desktop
Add your server to Claude Desktop configuration.
{
"mcpServers": {
"mcp-auth-demo": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"https://your-auth-demo.vercel.app/api/mcp"
]
}
}
}
Restart Claude Desktop after updating the config. You'll be prompted to authenticate when accessing MCP tools.
Testing the Authentication Flow
• Update MCP configurations with your production URL
• Try to access MCP tools - you should see an OAuth login prompt
• Complete Google authentication in your browser
• Verify that MCP tools work after successful authentication
• Test that unauthenticated requests are properly rejected
/.well-known/oauth-authorization-server
and/.well-known/oauth-protected-resource
) for automatic authentication flow discovery./.well-known/oauth-authorization-server
and/.well-known/oauth-protected-resource
for OAuth 2.1 compliance. Both VS Code MCP extension and Claude Desktop will use these endpoints for automatic authentication flow discovery.Before adding OAuth 2.1 authentication, you must have a working rolldice MCP server from the Builder's Toolkit workshop. This step verifies your prerequisites and creates a plan for applying authentication patterns.
1. Prerequisites Check
Verify your rolldice MCP server meets these requirements:
# Prerequisites Check for Rolldice MCP Server
## Required: Working Rolldice MCP Server
Before adding authentication, ensure your rolldice MCP server is working:
### Local Development
```bash
# Navigate to your rolldice project
cd path/to/your/rolldice-mcp
# Install dependencies
pnpm install
# Start development server
pnpm dev
# Test locally at http://localhost:3000
```
### Production Deployment
- Deployed rolldice server on Vercel
- MCP endpoints accessible via HTTPS
- Basic dice rolling functionality working
## Required: VS Code Insider with MCP
You must have VS Code Insider configured with MCP extension:
### MCP Extension Setup
- VS Code Insider installed (not regular VS Code)
- MCP extension installed and enabled
- GitHub MCP server configured in .vscode/mcp.json
- Successfully tested MCP functionality with GitHub integration
### Test Your MCP Setup
Try these commands in VS Code Insider:
- "create a new repository"
- "list my repositories"
- "create a new issue"
If these don't work, complete the Developer Productivity workshop first:
**Reference**: /developer-productivity workshop has full MCP setup instructions
## Test Commands for Rolldice
Verify these work in your MCP clients:
- "roll a d6"
- "roll 2d10"
- "roll a d20 with advantage"
⚠️ **Important**: If your rolldice server or VS Code MCP setup isn't working, complete the prerequisite workshops first.
2. VS Code Insider MCP Configuration
Ensure you have VS Code Insider with MCP extension properly configured. You'll need this for testing your authenticated MCP server.
• VS Code Insider installed with MCP extension
• GitHub MCP server configured and working
• Basic understanding of .vscode/mcp.json configuration
3. Create Authentication Plan
Create an agents.md
file in your rolldice project root with step-by-step authentication instructions:
# Securing Your Rolldice MCP Server with OAuth 2.1
## Overview
This guide shows how to add OAuth 2.1 authentication to your existing rolldice MCP server using patterns from the [mcp-auth-demo](https://github.com/gocallum/mcp-auth-demo.git) project.
## Prerequisites
- Working rolldice MCP server (locally tested)
- Deployed rolldice MCP server on Vercel
- Google OAuth credentials from previous steps
- Familiarity with the mcp-auth-demo authentication patterns
## Step 1: Study the Authentication Demo
```bash
# Clone the authentication demo for reference
git clone https://github.com/gocallum/mcp-auth-demo.git
cd mcp-auth-demo
```
## Step 2: Copy Authentication Patterns
Apply these key authentication patterns from the demo to your rolldice server:
### 1. Authentication Utilities (lib/auth.ts)
- Google OAuth token verification
- User session management
- Token validation middleware
### 2. Protected MCP Handler (app/api/mcp/route.ts)
- Wrap existing rolldice functionality with authentication
- Maintain dice rolling logic while adding security
- Handle authentication errors gracefully
### 3. OAuth Endpoints
- Authorization server metadata (/.well-known/oauth-authorization-server)
- Protected resource metadata (/.well-known/oauth-protected-resource)
- Authentication callback handlers
## Step 3: Environment Variables
Add these environment variables to both local and production environments:
```env
# Google OAuth Configuration
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
```
## Step 4: Test Authentication Flow
1. Test locally with http://localhost:3000
2. Verify OAuth login redirects work
3. Test dice rolling after authentication
4. Deploy to production with same environment variables
5. Update MCP client configurations
## Step 5: MCP Client Configuration
Update your MCP clients to use the authenticated server:
### VS Code MCP Extension
```json
{
"servers": {
"secure-rolldice": {
"type": "http",
"url": "https://your-secure-rolldice.vercel.app/api/mcp"
}
}
}
```
### Claude Desktop
```json
{
"mcpServers": {
"secure-rolldice": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"https://your-secure-rolldice.vercel.app/api/mcp"
]
}
}
}
```
## Success Criteria
- [ ] OAuth login prompt appears when accessing rolldice tools
- [ ] Google authentication completes successfully
- [ ] Dice rolling works after authentication
- [ ] Unauthenticated requests are properly rejected
- [ ] Both VS Code MCP extension and Claude Desktop work
## Troubleshooting
- Verify Google OAuth redirect URIs include your production domain
- Check environment variables are set in Vercel
- Ensure discovery endpoints return proper OAuth metadata
- Test authentication flow in incognito/private browser window
4. Environment Variables Setup
You'll need the same Google OAuth credentials from Phase 1. Make sure you have:
•
GOOGLE_CLIENT_ID
- From Google Cloud Console•
GOOGLE_CLIENT_SECRET
- From Google Cloud Console• Working OAuth redirect URIs configured
Now you'll apply what you learned from the authentication demo to secure your own rolldice MCP server. This step prepares your existing project for authentication integration.
1. Access Your Rolldice Project
Navigate to your existing rolldice MCP project from the Builder's Toolkit workshop.
# Clone your existing rolldice project from Builder's Toolkit
git clone https://github.com/YOUR_USERNAME/rolldice-mcp.git
cd rolldice-mcp
# Or navigate to your existing project
cd path/to/your/rolldice-mcp
2. Install Authentication Dependencies
Add the same OAuth 2.1 dependencies that you studied in the demo project.
# Install OAuth 2.1 authentication dependencies
pnpm add google-auth-library
pnpm add mcp-handler
# Install additional Next.js dependencies if needed
pnpm add next @types/node typescript
3. Review Your Current Implementation
Examine your current rolldice MCP server structure before adding authentication:
app/api/mcp/route.ts
Current unprotected MCP handler
lib/dice.ts
Your dice rolling business logic
Now implement the OAuth 2.1 authentication layer using the patterns you studied from the mcp-auth-demo. This step secures your rolldice MCP server.
1. Create Authentication Utilities
Add the OAuth token validation and user management utilities:
import { OAuth2Client } from "google-auth-library";
const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
export async function verifyGoogleToken(token: string) {
try {
const ticket = await client.verifyIdToken({
idToken: token,
audience: process.env.GOOGLE_CLIENT_ID,
});
return ticket.getPayload();
} catch (error) {
console.error("Token verification failed:", error);
return null;
}
}
2. Secure Your MCP Handler
Update your MCP route to require authentication while preserving dice functionality:
import { createMcpHandler } from "mcp-handler";
import { verifyGoogleToken } from "@/lib/auth";
import { rollDice, rollMultipleDice } from "@/lib/dice";
// Authenticated MCP handler for rolldice
const handler = createMcpHandler({
async authenticate(authInfo) {
if (!authInfo?.token) {
throw new Error("Authentication required");
}
const payload = await verifyGoogleToken(authInfo.token);
if (!payload) {
throw new Error("Invalid authentication");
}
return { user: payload.email };
},
tools: [
// Your existing rolldice tools with authentication
],
});
export { handler as GET, handler as POST };
3. Add OAuth Discovery Endpoints
Create the OAuth 2.1 discovery endpoints required for MCP authentication:
# Create these OAuth 2.1 discovery endpoints:
# app/api/auth/authorize/route.ts - OAuth authorization endpoint
# app/api/auth/token/route.ts - Token exchange endpoint
# app/api/auth/callback/route.ts - OAuth callback handler
# app/.well-known/oauth-authorization-server/route.ts - Discovery
# app/.well-known/oauth-protected-resource/route.ts - Resource metadata
4. Configure Environment Variables
Add your Google OAuth credentials to your local .env.local file:
# Google OAuth 2.1 Configuration
GOOGLE_CLIENT_ID=your_google_client_id_here.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
Test your authentication implementation locally, then deploy your secure rolldice MCP server and configure Claude Desktop to use it with OAuth 2.1.
1. Test Locally
Start your development server and verify the authentication flow works.
pnpm dev
2. Deploy to Production
Deploy your secure rolldice server using the same environment variables as your demo.
Configure MCP Clients for Secure Server
Set up both VS Code and Claude Desktop to use your new secure rolldice server.
VS Code MCP Extension
Configure VS Code to connect to your MCP server.
{
"servers": {
"secure-rolldice": {
"type": "http",
"url": "https://your-secure-rolldice.vercel.app/api/mcp"
},
"secure-rolldice-local": {
"type": "http",
"url": "http://localhost:3000/api/mcp"
}
}
}
The MCP extension will handle the OAuth 2.1 authentication flow automatically.
Claude Desktop
Add your server to Claude Desktop configuration.
{
"mcpServers": {
"secure-rolldice": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"https://your-secure-rolldice.vercel.app/api/mcp"
]
}
}
}
Restart Claude Desktop after updating the config. You'll be prompted to authenticate when accessing MCP tools.
Testing the Authentication Flow
• OAuth login prompt appears when accessing tools
• Authentication completes successfully
• MCP tools work after authentication
• Unauthenticated requests are properly rejected
/.well-known/oauth-authorization-server
and/.well-known/oauth-protected-resource
) for automatic authentication flow discovery.4. Test Authentication Flow
Verify that your OAuth 2.1 authentication works correctly with your rolldice tools.
• OAuth login prompt appears when accessing rolldice tools
• Google authentication completes successfully
• Dice rolling works after authentication (try "roll a d20")
• Unauthenticated requests return proper error messages
• Both VS Code MCP extension and Claude Desktop work
Workshop Progress: 0 of 8 steps completed