diff --git a/.env.oauth21 b/.env.oauth21
index 563ff4f..4f453cb 100644
--- a/.env.oauth21
+++ b/.env.oauth21
@@ -7,11 +7,6 @@
 
 GOOGLE_OAUTH_CLIENT_ID="your-google-client-id"
 GOOGLE_OAUTH_CLIENT_SECRET="your-google-client-secret"
-# Optional: OAuth 2.1 Settings
-OAUTH2_AUTHORIZATION_SERVER_URL=https://accounts.google.com
-OAUTH2_ENABLE_BEARER_PASSTHROUGH=true
-OAUTH2_SESSION_TIMEOUT=3600
-OAUTH2_MAX_SESSIONS_PER_USER=5
 
 # Development Settings (set to true for localhost testing)
 OAUTH2_ALLOW_INSECURE_TRANSPORT=false
@@ -19,6 +14,3 @@ OAUTH2_ENABLE_DEBUG=false
 
 # Legacy Compatibility (recommended during migration)
 OAUTH2_ENABLE_LEGACY_AUTH=true
-
-# Required scopes for Google Workspace
-OAUTH2_REQUIRED_SCOPES=https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/userinfo.profile
diff --git a/README.md b/README.md
index c1e219c..ac9c56a 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,7 @@ A production-ready MCP server that integrates all major Google Workspace service
 | `USER_GOOGLE_EMAIL` *(optional)* | Default email for single-user auth |
 | `GOOGLE_PSE_API_KEY` *(optional)* | API key for Google Custom Search - see [Custom Search Setup](#google-custom-search-setup) |
 | `GOOGLE_PSE_ENGINE_ID` *(optional)* | Programmable Search Engine ID for Custom Search |
+| `MCP_ENABLE_OAUTH21` *(optional)* | Set to `true` to enable OAuth 2.1 support (requires streamable-http transport) |
 | `OAUTHLIB_INSECURE_TRANSPORT=1` | Development only (allows `http://` redirect) |
 
 Claude Desktop stores these securely in the OS keychain; set them once in the extension pane.
@@ -250,14 +251,16 @@ The server includes OAuth 2.1 support for bearer token authentication, enabling
 - Browser-based clients requiring CORS support
 
 **Enabling OAuth 2.1:**
+To enable OAuth 2.1, set the `MCP_ENABLE_OAUTH21` environment variable to `true`.
+
 ```bash
 # OAuth 2.1 requires HTTP transport mode
+export MCP_ENABLE_OAUTH21=true
 uv run main.py --transport streamable-http
-
-# The server will automatically detect your GOOGLE_OAUTH_CLIENT_ID/SECRET
-# and initialize OAuth 2.1 if available
 ```
 
+If `MCP_ENABLE_OAUTH21` is not set to `true`, the server will use legacy authentication, which is suitable for clients that do not support OAuth 2.1.
+
 <details>
 <summary><b>Innovative CORS Proxy Architecture</b></summary>
 
diff --git a/auth/oauth21_integration.py b/auth/oauth21_integration.py
index 567dc2f..c17eac5 100644
--- a/auth/oauth21_integration.py
+++ b/auth/oauth21_integration.py
@@ -20,34 +20,34 @@ logger = logging.getLogger(__name__)
 
 class OAuth21GoogleServiceBuilder:
     """Builds Google services using FastMCP OAuth authenticated sessions."""
-    
+
     def __init__(self):
         """
         Initialize the service builder.
         """
         self._service_cache: Dict[str, Tuple[Any, str]] = {}
-    
+
     def extract_session_from_context(self, context: Optional[Dict[str, Any]] = None) -> Optional[str]:
         """
         Extract session ID from various context sources.
-        
+
         Args:
             context: Context dictionary that may contain session information
-            
+
         Returns:
             Session ID if found, None otherwise
         """
         if not context:
             return None
-            
+
         # Try to extract from OAuth 2.1 auth context
         if "auth_context" in context and hasattr(context["auth_context"], "session_id"):
             return context["auth_context"].session_id
-            
+
         # Try direct session_id
         if "session_id" in context:
             return context["session_id"]
-            
+
         # Try from request state
         if "request" in context:
             request = context["request"]
@@ -55,9 +55,9 @@ class OAuth21GoogleServiceBuilder:
                 auth_ctx = request.state.auth
                 if hasattr(auth_ctx, "session_id"):
                     return auth_ctx.session_id
-                    
+
         return None
-    
+
     async def get_authenticated_service_with_session(
         self,
         service_name: str,
@@ -70,7 +70,7 @@ class OAuth21GoogleServiceBuilder:
     ) -> Tuple[Any, str]:
         """
         Get authenticated Google service using OAuth 2.1 session if available.
-        
+
         Args:
             service_name: Google service name (e.g., "gmail", "drive")
             version: API version (e.g., "v1", "v3")
@@ -79,59 +79,62 @@ class OAuth21GoogleServiceBuilder:
             required_scopes: Required OAuth scopes
             session_id: OAuth 2.1 session ID
             auth_context: OAuth 2.1 authentication context
-            
+
         Returns:
             Tuple of (service instance, actual user email)
-            
+
         Raises:
             GoogleAuthenticationError: If authentication fails
         """
         cache_key = f"{user_google_email}:{service_name}:{version}:{':'.join(sorted(required_scopes))}"
-        
+
         # Check cache first
         if cache_key in self._service_cache:
             logger.debug(f"[{tool_name}] Using cached service for {user_google_email}")
             return self._service_cache[cache_key]
-        
+
         try:
             # First check the global OAuth 2.1 session store
             from auth.oauth21_session_store import get_oauth21_session_store
             store = get_oauth21_session_store()
             credentials = store.get_credentials(user_google_email)
-            
+
             if credentials and credentials.valid:
                 logger.info(f"[{tool_name}] Found OAuth 2.1 credentials in global store for {user_google_email}")
-                
+
                 # Build the service
                 service = await asyncio.to_thread(
                     build, service_name, version, credentials=credentials
                 )
-                
+
                 # Cache the service
                 self._service_cache[cache_key] = (service, user_google_email)
-                
+
                 return service, user_google_email
-            
-            # OAuth 2.1 is now handled by FastMCP - removed legacy auth_layer code
-            
-            # Fall back to legacy authentication
-            logger.debug(f"[{tool_name}] Falling back to legacy authentication for {user_google_email}")
-            from auth.google_auth import get_authenticated_google_service as legacy_get_service
-            
-            return await legacy_get_service(
-                service_name=service_name,
-                version=version,
-                tool_name=tool_name,
-                user_google_email=user_google_email,
-                required_scopes=required_scopes,
+
+            # If OAuth 2.1 is not enabled, fall back to legacy authentication
+            if not is_oauth21_enabled():
+                logger.debug(f"[{tool_name}] OAuth 2.1 is not enabled. Falling back to legacy authentication for {user_google_email}")
+                return await get_legacy_auth_service(
+                    service_name=service_name,
+                    version=version,
+                    tool_name=tool_name,
+                    user_google_email=user_google_email,
+                    required_scopes=required_scopes,
+                )
+
+            # If we are here, it means OAuth 2.1 is enabled but credentials are not found
+            logger.error(f"[{tool_name}] OAuth 2.1 is enabled, but no valid credentials found for {user_google_email}")
+            raise GoogleAuthenticationError(
+                f"OAuth 2.1 is enabled, but no valid credentials found for {user_google_email}"
             )
-            
+
         except Exception as e:
             logger.error(f"[{tool_name}] Authentication failed for {user_google_email}: {e}")
             raise GoogleAuthenticationError(
                 f"Failed to authenticate for {service_name}: {str(e)}"
             )
-    
+
     def clear_cache(self):
         """Clear the service cache."""
         self._service_cache.clear()
@@ -157,6 +160,46 @@ def set_auth_layer(auth_layer):
     logger.info("set_auth_layer called - OAuth is now handled by FastMCP")
 
 
+_oauth21_enabled = False
+
+def is_oauth21_enabled() -> bool:
+    """
+    Check if the OAuth 2.1 authentication layer is active.
+    """
+    global _oauth21_enabled
+    return _oauth21_enabled
+
+
+def enable_oauth21():
+    """
+    Enable the OAuth 2.1 authentication layer.
+    """
+    global _oauth21_enabled
+    _oauth21_enabled = True
+    logger.info("OAuth 2.1 authentication has been enabled.")
+
+
+async def get_legacy_auth_service(
+    service_name: str,
+    version: str,
+    tool_name: str,
+    user_google_email: str,
+    required_scopes: list[str],
+) -> Tuple[Any, str]:
+    """
+    Get authenticated Google service using legacy authentication.
+    """
+    from auth.google_auth import get_authenticated_google_service as legacy_get_service
+
+    return await legacy_get_service(
+        service_name=service_name,
+        version=version,
+        tool_name=tool_name,
+        user_google_email=user_google_email,
+        required_scopes=required_scopes,
+    )
+
+
 async def get_authenticated_google_service_oauth21(
     service_name: str,
     version: str,
@@ -167,10 +210,10 @@ async def get_authenticated_google_service_oauth21(
 ) -> Tuple[Any, str]:
     """
     Enhanced version of get_authenticated_google_service that supports OAuth 2.1.
-    
+
     This function checks for OAuth 2.1 session context and uses it if available,
     otherwise falls back to legacy authentication.
-    
+
     Args:
         service_name: Google service name
         version: API version
@@ -178,20 +221,20 @@ async def get_authenticated_google_service_oauth21(
         user_google_email: User's Google email
         required_scopes: Required OAuth scopes
         context: Optional context containing session information
-        
+
     Returns:
         Tuple of (service instance, actual user email)
     """
     builder = get_oauth21_service_builder()
-    
+
     # FastMCP handles context now - extract any session info
     session_id = None
     auth_context = None
-    
+
     if context:
         session_id = builder.extract_session_from_context(context)
         auth_context = context.get("auth_context")
-    
+
     return await builder.get_authenticated_service_with_session(
         service_name=service_name,
         version=version,
diff --git a/auth/service_decorator.py b/auth/service_decorator.py
index 0e2cf21..0d036a9 100644
--- a/auth/service_decorator.py
+++ b/auth/service_decorator.py
@@ -41,9 +41,9 @@ async def get_authenticated_google_service_oauth21(
     """
     from auth.oauth21_session_store import get_oauth21_session_store
     from googleapiclient.discovery import build
-    
+
     store = get_oauth21_session_store()
-    
+
     # Use the new validation method to ensure session can only access its own credentials
     credentials = store.get_credentials_with_validation(
         requested_user_email=user_google_email,
@@ -51,23 +51,23 @@ async def get_authenticated_google_service_oauth21(
         auth_token_email=auth_token_email,
         allow_recent_auth=allow_recent_auth
     )
-    
+
     if not credentials:
         from auth.google_auth import GoogleAuthenticationError
         raise GoogleAuthenticationError(
             f"Access denied: Cannot retrieve credentials for {user_google_email}. "
             f"You can only access credentials for your authenticated account."
         )
-    
+
     # Check scopes
     if not all(scope in credentials.scopes for scope in required_scopes):
         from auth.google_auth import GoogleAuthenticationError
         raise GoogleAuthenticationError(f"OAuth 2.1 credentials lack required scopes. Need: {required_scopes}, Have: {credentials.scopes}")
-    
+
     # Build service
     service = build(service_name, version, credentials=credentials)
     logger.info(f"[{tool_name}] Successfully authenticated {service_name} service using OAuth 2.1 for user: {user_google_email}")
-    
+
     return service, user_google_email
 
 logger = logging.getLogger(__name__)
@@ -129,7 +129,7 @@ SCOPE_GROUPS = {
     # Tasks scopes
     "tasks": TASKS_SCOPE,
     "tasks_read": TASKS_READONLY_SCOPE,
-    
+
     # Custom Search scope
     "customsearch": CUSTOM_SEARCH_SCOPE,
 }
@@ -307,13 +307,13 @@ def require_google_service(
             if service is None:
                 try:
                     tool_name = func.__name__
-                    
+
                     # SIMPLIFIED: Just get the authenticated user from the context
                     # The AuthInfoMiddleware has already done all the authentication checks
                     authenticated_user = None
                     auth_method = None
                     mcp_session_id = None
-                    
+
                     try:
                         from fastmcp.server.dependencies import get_context
                         ctx = get_context()
@@ -321,82 +321,31 @@ def require_google_service(
                             # Get the authenticated user email set by AuthInfoMiddleware
                             authenticated_user = ctx.get_state("authenticated_user_email")
                             auth_method = ctx.get_state("authenticated_via")
-                            
+
                             # Get session ID for logging
                             if hasattr(ctx, 'session_id'):
                                 mcp_session_id = ctx.session_id
                                 # Set FastMCP session ID in context variable for propagation
                                 from core.context import set_fastmcp_session_id
                                 set_fastmcp_session_id(mcp_session_id)
-                            
+
                             logger.info(f"[{tool_name}] Authentication from middleware: user={authenticated_user}, method={auth_method}")
                     except Exception as e:
                         logger.debug(f"[{tool_name}] Could not get FastMCP context: {e}")
-                    
+
                     # Log authentication status
                     logger.info(f"[{tool_name}] Authentication Status:"
                               f" Method={auth_method or 'none'},"
                               f" User={authenticated_user or 'none'},"
                               f" MCPSessionID={mcp_session_id or 'none'}")
-                    
-                    # SIMPLIFIED: Check transport mode and authentication state
-                    from core.config import get_transport_mode
-                    transport_mode = get_transport_mode()
-                    
-                    # Check if OAuth 2.1 provider is configured
-                    oauth21_enabled = False
-                    try:
-                        from core.server import get_auth_provider
-                        auth_provider = get_auth_provider()
-                        oauth21_enabled = auth_provider is not None
-                    except Exception:
-                        pass
-                    
-                    # Determine if we should proceed based on authentication state
-                    if transport_mode == "streamable-http" and oauth21_enabled:
-                        # OAuth 2.1 mode - require authentication
-                        if not authenticated_user:
-                            logger.error(f"[{tool_name}] SECURITY: Unauthenticated request denied in OAuth 2.1 mode")
-                            raise Exception(
-                                "Authentication required. This server is configured with OAuth 2.1 authentication. "
-                                "Please authenticate first using the OAuth flow before accessing resources."
-                            )
-                        
-                        # Additional security: Verify the authenticated user matches the requested user
-                        if authenticated_user != user_google_email:
-                            logger.warning(
-                                f"[{tool_name}] User mismatch - authenticated as {authenticated_user} "
-                                f"but requesting resources for {user_google_email}"
-                            )
-                            # The OAuth21SessionStore will handle the actual validation
-                    
-                    # Determine authentication method to use
-                    # Use OAuth 2.1 only if:
-                    # 1. OAuth 2.1 mode is active (oauth21_enabled), OR
-                    # 2. We have an authenticated user (from bearer token), OR  
-                    # 3. In stdio mode, the user has a session in the OAuth21 store
-                    use_oauth21 = False
-                    if oauth21_enabled and (transport_mode == "streamable-http" or authenticated_user):
-                        # OAuth 2.1 mode is active or we have bearer token auth
-                        use_oauth21 = True
-                    elif transport_mode == "stdio" and OAUTH21_INTEGRATION_AVAILABLE:
-                        # In stdio mode, check if user has OAuth 2.1 credentials stored
-                        try:
-                            from auth.oauth21_session_store import get_oauth21_session_store
-                            store = get_oauth21_session_store()
-                            if store.has_session(user_google_email):
-                                use_oauth21 = True
-                                logger.debug(f"[{tool_name}] User has OAuth 2.1 session in stdio mode")
-                        except Exception:
-                            pass
-                    
-                    if use_oauth21:
-                        # Use OAuth 2.1 authentication
-                        logger.info(f"[{tool_name}] Using OAuth 2.1 authentication")
-                        
-                        # Determine if we should allow recent auth (ONLY in stdio mode)
-                        allow_recent_auth = (transport_mode == "stdio" and not authenticated_user)
-                        
+
+                    from auth.oauth21_integration import is_oauth21_enabled
+
+                    if is_oauth21_enabled():
+                        logger.debug(f"[{tool_name}] Attempting OAuth 2.1 authentication flow.")
+                        # The downstream get_authenticated_google_service_oauth21 will handle
+                        # whether the user's token is valid for the requested resource.
+                        # This decorator should not block the call here.
                         service, actual_user_email = await get_authenticated_google_service_oauth21(
                             service_name=service_name,
                             version=service_version,
@@ -405,11 +354,11 @@ def require_google_service(
                             required_scopes=resolved_scopes,
                             session_id=mcp_session_id,
                             auth_token_email=authenticated_user,
-                            allow_recent_auth=allow_recent_auth,
+                            allow_recent_auth=False,
                         )
-                    elif transport_mode == "stdio":
-                        # Fall back to legacy authentication in stdio mode
-                        logger.info(f"[{tool_name}] Using legacy authentication (stdio mode)")
+                    else:
+                        # If OAuth 2.1 is not enabled, always use the legacy authentication method.
+                        logger.debug(f"[{tool_name}] Using legacy authentication flow (OAuth 2.1 disabled).")
                         service, actual_user_email = await get_authenticated_google_service(
                             service_name=service_name,
                             version=service_version,
@@ -418,10 +367,7 @@ def require_google_service(
                             required_scopes=resolved_scopes,
                             session_id=mcp_session_id,
                         )
-                    else:
-                        logger.error(f"[{tool_name}] No authentication available in {transport_mode} mode")
-                        raise Exception(f"Authentication not available in {transport_mode} mode")
-                    
+
                     if cache_enabled:
                         cache_key = _get_cache_key(user_google_email, service_name, service_version, resolved_scopes)
                         _cache_service(cache_key, service, actual_user_email)
@@ -500,12 +446,12 @@ def require_multiple_services(service_configs: List[Dict[str, Any]]):
 
                 try:
                     tool_name = func.__name__
-                    
+
                     # SIMPLIFIED: Get authentication state from context (set by AuthInfoMiddleware)
                     authenticated_user = None
                     auth_method = None
                     mcp_session_id = None
-                    
+
                     try:
                         from fastmcp.server.dependencies import get_context
                         ctx = get_context()
@@ -516,11 +462,11 @@ def require_multiple_services(service_configs: List[Dict[str, Any]]):
                                 mcp_session_id = ctx.session_id
                     except Exception as e:
                         logger.debug(f"[{tool_name}] Could not get FastMCP context: {e}")
-                    
+
                     # Check transport mode and OAuth 2.1 configuration
                     from core.config import get_transport_mode
                     transport_mode = get_transport_mode()
-                    
+
                     oauth21_enabled = False
                     try:
                         from core.server import get_auth_provider
@@ -528,7 +474,7 @@ def require_multiple_services(service_configs: List[Dict[str, Any]]):
                         oauth21_enabled = auth_provider is not None
                     except Exception:
                         pass
-                    
+
                     # In OAuth 2.1 mode, require authentication
                     if transport_mode == "streamable-http" and oauth21_enabled:
                         if not authenticated_user:
@@ -537,7 +483,7 @@ def require_multiple_services(service_configs: List[Dict[str, Any]]):
                                 "Authentication required. This server is configured with OAuth 2.1 authentication. "
                                 "Please authenticate first using the OAuth flow before accessing resources."
                             )
-                    
+
                     # Determine authentication method to use (same logic as single service)
                     use_oauth21 = False
                     if oauth21_enabled and (transport_mode == "streamable-http" or authenticated_user):
@@ -550,13 +496,13 @@ def require_multiple_services(service_configs: List[Dict[str, Any]]):
                                 use_oauth21 = True
                         except Exception:
                             pass
-                    
+
                     if use_oauth21:
                         logger.debug(f"OAuth 2.1 authentication for {tool_name} ({service_type})")
-                        
+
                         # Determine if we should allow recent auth (ONLY in stdio mode)
                         allow_recent_auth = (transport_mode == "stdio" and not authenticated_user)
-                        
+
                         service, _ = await get_authenticated_google_service_oauth21(
                             service_name=service_name,
                             version=service_version,
diff --git a/core/server.py b/core/server.py
index 5177d99..cea7c44 100644
--- a/core/server.py
+++ b/core/server.py
@@ -1,252 +1,114 @@
 import logging
 import os
-from contextlib import asynccontextmanager
-
-from typing import Optional
+from typing import Optional, Union
 from importlib import metadata
 
-from fastapi.responses import HTMLResponse
-from fastapi.responses import JSONResponse
-
-from fastmcp import FastMCP
-from starlette.applications import Starlette
+from fastapi.responses import HTMLResponse, JSONResponse
 from starlette.requests import Request
-from starlette.responses import RedirectResponse
 from starlette.middleware import Middleware
 from fastapi.middleware.cors import CORSMiddleware
 
-from auth.oauth21_session_store import get_oauth21_session_store
-from auth.google_auth import handle_auth_callback, start_auth_flow, check_client_secrets, save_credentials_to_file
+from fastmcp import FastMCP
+
+from auth.oauth21_session_store import get_oauth21_session_store, set_auth_provider
+from auth.google_auth import handle_auth_callback, start_auth_flow, check_client_secrets
 from auth.mcp_session_middleware import MCPSessionMiddleware
 from auth.oauth_responses import create_error_response, create_success_response, create_server_error_response
 from auth.auth_info_middleware import AuthInfoMiddleware
-from google.oauth2.credentials import Credentials
-
-# Import common OAuth handlers
-from auth.oauth_common_handlers import (
-    handle_oauth_authorize,
-    handle_proxy_token_exchange,
-    handle_oauth_protected_resource,
-    handle_oauth_authorization_server,
-    handle_oauth_client_config,
-    handle_oauth_register
-)
-
-# FastMCP OAuth imports
 from auth.fastmcp_google_auth import GoogleWorkspaceAuthProvider
-from auth.oauth21_session_store import set_auth_provider, store_token_session
-
-# Try to import GoogleRemoteAuthProvider for FastMCP 2.11.1+
-try:
-    from auth.google_remote_auth_provider import GoogleRemoteAuthProvider
-    GOOGLE_REMOTE_AUTH_AVAILABLE = True
-except ImportError:
-    GOOGLE_REMOTE_AUTH_AVAILABLE = False
-    GoogleRemoteAuthProvider = None
-
-# Import shared configuration
 from auth.scopes import SCOPES
 from core.config import (
     WORKSPACE_MCP_PORT,
-    WORKSPACE_MCP_BASE_URI,
     USER_GOOGLE_EMAIL,
     get_transport_mode,
     set_transport_mode as _set_transport_mode,
     get_oauth_redirect_uri as get_oauth_redirect_uri_for_current_mode,
 )
 
-# Configure logging
+# Try to import GoogleRemoteAuthProvider for FastMCP 2.11.1+
+try:
+    from auth.google_remote_auth_provider import GoogleRemoteAuthProvider
+    GOOGLE_REMOTE_AUTH_AVAILABLE = True
+except ImportError:
+    GOOGLE_REMOTE_AUTH_AVAILABLE = False
+    GoogleRemoteAuthProvider = None
+
 logging.basicConfig(level=logging.INFO)
 logger = logging.getLogger(__name__)
 
-# FastMCP authentication provider instance
-from typing import Union
 _auth_provider: Optional[Union[GoogleWorkspaceAuthProvider, GoogleRemoteAuthProvider]] = None
 
-# Create middleware configuration
-
+# --- Middleware Definitions ---
 cors_middleware = Middleware(
     CORSMiddleware,
-    allow_origins=["*"],  # In production, specify allowed origins
+    allow_origins=["*"],
     allow_credentials=True,
     allow_methods=["*"],
     allow_headers=["*"],
 )
-
 session_middleware = Middleware(MCPSessionMiddleware)
+auth_info_middleware = AuthInfoMiddleware()
 
-# Custom FastMCP that adds CORS to streamable HTTP
-class CORSEnabledFastMCP(FastMCP):
-    def streamable_http_app(self) -> "Starlette":
-        """Override to add CORS and session middleware to the app."""
-        app = super().streamable_http_app()
-        # Add session middleware first (to set context before other middleware)
-        app.user_middleware.insert(0, session_middleware)
-        # Add CORS as the second middleware
-        app.user_middleware.insert(1, cors_middleware)
-        # Rebuild middleware stack
-        app.middleware_stack = app.build_middleware_stack()
-        logger.info("Added session and CORS middleware to streamable HTTP app")
-        return app
-
-
-# Basic MCP server instance - auth will be set based on transport mode
-server = CORSEnabledFastMCP(
+# --- Server Instance ---
+server = FastMCP(
     name="google_workspace",
     port=WORKSPACE_MCP_PORT,
     host="0.0.0.0",
-    auth=None  # Will be set in set_transport_mode() for HTTP
+    auth=None,
 )
 
-# Add the AuthInfo middleware to inject authentication into FastMCP context
-auth_info_middleware = AuthInfoMiddleware()
-# Set the auth provider type so tools can access it
-auth_info_middleware.auth_provider_type = "GoogleRemoteAuthProvider"
+# Add middleware to the server instance
 server.add_middleware(auth_info_middleware)
+server.add_middleware(session_middleware)
+server.add_middleware(cors_middleware)
 
-# Add startup and shutdown event handlers to the underlying FastAPI app
-def add_lifecycle_events():
-    """Add lifecycle events after server creation."""
-    # Get the FastAPI app from streamable HTTP
-    app = server.streamable_http_app()
-    
-    @asynccontextmanager
-    async def lifespan(app):
-        # Startup
-        global _auth_provider
-        try:
-            _auth_provider = await initialize_auth()
-            if _auth_provider:
-                logger.info("OAuth 2.1 authentication initialized on startup")
-            else:
-                logger.info("OAuth authentication not configured or not available")
-        except Exception as e:
-            logger.error(f"Failed to initialize authentication on startup: {e}")
-        
-        yield
-        
-        # Shutdown
-        await shutdown_auth()
-    
-    # Set the lifespan if it's not already set
-    if not hasattr(app, 'lifespan') or app.lifespan is None:
-        app.router.lifespan_context = lifespan
 
 def set_transport_mode(mode: str):
-    """Set the current transport mode for OAuth callback handling."""
-    global _auth_provider
-    
+    """Sets the transport mode for the server."""
     _set_transport_mode(mode)
     logger.info(f"Transport mode set to: {mode}")
-    
-    # Initialize auth and lifecycle events for HTTP transport
-    if mode == "streamable-http":
-        # Initialize auth provider immediately for HTTP mode
-        if os.getenv("GOOGLE_OAUTH_CLIENT_ID") and not _auth_provider:
-            try:
-                # Use GoogleRemoteAuthProvider if available (FastMCP 2.11.1+)
-                if GOOGLE_REMOTE_AUTH_AVAILABLE:
-                    try:
-                        _auth_provider = GoogleRemoteAuthProvider()
-                        server.auth = _auth_provider
-                        set_auth_provider(_auth_provider)
-                        
-                        # Manually register the auth provider's routes
-                        auth_routes = _auth_provider.get_routes()
-                        logger.info(f"Registering {len(auth_routes)} routes from GoogleRemoteAuthProvider")
-                        for route in auth_routes:
-                            server.custom_route(route.path, methods=list(route.methods))(route.endpoint)
-                        
-                        logger.info("OAuth 2.1 authentication provider initialized with GoogleRemoteAuthProvider")
-                    except Exception as e:
-                        logger.warning(f"Failed to initialize GoogleRemoteAuthProvider, falling back to legacy: {e}")
-                        _auth_provider = GoogleWorkspaceAuthProvider()
-                        server.auth = _auth_provider
-                        set_auth_provider(_auth_provider)
-                        logger.info("OAuth 2.1 authentication provider initialized (legacy)")
-                else:
-                    _auth_provider = GoogleWorkspaceAuthProvider()
-                    server.auth = _auth_provider
-                    set_auth_provider(_auth_provider)
-                    logger.info("OAuth 2.1 authentication provider initialized (legacy)")
-            except Exception as e:
-                logger.error(f"Failed to initialize auth provider: {e}")
-        
-        add_lifecycle_events()
 
-async def initialize_auth() -> Optional[Union[GoogleWorkspaceAuthProvider, GoogleRemoteAuthProvider]]:
-    """Initialize FastMCP authentication if available and configured."""
+def configure_server_for_http():
+    """
+    Configures the authentication provider for HTTP transport.
+    This must be called BEFORE server.run().
+    """
     global _auth_provider
+    transport_mode = get_transport_mode()
 
-    # Only initialize auth for HTTP transport
-    if get_transport_mode() != "streamable-http":
-        logger.info("Authentication not available in stdio mode")
-        return None
+    if transport_mode != "streamable-http":
+        return
 
-    # Check if OAuth is configured
-    if not os.getenv("GOOGLE_OAUTH_CLIENT_ID"):
-        logger.info("OAuth not configured (GOOGLE_OAUTH_CLIENT_ID not set)")
-        return None
+    oauth21_enabled = os.getenv("MCP_ENABLE_OAUTH21", "false").lower() == "true"
 
-    # Return existing auth provider if already initialized
-    if _auth_provider:
-        logger.info("Using existing OAuth 2.1 authentication provider")
-        return _auth_provider
+    if oauth21_enabled:
+        if not os.getenv("GOOGLE_OAUTH_CLIENT_ID"):
+            logger.warning("OAuth 2.1 is enabled, but GOOGLE_OAUTH_CLIENT_ID is not set.")
+            return
 
-    try:
-        # Use GoogleRemoteAuthProvider if available (FastMCP 2.11.1+)
         if GOOGLE_REMOTE_AUTH_AVAILABLE:
+            logger.info("OAuth 2.1 is ENABLED. Initializing and attaching GoogleRemoteAuthProvider.")
             try:
                 _auth_provider = GoogleRemoteAuthProvider()
                 server.auth = _auth_provider
                 set_auth_provider(_auth_provider)
-                
-                # Manually register the auth provider's routes
-                # This ensures the OAuth discovery endpoints are available
-                auth_routes = _auth_provider.get_routes()
-                logger.info(f"Registering {len(auth_routes)} routes from GoogleRemoteAuthProvider")
-                for route in auth_routes:
-                    logger.info(f"  - Registering route: {route.path} ({', '.join(route.methods)})")
-                    server.custom_route(route.path, methods=list(route.methods))(route.endpoint)
-                
-                logger.info("FastMCP authentication initialized with GoogleRemoteAuthProvider (v2.11.1+)")
-                return _auth_provider
+                from auth.oauth21_integration import enable_oauth21
+                enable_oauth21()
             except Exception as e:
-                logger.warning(f"Failed to initialize GoogleRemoteAuthProvider, falling back to legacy: {e}")
-        
-        # Fallback to legacy GoogleWorkspaceAuthProvider
-        _auth_provider = GoogleWorkspaceAuthProvider()
-        server.auth = _auth_provider
-        set_auth_provider(_auth_provider)
-        
-        logger.info("FastMCP authentication initialized with Google Workspace provider (legacy)")
-        return _auth_provider
-    except Exception as e:
-        logger.error(f"Failed to initialize authentication: {e}")
-        return None
-
-async def shutdown_auth():
-    """Shutdown authentication provider."""
-    global _auth_provider
-    if _auth_provider:
-        try:
-            # FastMCP auth providers don't need explicit shutdown
-            logger.info("Authentication provider stopped")
-        except Exception as e:
-            logger.error(f"Error stopping authentication: {e}")
-        finally:
-            _auth_provider = None
-            server.auth = None
+                logger.error(f"Failed to initialize GoogleRemoteAuthProvider: {e}", exc_info=True)
+        else:
+            logger.error("OAuth 2.1 is enabled, but GoogleRemoteAuthProvider is not available.")
+    else:
+        logger.info("OAuth 2.1 is DISABLED. Server will use legacy tool-based authentication.")
+        server.auth = None
 
 def get_auth_provider() -> Optional[Union[GoogleWorkspaceAuthProvider, GoogleRemoteAuthProvider]]:
-    """Get the global authentication provider instance."""
+    """Gets the global authentication provider instance."""
     return _auth_provider
 
-
-# Health check endpoint
+# --- Custom Routes ---
 @server.custom_route("/health", methods=["GET"])
 async def health_check(request: Request):
-    """Health check endpoint for container orchestration."""
     try:
         version = metadata.version("workspace-mcp")
     except metadata.PackageNotFoundError:
@@ -258,60 +120,44 @@ async def health_check(request: Request):
         "transport": get_transport_mode()
     })
 
-
 @server.custom_route("/oauth2callback", methods=["GET"])
 async def oauth2_callback(request: Request) -> HTMLResponse:
-    """
-    Handle OAuth2 callback from Google via a custom route.
-    This endpoint exchanges the authorization code for credentials and saves them.
-    It then displays a success or error page to the user.
-    """
     state = request.query_params.get("state")
     code = request.query_params.get("code")
     error = request.query_params.get("error")
 
     if error:
-        error_message = f"Authentication failed: Google returned an error: {error}. State: {state}."
-        logger.error(error_message)
-        return create_error_response(error_message)
+        msg = f"Authentication failed: Google returned an error: {error}. State: {state}."
+        logger.error(msg)
+        return create_error_response(msg)
 
     if not code:
-        error_message = "Authentication failed: No authorization code received from Google."
-        logger.error(error_message)
-        return create_error_response(error_message)
+        msg = "Authentication failed: No authorization code received from Google."
+        logger.error(msg)
+        return create_error_response(msg)
 
     try:
-        # Check if we have credentials available (environment variables or file)
         error_message = check_client_secrets()
         if error_message:
             return create_server_error_response(error_message)
 
-        logger.info(f"OAuth callback: Received code (state: {state}). Attempting to exchange for tokens.")
+        logger.info(f"OAuth callback: Received code (state: {state}).")
 
-        # Exchange code for credentials. handle_auth_callback will save them.
-        # The user_id returned here is the Google-verified email.
         verified_user_id, credentials = handle_auth_callback(
-            scopes=SCOPES, # Ensure all necessary scopes are requested
+            scopes=SCOPES,
             authorization_response=str(request.url),
             redirect_uri=get_oauth_redirect_uri_for_current_mode(),
-            session_id=None # Session ID tracking removed
+            session_id=None
         )
 
-        logger.info(f"OAuth callback: Successfully authenticated user: {verified_user_id} (state: {state}).")
+        logger.info(f"OAuth callback: Successfully authenticated user: {verified_user_id}.")
 
-        # Store Google credentials in OAuth 2.1 session store
         try:
             store = get_oauth21_session_store()
-            
-            # Try to get MCP session ID from request for binding
             mcp_session_id = None
-            try:
-                if hasattr(request, 'state') and hasattr(request.state, 'session_id'):
-                    mcp_session_id = request.state.session_id
-                    logger.info(f"OAuth callback: Found MCP session ID for binding: {mcp_session_id}")
-            except Exception as e:
-                logger.debug(f"OAuth callback: Could not get MCP session ID: {e}")
-            
+            if hasattr(request, 'state') and hasattr(request.state, 'session_id'):
+                mcp_session_id = request.state.session_id
+
             store.store_session(
                 user_email=verified_user_id,
                 access_token=credentials.token,
@@ -321,110 +167,40 @@ async def oauth2_callback(request: Request) -> HTMLResponse:
                 client_secret=credentials.client_secret,
                 scopes=credentials.scopes,
                 expiry=credentials.expiry,
-                session_id=f"google-{state}",  # Use state as a pseudo session ID
-                mcp_session_id=mcp_session_id,  # Bind to MCP session if available
+                session_id=f"google-{state}",
+                mcp_session_id=mcp_session_id,
             )
-            logger.info(f"Stored Google credentials in OAuth 2.1 session store for {verified_user_id} (mcp: {mcp_session_id})")
+            logger.info(f"Stored Google credentials in OAuth 2.1 session store for {verified_user_id}")
         except Exception as e:
-            logger.error(f"Failed to store Google credentials in OAuth 2.1 store: {e}")
+            logger.error(f"Failed to store credentials in OAuth 2.1 store: {e}")
 
-        # Return success page using shared template
         return create_success_response(verified_user_id)
-
     except Exception as e:
-        error_message_detail = f"Error processing OAuth callback (state: {state}): {str(e)}"
-        logger.error(error_message_detail, exc_info=True)
-        # Generic error page for any other issues during token exchange or credential saving
+        logger.error(f"Error processing OAuth callback: {str(e)}", exc_info=True)
         return create_server_error_response(str(e))
 
+# --- Tools ---
 @server.tool()
-async def start_google_auth(
-    service_name: str,
-    user_google_email: str = USER_GOOGLE_EMAIL
-) -> str:
-    """
-    Initiates the Google OAuth 2.0 authentication flow for the specified user email and service.
-    This is the primary method to establish credentials when no valid session exists or when targeting a specific account for a particular service.
-    It generates an authorization URL that the LLM must present to the user.
-    This initiates a new authentication flow for the specified user and service.
-
-    LLM Guidance:
-    - Use this tool when you need to authenticate a user for a specific Google service (e.g., "Google Calendar", "Google Docs", "Gmail", "Google Drive")
-      and don't have existing valid credentials for the session or specified email.
-    - You MUST provide the `user_google_email` and the `service_name`. If you don't know the email, ask the user first.
-    - Valid `service_name` values typically include "Google Calendar", "Google Docs", "Gmail", "Google Drive".
-    - After calling this tool, present the returned authorization URL clearly to the user and instruct them to:
-        1. Click the link and complete the sign-in/consent process in their browser.
-        2. Note the authenticated email displayed on the success page.
-        3. Provide that email back to you (the LLM).
-        4. Retry their original request, including the confirmed `user_google_email`.
-
-    Args:
-        user_google_email (str): The user's full Google email address (e.g., 'example@gmail.com'). This is REQUIRED.
-        service_name (str): The name of the Google service for which authentication is being requested (e.g., "Google Calendar", "Google Docs"). This is REQUIRED.
-
-    Returns:
-        str: A detailed message for the LLM with the authorization URL and instructions to guide the user through the authentication process.
-    """
-    if not user_google_email or not isinstance(user_google_email, str) or '@' not in user_google_email:
-        error_msg = "Invalid or missing 'user_google_email'. This parameter is required and must be a valid email address. LLM, please ask the user for their Google email address."
-        logger.error(f"[start_google_auth] {error_msg}")
-        raise Exception(error_msg)
-
-    if not service_name or not isinstance(service_name, str):
-        error_msg = "Invalid or missing 'service_name'. This parameter is required (e.g., 'Google Calendar', 'Google Docs'). LLM, please specify the service name."
-        logger.error(f"[start_google_auth] {error_msg}")
-        raise Exception(error_msg)
-
-    logger.info(f"Tool 'start_google_auth' invoked for user_google_email: '{user_google_email}', service: '{service_name}'.")
-
-    # Ensure OAuth callback is available for current transport mode
-    from auth.oauth_callback_server import ensure_oauth_callback_available
-    redirect_uri = get_oauth_redirect_uri_for_current_mode()
-    success, error_msg = ensure_oauth_callback_available(get_transport_mode(), WORKSPACE_MCP_PORT, WORKSPACE_MCP_BASE_URI)
-    if not success:
-        if error_msg:
-            raise Exception(f"Failed to start OAuth callback server: {error_msg}")
-        else:
-            raise Exception("Failed to start OAuth callback server. Please try again.")
-
-    auth_result = await start_auth_flow(
-        user_google_email=user_google_email,
-        service_name=service_name,
-        redirect_uri=redirect_uri
-    )
-    return auth_result
-
-
-# OAuth 2.1 Discovery Endpoints are now handled by GoogleRemoteAuthProvider when available
-# For legacy mode, we need to register them manually
-if not GOOGLE_REMOTE_AUTH_AVAILABLE:
-    server.custom_route("/.well-known/oauth-protected-resource", methods=["GET", "OPTIONS"])(handle_oauth_protected_resource)
-
-
-# Authorization server metadata endpoint now handled by GoogleRemoteAuthProvider
-if not GOOGLE_REMOTE_AUTH_AVAILABLE:
-    server.custom_route("/.well-known/oauth-authorization-server", methods=["GET", "OPTIONS"])(handle_oauth_authorization_server)
-
-
-# OAuth client configuration endpoint now handled by GoogleRemoteAuthProvider
-if not GOOGLE_REMOTE_AUTH_AVAILABLE:
-    server.custom_route("/.well-known/oauth-client", methods=["GET", "OPTIONS"])(handle_oauth_client_config)
-
-
-# OAuth authorization proxy endpoint now handled by GoogleRemoteAuthProvider
-if not GOOGLE_REMOTE_AUTH_AVAILABLE:
-    server.custom_route("/oauth2/authorize", methods=["GET", "OPTIONS"])(handle_oauth_authorize)
-
-
-# Token exchange proxy endpoint now handled by GoogleRemoteAuthProvider
-if not GOOGLE_REMOTE_AUTH_AVAILABLE:
-    server.custom_route("/oauth2/token", methods=["POST", "OPTIONS"])(handle_proxy_token_exchange)
-
-
-# Dynamic client registration endpoint now handled by GoogleRemoteAuthProvider
-if not GOOGLE_REMOTE_AUTH_AVAILABLE:
-    server.custom_route("/oauth2/register", methods=["POST", "OPTIONS"])(handle_oauth_register)
-
+async def start_google_auth(service_name: str, user_google_email: str = USER_GOOGLE_EMAIL) -> str:
+    if not user_google_email:
+        raise ValueError("user_google_email must be provided.")
 
+    error_message = check_client_secrets()
+    if error_message:
+        return f"**Authentication Error:** {error_message}"
 
+    try:
+        auth_url, _ = start_auth_flow(
+            scopes=SCOPES,
+            redirect_uri=get_oauth_redirect_uri_for_current_mode(),
+            login_hint=user_google_email
+        )
+        return (
+            "**Action Required: Authenticate with Google**\n\n"
+            "Please visit this URL to authenticate:\n\n"
+            f"**[Authenticate with Google]({auth_url})**\n\n"
+            "After authenticating, retry your request."
+        )
+    except Exception as e:
+        logger.error(f"Failed to start Google authentication flow: {e}", exc_info=True)
+        return f"**Error:** An unexpected error occurred: {e}"
diff --git a/main.py b/main.py
index b766fe1..d1c5889 100644
--- a/main.py
+++ b/main.py
@@ -4,7 +4,7 @@ import os
 import sys
 from importlib import metadata
 from dotenv import load_dotenv
-from core.server import server, set_transport_mode
+from core.server import server, set_transport_mode, configure_server_for_http
 from core.utils import check_credentials_directory_permissions
 
 # Load environment variables from .env file, specifying an explicit path
@@ -86,6 +86,28 @@ def main():
     safe_print(f"   🐍 Python: {sys.version.split()[0]}")
     safe_print("")
 
+    # Active Configuration
+    safe_print("엑 Active Configuration:")
+
+    # Redact client secret for security
+    client_secret = os.getenv('GOOGLE_OAUTH_CLIENT_SECRET', 'Not Set')
+    redacted_secret = f"{client_secret[:4]}...{client_secret[-4:]}" if len(client_secret) > 8 else "Invalid or too short"
+
+    config_vars = {
+        "GOOGLE_OAUTH_CLIENT_ID": os.getenv('GOOGLE_OAUTH_CLIENT_ID', 'Not Set'),
+        "GOOGLE_OAUTH_CLIENT_SECRET": redacted_secret,
+        "USER_GOOGLE_EMAIL": os.getenv('USER_GOOGLE_EMAIL', 'Not Set'),
+        "MCP_SINGLE_USER_MODE": os.getenv('MCP_SINGLE_USER_MODE', 'false'),
+        "MCP_ENABLE_OAUTH21": os.getenv('MCP_ENABLE_OAUTH21', 'false'),
+        "OAUTHLIB_INSECURE_TRANSPORT": os.getenv('OAUTHLIB_INSECURE_TRANSPORT', 'false'),
+        "GOOGLE_CLIENT_SECRET_PATH": os.getenv('GOOGLE_CLIENT_SECRET_PATH', 'Not Set'),
+    }
+
+    for key, value in config_vars.items():
+        safe_print(f"   - {key}: {value}")
+    safe_print("")
+
+
     # Import tool modules to register them with the MCP server via decorators
     tool_imports = {
         'gmail': lambda: __import__('gmail.gmail_tools'),
@@ -151,10 +173,10 @@ def main():
 
         # Configure auth initialization for FastMCP lifecycle events
         if args.transport == 'streamable-http':
-            safe_print("🔐 OAuth 2.1 authentication will be initialized on startup")
-            safe_print(f"   Discovery endpoints will be available at {base_uri}:{port}/.well-known/")
+            configure_server_for_http()
+            safe_print("🔐 HTTP server configured for authentication.")
         else:
-            safe_print("🔐 OAuth authentication not available in stdio mode (using legacy auth)")
+            safe_print("🔐 Using legacy authentication for stdio mode.")
 
         if args.transport == 'streamable-http':
             safe_print(f"🚀 Starting server on {base_uri}:{port}")
