Skip to content

Latest commit

ย 

History

18 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

MCP OAuth Framework

The "Rails for MCP OAuth" - Build OAuth-enabled MCP servers in minutes, not hours.

npm version TypeScript License: MIT

Transform 200+ lines of OAuth boilerplate into 20 lines of clean, production-ready code.

โšก Quick Start (2 Minutes)

npm install @sg20/mcp-oauth-framework

Create a GitHub MCP Server:

import { BaseMCPServer } from '@sg20/mcp-oauth-framework/base';

class GitHubServer extends BaseMCPServer {
  constructor() {
    super({
      name: 'github-server',
      version: '1.0.0',
      providers: [{
        name: 'github',
        clientId: process.env.GITHUB_CLIENT_ID!,
        authorizationUrl: 'https://github.com/login/oauth/authorize',
        tokenUrl: 'https://github.com/login/oauth/access_token',
        scope: ['repo', 'user:email']
      }]
    });
  }

  async initialize() {
    this.addTool({
      name: 'list-repos',
      description: 'List user repositories',
      auth: { required: true, provider: 'github' },
      handler: async () => {
        const response = await this.makeAuthenticatedRequest(
          'github', 
          'https://api.github.com/user/repos'
        );
        return response.json();
      }
    });
  }
}

new GitHubServer().start();

That's it! You now have a fully functional OAuth-enabled MCP server with:

  • โœ… Secure PKCE OAuth 2.0 flow
  • โœ… Automatic token management
  • โœ… Browser-based authentication
  • โœ… Production-ready error handling

๐ŸŽฏ Why This Framework?

โŒ Without Framework (The Hard Way)

// 200+ lines of OAuth boilerplate:
// - PKCE implementation
// - Token storage & encryption  
// - Browser flow management
// - Token refresh logic
// - Error handling
// - Security validation
// - MCP integration
// ... and much more

โœ… With Framework (The Easy Way)

// 20 lines of clean code:
class MyServer extends BaseMCPServer {
  constructor() {
    super({ providers: [oauthProvider] });
  }
  async initialize() {
    this.addTool(/* your tool */);
  }
}

Result: 90% less code, 100% more reliability

๐Ÿš€ Complete Example: GitHub MCP Server

See our complete GitHub server example that demonstrates:

  • 15 GitHub API tools - repos, issues, PRs, files, search
  • Production-ready - full error handling, validation, logging
  • 2-minute setup - simple .env configuration
  • Real OAuth flow - works with Claude Desktop out of the box

Live Example Usage

User: "List my GitHub repositories"

What happens:

  1. ๐ŸŒ Browser opens to GitHub OAuth page
  2. โœ… User clicks "Authorize"
  3. ๐Ÿ”„ Tokens stored securely locally
  4. ๐Ÿ“‹ Repository list appears in Claude
  5. ๐Ÿš€ Next time: instant results (no browser needed)

๐Ÿ—๏ธ Framework Architecture

Core Modules

@sg20/mcp-oauth-framework/
โ”œโ”€โ”€ base              # MCP server foundation
โ”‚   โ”œโ”€โ”€ BaseMCPServer # Abstract base class
โ”‚   โ””โ”€โ”€ ToolRegistry  # Tool management with auth
โ”œโ”€โ”€ auth              # OAuth implementation  
โ”‚   โ”œโ”€โ”€ AuthManager   # Authentication orchestrator
โ”‚   โ”œโ”€โ”€ OAuthFlow     # PKCE browser flow
โ”‚   โ””โ”€โ”€ TokenStore    # Secure token storage
โ””โ”€โ”€ shared            # Common utilities
    โ”œโ”€โ”€ types         # TypeScript interfaces
    โ””โ”€โ”€ utils         # OAuth helpers & validation

Security Features

  • ๐Ÿ” PKCE Flow - Proof Key for Code Exchange prevents code interception
  • ๐Ÿ”’ Encrypted Storage - Tokens encrypted with machine-specific keys
  • ๐Ÿ”„ Auto Refresh - Expired tokens refreshed automatically
  • โœ… Scope Validation - Tools validate required OAuth permissions
  • ๐Ÿ›ก๏ธ Secure Defaults - Minimal permissions, safe storage locations

