Skip to main content
Glama
ricleedo

Google Services MCP Server

by ricleedo

gmail-get-labels

Retrieve all labels from a Gmail account to organize and categorize emails effectively.

Instructions

Get all Gmail labels

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The core handler function that authenticates with Gmail API, lists all labels, maps them to a structured format, and returns formatted Markdown output or error.
    // Get Gmail labels function
    export async function getLabels() {
      try {
        const auth = createGmailAuth();
        const gmail = google.gmail({ version: "v1", auth });
    
        const response = await gmail.users.labels.list({
          userId: "me",
        });
    
        const labels = response.data.labels?.map((label) => ({
          id: label.id,
          name: label.name,
          type: label.type,
          messagesTotal: label.messagesTotal,
          messagesUnread: label.messagesUnread,
          threadsTotal: label.threadsTotal,
          threadsUnread: label.threadsUnread,
        }));
    
        return {
          content: [
            {
              type: "text" as const,
              text: formatLabelsToMarkdown(labels || []),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text" as const,
              text: `Error getting labels: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
        };
      }
    }
  • src/index.ts:209-211 (registration)
    Registers the 'gmail-get-labels' tool with the MCP server, providing no input schema and delegating execution to the getLabels handler.
    server.tool("gmail-get-labels", "Get all Gmail labels", {}, async () => {
      return await getLabels();
    });
  • Helper function that formats the retrieved Gmail labels into a Markdown string, categorizing system and custom labels with unread/message counts.
    function formatLabelsToMarkdown(labels: any[]): string {
      if (!labels.length) return "No labels found.";
      
      let markdown = `# Gmail Labels (${labels.length})\n\n`;
      
      const systemLabels = labels.filter(label => label.type === 'system');
      const userLabels = labels.filter(label => label.type === 'user');
      
      if (systemLabels.length) {
        markdown += `## System Labels\n\n`;
        systemLabels.forEach(label => {
          markdown += `- ${label.name} (\`${label.id}\`)`;
          if (label.messagesUnread > 0) {
            markdown += ` - ${label.messagesUnread} unread`;
          }
          markdown += `\n`;
        });
        markdown += `\n`;
      }
      
      if (userLabels.length) {
        markdown += `## Custom Labels\n\n`;
        userLabels.forEach(label => {
          markdown += `- ${label.name} (\`${label.id}\`)`;
          if (label.messagesTotal) {
            markdown += ` - ${label.messagesTotal} total`;
            if (label.messagesUnread > 0) {
              markdown += `, ${label.messagesUnread} unread`;
            }
          }
          markdown += `\n`;
        });
      }
      
      return markdown;
    }
  • Shared helper for creating OAuth2 authentication client used by all Gmail tools, reading credentials from environment variables.
    function createGmailAuth() {
      const clientId = process.env.GOOGLE_CLIENT_ID;
      const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
      const redirectUri =
        process.env.GOOGLE_REDIRECT_URI || "http://localhost:3000/oauth2callback";
    
      if (!clientId || !clientSecret) {
        throw new Error(
          "GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET are required. Run oauth-setup.js to configure."
        );
      }
    
      const oauth2Client = new google.auth.OAuth2(
        clientId,
        clientSecret,
        redirectUri
      );
    
      const accessToken = process.env.GOOGLE_ACCESS_TOKEN;
      const refreshToken = process.env.GOOGLE_REFRESH_TOKEN;
    
      if (!accessToken || !refreshToken) {
        throw new Error("OAuth2 tokens missing. Run oauth-setup.js to get tokens.");
      }
    
      oauth2Client.setCredentials({
        access_token: accessToken,
        refresh_token: refreshToken,
      });
    
      return oauth2Client;
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed2 schema fields changedv1.0.0
    • addedInput schema / $schema
      Added value: +"http://json-schema.org/draft-07/schema#"
    • addedInput schema / additionalProperties
      Added value: +false
  2. First observed

TDQS

B3.2/5.0
Behavior2/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 of behavioral disclosure. 'Get all Gmail labels' implies a read-only operation, but it does not specify authentication requirements, rate limits, pagination, or error handling. For a tool with zero annotation coverage, this is a significant gap in transparency.

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 a single, efficient sentence with zero waste. It is front-loaded and directly communicates the core functionality without unnecessary elaboration, making it highly concise and well-structured.

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 simplicity (0 parameters, no output schema) and lack of annotations, the description is minimally complete. It states what the tool does but lacks details on behavior, usage, or output format. This is adequate for a basic read operation but leaves gaps in contextual understanding.

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 input schema has 0 parameters with 100% coverage, so no parameter documentation is needed. The description does not add parameter details, which is appropriate here. A baseline of 4 is applied as it adequately handles the lack of parameters without introducing confusion.

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

Purpose4/5

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

The description 'Get all Gmail labels' clearly states the verb ('Get') and resource ('Gmail labels'), making the purpose immediately understandable. It distinguishes from siblings like 'gmail-get-email' or 'gmail-send-email' by focusing on labels rather than emails. However, it lacks specificity about scope (e.g., all labels for the authenticated user) which prevents a perfect score.

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?

No guidance is provided on when to use this tool versus alternatives. The description does not mention prerequisites, context, or comparisons with sibling tools like 'gmail-read-emails' or 'gmail-get-email'. This leaves the agent without explicit direction on appropriate usage scenarios.

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