Skip to main content
Glama

search_emails

Retrieve specific emails using advanced queries to locate relevant information efficiently. Specify search terms and set a maximum number of results for targeted email retrieval.

Instructions

Search emails with advanced query

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
max_resultsNo
queryYes

Implementation Reference

  • The main handler function for the 'search_emails' tool. It authenticates with Google Gmail API, performs the search using the provided query, fetches full message details including body extraction via helper, and returns a list of email dictionaries.
    async def search_emails(query: str, max_results: int = 10) -> List[Dict[str, Any]]:
        """
        Search emails with advanced query
        
        Args:
            query (str): Gmail search query (e.g., "from:example@gmail.com has:attachment")
            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
            ).execute()
    
            messages = results.get('messages', [])
            email_details = []
            for msg in messages:
                msg_full = service.users().messages().get(userId='me', id=msg['id'], format='full').execute()
                payload = msg_full.get('payload', {})
                headers = {h['name']: h['value'] for h in payload.get('headers', [])}
                body = _get_email_body(payload)
                email_details.append({
                    'id': msg['id'],
                    'threadId': msg.get('threadId'),
                    'subject': headers.get('Subject', '(No Subject)'),
                    'from': headers.get('From'),
                    'to': headers.get('To'),
                    'date': headers.get('Date'),
                    'body': body,
                    'labels': msg_full.get('labelIds', []),
                    'snippet': msg_full.get('snippet'),
                })
    
            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:261-264 (registration)
    The @mcp.tool decorator that registers the search_emails function as an MCP tool with name and description.
    @mcp.tool(
        name="search_emails",
        description="Search emails with advanced query",
    )
  • Helper function used by the search_emails handler to extract plain text body from Gmail message payloads.
    def _get_email_body(payload: Dict[str, Any]) -> str:
        """Helper function to extract plain text body from email payload."""
        # (Helper function 내용은 변경 없음)
        if not payload:
            return "(No body content)"
        if 'parts' in payload:
            for part in payload['parts']:
                if part['mimeType'] == 'text/plain' and 'body' in part and 'data' in part['body']:
                    return base64.urlsafe_b64decode(part['body']['data']).decode('utf-8')
            for part in payload['parts']:
                if part['mimeType'] == 'multipart/alternative' and 'parts' in part:
                    for sub_part in part['parts']:
                        if sub_part['mimeType'] == 'text/plain' and 'body' in sub_part and 'data' in sub_part['body']:
                            return base64.urlsafe_b64decode(sub_part['body']['data']).decode('utf-8')
        if 'body' in payload and 'data' in payload['body']:
            mime_type = payload.get('mimeType', 'text/plain')
            if 'text/plain' in mime_type:
                return base64.urlsafe_b64decode(payload['body']['data']).decode('utf-8')
        return "(Could not extract plain text body)"
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions 'advanced query' but doesn't disclose behavioral traits such as permissions needed, rate limits, pagination, or what 'advanced' means (e.g., search operators). This leaves critical operational details unspecified.

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 a single, efficient sentence with no wasted words, making it appropriately sized and front-loaded. However, it lacks structural depth that could improve clarity without adding bulk.

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?

Given no annotations, 0% schema coverage, no output schema, and a search tool with siblings, the description is incomplete. It doesn't explain return values, error handling, or contextual nuances, leaving significant gaps for effective agent use.

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?

Schema description coverage is 0%, so the description must compensate. It implies a 'query' parameter but adds no meaning beyond the schema's basic titles. No details on query syntax, format, or how 'max_results' interacts with search are provided, failing to enhance parameter understanding.

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

Purpose3/5

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

The description 'Search emails with advanced query' states the verb ('search') and resource ('emails'), providing a basic purpose. However, it's vague about what 'advanced query' entails and doesn't differentiate from sibling tools like 'list_emails' or 'search_google', leaving ambiguity in scope and functionality.

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. With siblings like 'list_emails' and 'search_google', the description lacks explicit context, prerequisites, or exclusions, offering no help in tool selection.

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