๐Ÿ“š Framework API

BaseMCPServer

The foundation for all OAuth-enabled MCP servers:

class MyServer extends BaseMCPServer {
  constructor(options: BaseMCPServerOptions) {
    super(options);
  }

  // Required: Implement your server initialization
  async initialize(): Promise<void> {
    this.addTool({
      name: 'my-tool',
      description: 'My awesome tool',
      auth: { required: true, provider: 'github', scopes: ['repo'] },
      handler: async (params, context) => {
        // context.auth contains authenticated user info
        return await this.makeAuthenticatedRequest('github', '/api/endpoint');
      }
    });
  }

  // Required: Cleanup on shutdown
  async cleanup(): Promise<void> {
    // Your cleanup logic
  }
}

Available Methods

// Tool registration
protected addTool(definition: ToolDefinition): void

// Authenticated API requests
protected makeAuthenticatedRequest(
  provider: string, 
  url: string, 
  options?: RequestInit,
  requiredScopes?: string[]
): Promise<Response>

// Manual authentication
protected requireAuth(provider: string, scopes?: string[]): Promise<AuthenticatedRequest>

// Logging
protected log(message: string, level?: 'info' | 'warn' | 'error'): void

OAuth Provider Configuration

interface OAuthProvider {
  name: string;                    // Unique identifier (e.g., 'github')
  clientId: string;               // OAuth client ID
  clientSecret?: string;          // OAuth client secret (optional with PKCE)
  authorizationUrl: string;       // Authorization endpoint
  tokenUrl: string;              // Token exchange endpoint  
  scope: string[];               // Required OAuth scopes
  additionalParams?: Record<string, string>; // Extra parameters
}

Tool Definition

interface ToolDefinition {
  name: string;                   // Tool name (kebab-case)
  description: string;           // Tool description for users
  auth?: {                       // Authentication requirements
    required: boolean;
    provider?: string;           // OAuth provider name
    scopes?: string[];          // Required scopes
    message?: string;           // Custom auth prompt
  };
  handler: (params: any, context: RequestContext) => Promise<any>;
}

๐Ÿ› ๏ธ Supported OAuth Providers

Built-in Support

  • GitHub - Repositories, issues, pull requests, files
  • Google - Drive, Gmail, Calendar APIs
  • Microsoft - Office 365, OneDrive, Teams
  • Custom - Easy to add any OAuth 2.0 provider

Adding Custom Providers

const customProvider: OAuthProvider = {
  name: 'my-service',
  clientId: process.env.MY_SERVICE_CLIENT_ID!,
  authorizationUrl: 'https://myservice.com/oauth/authorize',
  tokenUrl: 'https://myservice.com/oauth/token',
  scope: ['read', 'write'],
  additionalParams: {
    audience: 'https://myservice.com/api'
  }
};

๐ŸŽฎ Usage with Claude Desktop

Simple Configuration

Add to your Claude Desktop config (~/Library/Application Support/Claude/claude_desktop_config.json):

{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["/path/to/your/server/dist/index.js"]
    }
  }
}

That's it! The server automatically:

  • โœ… Reads configuration from .env file
  • โœ… Validates OAuth credentials
  • โœ… Provides helpful error messages
  • โœ… Handles authentication flow

Environment Configuration

Create .env in your server directory:

# Required
GITHUB_CLIENT_ID=your_github_client_id

# Optional but recommended  
GITHUB_CLIENT_SECRET=your_github_client_secret

# Optional: Enable debug logging
DEBUG=false

๐Ÿƒโ€โ™‚๏ธ Getting Started

1. Try the Example

The fastest way to understand the framework:

git clone https://github.com/swayamg20/mcp-framework.git
cd mcp-framework/examples/github-server

# Follow the 2-minute setup guide
cat SIMPLE-SETUP.md

2. Build Your Own Server

mkdir my-mcp-server && cd my-mcp-server
npm init -y
npm install @sg20/mcp-oauth-framework dotenv

# Create your server (see API examples above)
# Add to Claude Desktop config
# Start building amazing OAuth tools!

