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.

OAuth 2.1 AuthenticationMCP SecurityGoogle OAuthProduction Ready
8
Interactive Steps
Hands-on learning path
2
Learning Phases
Study → Apply patterns
1
Production Deploy
Enterprise-ready

Start Your Security Journey

Prerequisites

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
Essential Reading: MCP Authorization Specification

Before implementing OAuth 2.1 authentication for MCP servers, familiarize yourself with the official Model Context Protocol authorization specification:

Workshop Phases

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
1
Study Authentication PatternsLearn from a working OAuth 2.1 demo
1
Fork and Study the MCP Authentication Demo
Get hands-on with a working OAuth 2.1 MCP server implementation

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.

terminal
# 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

2
Configure Google Cloud Console
Set up Google OAuth 2.1 credentials and configure the authentication flow

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.

3
Configure Environment and Test Locally
Set up your local environment with Google OAuth credentials and test the authentication flow

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.

terminal
# 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.

4
Deploy Authentication Demo to Vercel
Deploy your configured MCP authentication demo to production with environment variables

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.

Navigate 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.

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.

.vscode/mcp.json
{
  "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.

claude_desktop_config.json
{
  "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

2
Apply Authentication PatternsSecure your rolldice MCP server
5
Prerequisites: Verify Your Rolldice MCP Server
Ensure your rolldice MCP server is working locally and deployed before adding authentication

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.md
# 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.

3. Create Authentication Plan

Create an agents.md file in your rolldice project root with step-by-step authentication instructions:

agents.md
# 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:

6
Prepare Your Rolldice MCP Project
Set up your existing rolldice project for OAuth 2.1 authentication

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.

terminal
# 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.

terminal
# 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

7
Implement OAuth 2.1 Authentication
Add Google OAuth authentication to your rolldice MCP server

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:

lib/auth.ts
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:

app/api/mcp/route.ts
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:

Multiple files
# 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:

.env.local
# Google OAuth 2.1 Configuration
GOOGLE_CLIENT_ID=your_google_client_id_here.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
8
Test and Deploy Your Secure MCP Server
Verify authentication works and deploy your secure rolldice server

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.

terminal
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.

.vscode/mcp.json
{
  "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.

claude_desktop_config.json
{
  "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

4. Test Authentication Flow

Verify that your OAuth 2.1 authentication works correctly with your rolldice tools.

Workshop Progress: 0 of 8 steps completed

Phase 1: 0/4 | Phase 2: 0/4
Ready to begin your security journey