Skip to main content
Glama
liliangshan

mcp-server-apidebug

by liliangshan

default_api_login

Authenticate to an API using environment variables for credentials. Automatically extracts the token from the response and updates the Authorization header. Optionally override the base URL with a parameter.

Instructions

API login authentication tool that uses environment variables for login credentials. Automatically extracts token from response and updates Authorization headers. Example: Call with optional baseUrl parameter to override default base URL

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
baseUrlNoBase URL for login request (optional, will override config baseUrl)

Implementation Reference

  • The core handler function for the api_login tool. It reads login configuration from environment variables (API_DEBUG_LOGIN_URL, API_DEBUG_LOGIN_METHOD, API_DEBUG_LOGIN_BODY), builds the login URL, executes the HTTP request, and returns login result with success/failure status.
    async function api_login(params, config, saveConfig) {
      const { baseUrl } = params || {};
    
      try {
        // Load current configuration
        const apiDebugConfig = loadApiConfig();
        
        // Use passed baseUrl or baseUrl from configuration
        const finalBaseUrl = baseUrl || apiDebugConfig.baseUrl || '';
        const loginUrl = getLoginUrl();
        const loginMethod = getLoginMethod();
        
        // Build full login URL
        let fullLoginUrl;
        if (loginUrl.startsWith('http://') || loginUrl.startsWith('https://')) {
          fullLoginUrl = loginUrl;
        } else {
          fullLoginUrl = finalBaseUrl + loginUrl;
        }
        
        // Get login request body from environment variables
        const loginBodyRaw = getLoginBody();
        let loginBody;
        
        // Process request body in different formats
        if (typeof loginBodyRaw === 'string') {
          // If it's a string, use it directly
          loginBody = loginBodyRaw;
        } else if (typeof loginBodyRaw === 'object') {
          // If it's an object, convert to JSON string
          loginBody = JSON.stringify(loginBodyRaw);
        } else {
          // Otherwise, use default format
          loginBody = '{"username":"","password":""}';
        }
    
        // Prepare request headers
        const headers = {
          ...apiDebugConfig.headers,
          'Content-Type': 'application/json'
        };
    
        // Execute login request
        let response;
        let responseData;
    
        try {
          const fetchOptions = {
            method: loginMethod,
            headers: headers,
            body: loginBody
          };
          
          // Add agent to HTTPS requests to skip certificate verification
          if (fullLoginUrl.startsWith('https')) {
            fetchOptions.agent = httpsAgent;
          }
          
          response = await fetch(fullLoginUrl, fetchOptions);
    
          // Get response data
          const contentType = response.headers.get('content-type');
    
          if (contentType && contentType.includes('application/json')) {
            responseData = await response.json();
          } else {
            responseData = await response.text();
          }
    
          // Determine if login was successful
          const isHttpSuccess = response.status >= 200 && response.status < 300;
    
          if (isHttpSuccess) {
            return {
              success: true,
              message: 'Login successful',
              description: getLoginDescription(),
              request: {
                url: fullLoginUrl,
                method: loginMethod,
                headers: headers,
                body: loginBody
              },
              response: {
                status: response.status,
                statusText: response.statusText,
                headers: Object.fromEntries(response.headers.entries()),
                data: responseData
              },
              timestamp: new Date().toISOString()
            };
          } else {
            return {
              success: false,
              message: `Login failed: HTTP ${response.status}: ${response.statusText}`,
              request: {
                url: fullLoginUrl,
                method: loginMethod,
                headers: headers,
                body: loginBody
              },
              response: {
                status: response.status,
                statusText: response.statusText,
                headers: Object.fromEntries(response.headers.entries()),
                data: responseData
              },
              error: `HTTP ${response.status}: ${response.statusText}`,
              timestamp: new Date().toISOString()
            };
          }
        } catch (fetchError) {
          return {
            success: false,
            message: `Login request failed: ${fetchError.message}`,
            request: {
              url: fullLoginUrl,
              method: loginMethod,
              headers: headers,
              body: loginBody
            },
            error: fetchError.message,
            timestamp: new Date().toISOString()
          };
        }
      } catch (err) {
        throw new Error(`Failed to perform login: ${err.message}`);
      }
    }
  • The input schema definition for the api_login tool tool. Defines the tool name (prefixed with TOOL_PREFIX, e.g., 'default_api_login'), description, and input parameters (optional baseUrl).
    {
      name: createToolName('api_login'),
      description: 'API login authentication tool that uses environment variables for login credentials. Automatically extracts token from response and updates Authorization headers. Example: Call with optional baseUrl parameter to override default base URL',
      inputSchema: {
        type: 'object',
        properties: {
          baseUrl: {
            type: 'string',
            description: 'Base URL for login request (optional, will override config baseUrl)'
          }
        }
      }
  • src/server.js:57-60 (registration)
    The createToolName function that generates the prefixed tool name. When TOOL_PREFIX is 'default', it creates 'default_api_login' from the base name 'api_login'.
    const createToolName = (name) => {
      const toolPrefix = process.env.TOOL_PREFIX || 'default';
      return toolPrefix ? `${toolPrefix}_${name}` : name;
    };
  • src/server.js:243-245 (registration)
    The server class method that bridges MCP tool calls to the actual handler. Calls the api_login function from src/utils/api_login.js.
    async api_login(params) {
      return api_login(params, this.config, saveConfig);
    }
  • Helper functions used by the login handler: getLoginUrl() reads from API_DEBUG_LOGIN_URL env var, getLoginMethod() reads from API_DEBUG_LOGIN_METHOD, getLoginBody() reads from API_DEBUG_LOGIN_BODY, and getLoginDescription() reads from API_DEBUG_LOGIN_DESCRIPTION.
    const getLoginUrl = () => {
      return process.env.API_DEBUG_LOGIN_URL || '/api/login';
    };
    
    // Get login method from environment variable
    const getLoginMethod = () => {
      return (process.env.API_DEBUG_LOGIN_METHOD || 'POST').toUpperCase();
    };
    
    // Get login body from environment variable
    const getLoginBody = () => {
      const envBody = process.env.API_DEBUG_LOGIN_BODY || '{"username":"","password":""}';
      
      // If it is a string format, return it directly
      if (typeof envBody === 'string' && !envBody.startsWith('{')) {
        return envBody;
      }
      
      // If it is JSON format, parse and return it
      try {
        return JSON.parse(envBody);
      } catch {
        // If parsing fails, return the original string
        return envBody;
      }
    };
    
    // Get login description from environment variable
    const getLoginDescription = () => {
      const envDesc = process.env.API_DEBUG_LOGIN_DESCRIPTION || 'Save returned token to common headers in debug tool, field name Authorization, field value Bearer token';
      return envDesc + '. Use api_config interface to handle login configuration after successful login.';
    };
Behavior3/5

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

Discloses automatic token extraction and header update, but no details on side effects or error handling; no annotations provided.

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?

Two efficient sentences front-loading purpose and key behavior with an example.

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?

Lacks specification of required environment variable names, error handling, and success/failure indicators.

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?

Schema covers the single parameter well, and description adds context about overriding config baseUrl.

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?

Clearly identifies as an API login authentication tool and distinguishes from sibling tools like default_api_config or default_api_execute.

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

Usage Guidelines2/5

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

Lacks guidance on when to use vs alternatives, no prerequisites or context about needing to call this before other operations.

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/liliangshan/mcp-server-apidebug'

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