Skip to main content
Glama
CupOfOwls

Kroger MCP Server

test_authentication

Verify the validity of your Kroger authentication token to ensure secure access to grocery shopping features like store finding and cart management.

Instructions

    Test if the current authentication token is valid.
    
    Returns:
        Dictionary indicating authentication status
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main execution logic for the 'test_authentication' tool. It checks the validity of the current authentication token using the shared authenticated client, provides detailed status including refresh token availability, and handles errors gracefully.
    @mcp.tool()
    async def test_authentication(ctx: Context = None) -> Dict[str, Any]:
        """
        Test if the current authentication token is valid.
        
        Returns:
            Dictionary indicating authentication status
        """
        if ctx:
            await ctx.info("Testing authentication token validity")
        
        try:
            client = get_authenticated_client()
            is_valid = client.test_current_token()
            
            if ctx:
                await ctx.info(f"Authentication test result: {'valid' if is_valid else 'invalid'}")
            
            result = {
                "success": True,
                "token_valid": is_valid,
                "message": f"Authentication token is {'valid' if is_valid else 'invalid'}"
            }
            
            # Check for refresh token availability
            if hasattr(client.client, 'token_info') and client.client.token_info:
                has_refresh_token = "refresh_token" in client.client.token_info
                result["has_refresh_token"] = has_refresh_token
                result["can_auto_refresh"] = has_refresh_token
                
                if has_refresh_token:
                    result["message"] += ". Token can be automatically refreshed when it expires."
                else:
                    result["message"] += ". No refresh token available - will need to re-authenticate when token expires."
            
            return result
            
        except Exception as e:
            if ctx:
                await ctx.error(f"Error testing authentication: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "token_valid": False
            }
  • The registration point where profile_tools.register_tools(mcp) is called, which defines and registers the test_authentication tool using FastMCP's @mcp.tool() decorator.
    profile_tools.register_tools(mcp)
  • Supporting helper function get_authenticated_client() that provides the authenticated KrogerAPI client instance, handling token loading, validation, and refresh. Called directly in test_authentication.
    def get_authenticated_client() -> KrogerAPI:
        """Get or create a user-authenticated client for cart operations
        
        This function attempts to load an existing token or prompts for authentication.
        In an MCP context, the user needs to explicitly call start_authentication and
        complete_authentication tools to authenticate.
        
        Returns:
            KrogerAPI: Authenticated client
            
        Raises:
            Exception: If no valid token is available and authentication is required
        """
        global _authenticated_client
        
        if _authenticated_client is not None and _authenticated_client.test_current_token():
            # Client exists and token is still valid
            return _authenticated_client
        
        # Clear the reference if token is invalid
        _authenticated_client = None
        
        try:
            load_and_validate_env(["KROGER_CLIENT_ID", "KROGER_CLIENT_SECRET", "KROGER_REDIRECT_URI"])
            
            # Try to load existing user token first
            token_file = ".kroger_token_user.json"
            token_info = load_token(token_file)
            
            if token_info:
                # Create a new client with the loaded token
                _authenticated_client = KrogerAPI()
                _authenticated_client.client.token_info = token_info
                _authenticated_client.client.token_file = token_file
                
                if _authenticated_client.test_current_token():
                    # Token is valid, use it
                    return _authenticated_client
                
                # Token is invalid, try to refresh it
                if "refresh_token" in token_info:
                    try:
                        _authenticated_client.authorization.refresh_token(token_info["refresh_token"])
                        # If refresh was successful, return the client
                        if _authenticated_client.test_current_token():
                            return _authenticated_client
                    except Exception:
                        # Refresh failed, need to re-authenticate
                        _authenticated_client = None
            
            # No valid token available, need user-initiated authentication
            raise Exception(
                "Authentication required. Please use the start_authentication tool to begin the OAuth flow, "
                "then complete it with the complete_authentication tool."
            )
        except Exception as e:
            if "Authentication required" in str(e):
                # This is an expected error when authentication is needed
                raise
            else:
                # Other unexpected errors
                raise Exception(f"Authentication failed: {str(e)}")
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It discloses the core behavior (testing token validity) and return type (dictionary indicating status), but lacks details on error handling, rate limits, permissions needed, or what constitutes a valid token. It adds basic context but misses richer behavioral traits for a tool with no annotation coverage.

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

Conciseness5/5

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

The description is front-loaded with the core purpose in the first sentence, followed by a brief return statement. Both sentences earn their place by clarifying functionality and output without waste. It is appropriately sized for a simple tool with no parameters.

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

Completeness3/5

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

Given the tool's low complexity (0 parameters, no output schema, no annotations), the description is minimally complete. It covers the purpose and return type, but for a tool with no structured data, it could benefit from more detail on authentication context or error cases. It's adequate but has clear gaps in behavioral disclosure.

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

Parameters4/5

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

The tool has 0 parameters with 100% schema description coverage, so no parameter information is needed. The description appropriately does not discuss parameters, maintaining focus on the tool's purpose and output. This meets the baseline for zero parameters, as it avoids unnecessary details.

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 verb ('Test') and resource ('current authentication token'), and distinguishes it from siblings like 'complete_authentication', 'force_reauthenticate', and 'get_authentication_info' by focusing on validation rather than completion, enforcement, or information retrieval. It directly answers what the tool does without redundancy.

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

Usage Guidelines3/5

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

The description implies usage when checking token validity, but does not explicitly state when to use this tool versus alternatives like 'get_authentication_info' or 'force_reauthenticate'. It provides context (testing authentication) but lacks guidance on prerequisites, exclusions, or specific scenarios for selection among siblings.

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