3. Join the Community

  • GitHub Issues - Bug reports and feature requests
  • Discussions - Share your servers and get help
  • Examples - Browse community-built servers
  • Contributing - Help improve the framework

๐Ÿ”ง Advanced Usage

Multi-Provider Servers

class MultiServiceServer extends BaseMCPServer {
  constructor() {
    super({
      name: 'multi-service-server',
      version: '1.0.0',
      providers: [
        githubProvider,
        googleProvider,
        slackProvider
      ]
    });
  }
}

Custom Tool Middleware

this.addTool({
  name: 'advanced-tool',
  description: 'Tool with custom logic',
  auth: { required: true, provider: 'github', scopes: ['repo'] },
  handler: async (params, context) => {
    // Access authenticated user info
    const { tokens, user } = context.auth!;
    
    // Custom validation
    if (!user.email?.endsWith('@company.com')) {
      throw new Error('Only company users allowed');
    }
    
    // Make multiple authenticated requests
    const [repos, issues] = await Promise.all([
      this.makeAuthenticatedRequest('github', '/user/repos'),
      this.makeAuthenticatedRequest('github', '/issues')
    ]);
    
    return { repos: await repos.json(), issues: await issues.json() };
  }
});

Error Handling

try {
  const result = await this.makeAuthenticatedRequest('github', '/user/repos');
  return result.json();
} catch (error) {
  if (error.code === 'AUTHENTICATION_REQUIRED') {
    // User needs to re-authenticate
    throw new Error('Please re-authenticate with GitHub');
  }
  if (error.code === 'INSUFFICIENT_SCOPE') {
    // User needs more permissions
    throw new Error('Additional GitHub permissions required');
  }
  // Handle other errors
  throw error;
}

๐Ÿš€ Production Deployment

Environment Variables

# Required
GITHUB_CLIENT_ID=your_production_client_id

# Recommended for production
GITHUB_CLIENT_SECRET=your_production_client_secret

# Optional configuration
DEBUG=false
OAUTH_PORT=8080
OAUTH_HOST=localhost
OAUTH_CALLBACK_PATH=/oauth/callback

Security Best Practices

  • โœ… Use HTTPS in production - Configure proper callback URLs
  • โœ… Validate all inputs - Framework provides validation helpers
  • โœ… Monitor token usage - Implement logging and monitoring
  • โœ… Regular security updates - Keep dependencies updated
  • โœ… Never commit secrets - Always use environment variables

Performance Tips

  • ๐Ÿš€ Token reuse - Framework automatically caches valid tokens
  • ๐Ÿš€ Concurrent requests - Use Promise.all() for parallel API calls
  • ๐Ÿš€ Scope optimization - Request only necessary permissions
  • ๐Ÿš€ Error recovery - Implement retry logic for transient failures

๐Ÿ“– Documentation

๐Ÿค Contributing

We welcome contributions! Here's how to get started:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes with tests and documentation
  4. Submit a pull request

Development Setup

git clone https://github.com/swayamg20/mcp-framework.git
cd mcp-framework
npm install
npm run build
npm test

Adding New OAuth Providers

  1. Add provider configuration to types
  2. Implement user info normalization
  3. Add example usage
  4. Update documentation
  5. Submit PR with tests

๐Ÿ“Š Framework Stats

  • ๐Ÿ—๏ธ Architecture: Modular, extensible, type-safe
  • ๐Ÿ”’ Security: PKCE, encrypted storage, scope validation
  • ๐Ÿ“ Code Reduction: 90% less OAuth boilerplate
  • โšก Performance: Automatic token caching and refresh
  • ๐Ÿงช Testing: Comprehensive test suite
  • ๐Ÿ“š Documentation: Complete API reference and examples

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ†˜ Support & Community

  • ๐Ÿ› Bug Reports: GitHub Issues
  • ๐Ÿ’ฌ Discussions: GitHub Discussions
  • ๐Ÿ“š Documentation: Complete guides and API reference included
  • ๐Ÿ’ก Feature Requests: Submit ideas via GitHub Issues

Ready to build OAuth-enabled MCP servers in minutes instead of hours?

๐Ÿš€ Try the GitHub Example


Made with โค๏ธ for the MCP community. Empowering developers to build amazing AI integrations.

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages