Skip to main content
Glama
CupOfOwls

Kroger MCP Server

complete_authentication

Finalize OAuth authentication for Kroger by processing the authorization callback URL after user consent in the browser.

Instructions

    Complete the OAuth flow using the redirect URL from Kroger.
    
    After opening the auth URL in your browser and authorizing the app,
    you'll be redirected to a callback URL. Copy that entire URL and
    pass it to this tool to complete the authentication process.
    
    Args:
        redirect_url: The full URL from your browser after authorization
        
    Returns:
        Dictionary indicating authentication status
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
redirect_urlYes

Implementation Reference

  • The core handler function for the 'complete_authentication' tool. It processes the OAuth redirect URL, validates the state parameter, extracts the authorization code, and exchanges it for access tokens using PKCE verification. Handles errors and stores no persistent state beyond globals.
    @mcp.tool()
    async def complete_authentication(redirect_url: str, ctx: Context = None) -> Dict[str, Any]:
        """
        Complete the OAuth flow using the redirect URL from Kroger.
        
        After opening the auth URL in your browser and authorizing the app,
        you'll be redirected to a callback URL. Copy that entire URL and
        pass it to this tool to complete the authentication process.
        
        Args:
            redirect_url: The full URL from your browser after authorization
            
        Returns:
            Dictionary indicating authentication status
        """
        global _pkce_params, _auth_state
        
        if not _pkce_params or not _auth_state:
            if ctx:
                await ctx.error("Authentication flow not started")
            return {
                "error": True,
                "message": "Authentication flow not started. Please use start_authentication first."
            }
            
        try:
            # Parse the redirect URL
            parsed_url = urlparse(redirect_url)
            query_params = parse_qs(parsed_url.query)
            
            # Extract code and state
            if 'code' not in query_params:
                if ctx:
                    await ctx.error("Authorization code not found in redirect URL")
                return {
                    "error": True,
                    "message": "Authorization code not found in redirect URL. Please check the URL and try again."
                }
                
            auth_code = query_params['code'][0]
            received_state = query_params.get('state', [None])[0]
            
            # Verify state parameter to prevent CSRF attacks
            if received_state != _auth_state:
                if ctx:
                    await ctx.error(f"State mismatch: expected {_auth_state}, got {received_state}")
                return {
                    "error": True,
                    "message": "State parameter mismatch. This could indicate a CSRF attack. Please try authenticating again."
                }
                
            # Get client credentials
            client_id = os.environ.get("KROGER_CLIENT_ID")
            client_secret = os.environ.get("KROGER_CLIENT_SECRET")
            redirect_uri = os.environ.get("KROGER_REDIRECT_URI", "http://localhost:8000/callback")
            
            if not client_id or not client_secret:
                if ctx:
                    await ctx.error("Missing Kroger API credentials")
                return {
                    "error": True,
                    "message": "Missing Kroger API credentials. Please set KROGER_CLIENT_ID and KROGER_CLIENT_SECRET."
                }
                
            # Initialize Kroger API client
            kroger = KrogerAPI()
            
            # Exchange the authorization code for tokens with the code verifier
            if ctx:
                await ctx.info(f"Exchanging authorization code for tokens with code_verifier")
            
            # Use the code_verifier from the PKCE parameters
            token_info = kroger.authorization.get_token_with_authorization_code(
                auth_code,
                code_verifier=_pkce_params["code_verifier"]
            )
            
            # Clear PKCE parameters and state after successful exchange
            _pkce_params = None
            _auth_state = None
            
            if ctx:
                await ctx.info(f"Authentication successful!")
            
            # Return success response
            return {
                "success": True,
                "message": "Authentication successful! You can now use Kroger API tools that require authentication.",
                "token_info": {
                    "expires_in": token_info.get("expires_in"),
                    "token_type": token_info.get("token_type"),
                    "scope": token_info.get("scope"),
                    "has_refresh_token": "refresh_token" in token_info
                }
            }
            
        except Exception as e:
            error_message = str(e)
            
            if ctx:
                await ctx.error(f"Authentication error: {error_message}")
                
            return {
                "error": True,
                "message": f"Authentication failed: {error_message}"
            }
  • Registers the authentication tools by calling register_auth_tools from auth.py.
    def register_tools(mcp):
        """Register authentication tools with the FastMCP server"""
        register_auth_tools(mcp)
  • Invokes the registration of auth tools in the main server setup, making complete_authentication available as an MCP tool.
    auth_tools.register_tools(mcp)
  • Defines and registers both start_authentication and complete_authentication tools using @mcp.tool() decorators within the registration function.
    def register_auth_tools(mcp):
        """Register authentication-specific tools with the FastMCP server"""
        
        @mcp.tool()
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden. It adequately describes the core behavior (completing OAuth flow with a redirect URL) and mentions the return format ('Dictionary indicating authentication status'). However, it lacks details about error conditions, what specific data the dictionary contains, or any side effects like token storage.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and well-structured with three distinct parts: purpose statement, usage instructions, and parameter/return documentation. Every sentence adds value, though the 'Args' and 'Returns' formatting could be more integrated with the natural language flow.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a single-parameter authentication completion tool with no annotations or output schema, the description provides good coverage of purpose, usage context, parameter meaning, and expected return type. It could be more complete by specifying what the authentication status dictionary contains or error scenarios.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage and only one parameter, the description fully compensates by providing clear semantics: 'The full URL from your browser after authorization' explains exactly what the redirect_url parameter should contain, including its source and format requirements.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('complete the OAuth flow') and resource ('using the redirect URL from Kroger'), distinguishing it from sibling tools like 'start_authentication' and 'force_reauthenticate'. It explicitly identifies the tool's role in the authentication process flow.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit when-to-use guidance: 'After opening the auth URL in your browser and authorizing the app, you'll be redirected to a callback URL. Copy that entire URL and pass it to this tool.' This clearly defines the prerequisite step (using start_authentication) and the specific trigger condition for invoking this tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/CupOfOwls/kroger-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server