Skip to main content
Glama

list_emails

Fetch and display recent emails from your Gmail inbox using a specific search query, with options to limit the number of results.

Instructions

List recent emails from Gmail inbox

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
max_resultsNo
queryYes

Implementation Reference

  • The handler function for the 'list_emails' tool. It is decorated with @mcp.tool(name="list_emails"), takes query and max_results parameters, authenticates with Google, queries the Gmail API for messages, extracts metadata (id, threadId, subject, from, date, snippet), and returns a list of email dictionaries.
    @mcp.tool(
        name="list_emails",
        description="List recent emails from Gmail inbox",
    )
    async def list_emails(query: str, max_results: int = 10) -> List[Dict[str, Any]]:
        """
        List recent emails from Gmail inbox
        
        Args:
            query (str): Search query to filter emails
            max_results (int): Maximum number of emails to return (default: 10)
        
        Returns:
            List[Dict[str, Any]]: List of email details
        """
        creds = get_google_credentials()
        if not creds:
            return "Google authentication failed."
    
        try:
            service = build('gmail', 'v1', credentials=creds)
            results = service.users().messages().list(
                userId='me',
                maxResults=max_results,
                q=query or ""
            ).execute()
    
            messages = results.get('messages', [])
            email_details = []
            for msg in messages:
                msg_data = service.users().messages().get(userId='me', id=msg['id'], format='metadata', metadataHeaders=['Subject', 'From', 'Date']).execute()
                headers = {h['name']: h['value'] for h in msg_data.get('payload', {}).get('headers', [])}
                email_details.append({
                    'id': msg['id'],
                    'threadId': msg.get('threadId'),
                    'subject': headers.get('Subject', '(No Subject)'),
                    'from': headers.get('From'),
                    'date': headers.get('Date'),
                    'snippet': msg_data.get('snippet'),
                })
    
            # CallToolResponse 반환 (MCP 표준)
            return email_details
    
        except HttpError as error:
            logger.error(f"API 오류 발생: {error}")
            return f"Gmail API 오류: {error.resp.status} - {error.content.decode()}"
        except Exception as e:
            logger.exception("이메일 목록 조회 중 오류:")
            return f"예상치 못한 오류 발생: {str(e)}"
  • server.py:209-212 (registration)
    The @mcp.tool decorator registers the 'list_emails' tool with MCP server, specifying its name and description.
    @mcp.tool(
        name="list_emails",
        description="List recent emails from Gmail inbox",
    )
  • The function signature provides the input schema (query: str, max_results: int=10) and output type (List[Dict[str, Any]]), along with detailed docstring describing parameters and return value.
    async def list_emails(query: str, max_results: int = 10) -> List[Dict[str, Any]]:
  • The get_google_credentials helper function used by list_emails to obtain Google API credentials from token.json or environment variables, handling refresh if needed.
    def get_google_credentials() -> Optional[Credentials]:
        """
        Google API 접근을 위한 인증 정보를 가져옵니다.
        기존 token.json 파일이 있으면 로드하고, 만료 시 리프레시합니다.
        없거나 유효하지 않으면 None을 반환합니다 (초기 인증 필요).
        """
        creds = None
        if os.path.exists(TOKEN_FILE):
            try:
                with open(TOKEN_FILE, 'r') as token:
                    creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
            except Exception as e:
                logger.error(f"토큰 파일 로딩 오류: {e}")
                creds = None
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                logger.info("Google API 자격 증명 갱신 중.")
                try:
                    creds.refresh(Request())
                    with open(TOKEN_FILE, 'w') as token:
                        token.write(creds.to_json())
                    logger.info("자격 증명 갱신 및 저장 완료.")
                except Exception as e:
                    logger.error(f"토큰 갱신 실패: {e}")
                    return None
            elif GOOGLE_REFRESH_TOKEN and GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET:
                logger.info("환경 변수의 리프레시 토큰 사용 중.")
                try:
                    creds = Credentials(
                        token=None,
                        refresh_token=GOOGLE_REFRESH_TOKEN,
                        token_uri='https://oauth2.googleapis.com/token',
                        client_id=GOOGLE_CLIENT_ID,
                        client_secret=GOOGLE_CLIENT_SECRET,
                        scopes=SCOPES
                    ) 
                    creds.refresh(Request())
                    with open(TOKEN_FILE, 'w') as token:
                        token.write(creds.to_json())
                    logger.info("리프레시 토큰으로 자격 증명 얻고 저장 완료.")
                except Exception as e:
                    logger.error(f"리프레시 토큰으로 토큰 얻기 실패: {e}")
                    return None
            else:
                logger.error("유효한 자격 증명 또는 리프레시 토큰을 찾을 수 없습니다. 수동 인증이 필요합니다.")
                return None
    
        return creds
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states this is a list operation but doesn't mention whether it requires authentication, has rate limits, what 'recent' means temporally, or how results are ordered. This leaves significant gaps in understanding the tool's behavior.

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 that gets straight to the point with no wasted words. It's appropriately sized for a simple list operation and front-loads the core functionality.

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

Completeness2/5

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

For a tool with no annotations, no output schema, and 0% schema description coverage, the description is inadequate. It doesn't explain return format, error conditions, authentication requirements, or how parameters interact. Given the complexity of email retrieval and sibling tools, more context is needed.

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

Parameters2/5

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

The schema description coverage is 0%, so the description must compensate. It mentions 'recent emails' but doesn't explain how the 'query' parameter works (e.g., Gmail search syntax) or what 'max_results' controls beyond its name. The description adds minimal value beyond what's implied by parameter names.

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 clearly states the verb ('List') and resource ('recent emails from Gmail inbox'), making the purpose immediately understandable. However, it doesn't distinguish this tool from sibling 'search_emails', which appears to be a similar email retrieval tool, so it doesn't achieve full differentiation.

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?

The description provides no guidance on when to use this tool versus alternatives like 'search_emails' or 'modify_email'. It mentions 'recent emails' but doesn't define what 'recent' means or specify any exclusions or prerequisites for usage.

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

Related 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/jikime/py-mcp-google-toolbox'

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