Skip to main content
Glama

search_gdrive

Locate and retrieve specific files in Google Drive by entering search queries. Supports pagination with page size and token options for efficient file management.

Instructions

Search for files in Google Drive

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
page_sizeNo
page_tokenNo
queryYes

Implementation Reference

  • The main handler function implementing the 'search_gdrive' tool. It authenticates with Google Drive API, constructs a search query based on the input, lists files matching the query, and returns formatted results with pagination support.
    async def search_gdrive(query: str, page_token: Optional[str] = None, page_size: Optional[int] = 10) -> Dict[str, Any]:
        """
        Search for files in Google Drive
        
        Args:
            query (str): Name of the file to be searched for
            page_token (str, optional): Token for the next page of results
            page_size (int, optional): Number of results per page (max 100). Defaults to 10.
        
        Returns:
            Dict[str, Any]: A dictionary containing:
                - success (bool): Whether the operation was successful
                - files (list): List of files found with their metadata
                - next_page_token (str): Token for the next page of results (if available)
                - total_files (int): Total number of files found
                - error (str): Error message (when unsuccessful)
        """
        creds = get_google_credentials()
        if not creds:
            return {
                "success": False,
                "error": "Google authentication failed."
            }
    
        try:
            # Initialize Google Drive API service
            service = build('drive', 'v3', credentials=creds)
            
            user_query = query.strip()
            search_query = ""
            
            # If query is empty, list all files
            if not user_query:
                search_query = "trashed = false"
            else:
                # Escape special characters in the query
                escaped_query = user_query.replace("\\", "\\\\").replace("'", "\\'")
                
                # Build search query with multiple conditions
                conditions = []
                
                # Search in title
                conditions.append(f"name contains '{escaped_query}'")
                
                # If specific file type is mentioned in query, add mimeType condition
                if "sheet" in user_query.lower():
                    conditions.append("mimeType = 'application/vnd.google-apps.spreadsheet'")
                elif "doc" in user_query.lower():
                    conditions.append("mimeType = 'application/vnd.google-apps.document'")
                elif "presentation" in user_query.lower() or "slide" in user_query.lower():
                    conditions.append("mimeType = 'application/vnd.google-apps.presentation'")
                
                search_query = f"({' or '.join(conditions)}) and trashed = false"
            
            # Set page size with limits
            if page_size is None:
                page_size = 10
            page_size = min(max(1, page_size), 100)  # Ensure between 1 and 100
            
            # Execute the search
            response = service.files().list(
                q=search_query,
                pageSize=page_size,
                pageToken=page_token,
                orderBy="modifiedTime desc",
                fields="nextPageToken, files(id, name, mimeType, modifiedTime, size)"
            ).execute()
            
            files = response.get('files', [])
            next_page_token = response.get('nextPageToken')
            
            # Format file list with additional details
            formatted_files = []
            for file in files:
                formatted_files.append({
                    "id": file.get('id', ''),
                    "name": file.get('name', ''),
                    "mime_type": file.get('mimeType', ''),
                    "modified_time": file.get('modifiedTime', ''),
                    "size": file.get('size', 'N/A')
                })
            
            logger.info(f"Google Drive 검색 결과: {len(formatted_files)}개의 파일 찾음")
            
            return {
                "success": True,
                "files": formatted_files,
                "total_files": len(formatted_files),
                "next_page_token": next_page_token
            }
        
        except HttpError as error:
            logger.error(f"Drive API 오류 발생: {error}")
            return {
                "success": False,
                "error": f"Google Drive API Error: {str(error)}",
                "files": []
            }
        except Exception as e:
            logger.exception("파일 검색 중 오류:")
            return {
                "success": False,
                "error": f"예상치 못한 오류 발생: {str(e)}",
                "files": []
            }
  • server.py:784-787 (registration)
    Registration of the 'search_gdrive' tool using the FastMCP @mcp.tool decorator, specifying the tool name and description.
    @mcp.tool(
        name="search_gdrive",
        description="Search for files in Google Drive",
    )
  • Input/output schema defined in the function docstring, describing parameters (query, page_token, page_size) and return format.
    """
    Search for files in Google Drive
    
    Args:
        query (str): Name of the file to be searched for
        page_token (str, optional): Token for the next page of results
        page_size (int, optional): Number of results per page (max 100). Defaults to 10.
    
    Returns:
        Dict[str, Any]: A dictionary containing:
            - success (bool): Whether the operation was successful
            - files (list): List of files found with their metadata
            - next_page_token (str): Token for the next page of results (if available)
            - total_files (int): Total number of files found
            - error (str): Error message (when unsuccessful)
    """
  • server.py:203-203 (registration)
    'search_gdrive' is listed among the available Google tools in the get_available_google_tools resource.
    "search_google", "read_gdrive_file", "search_gdrive"
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. It only states the basic action ('Search for files') without mentioning permissions, rate limits, pagination behavior (implied by page_size/page_token but not explained), or what the search returns. This leaves significant gaps for a tool with 3 parameters.

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 basic tool description, though it lacks depth due to its brevity.

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 the complexity (3 parameters, no annotations, no output schema), the description is incomplete. It doesn't cover parameter usage, behavioral traits, or output expectations. For a search tool with pagination and query parameters, more context is needed to use it effectively.

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 but adds no parameter information. It doesn't explain what 'query' should contain (e.g., search syntax), what 'page_size' and 'page_token' do, or how results are structured. With 3 parameters, this is inadequate.

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 ('Search') and resource ('files in Google Drive'), making the purpose immediately understandable. However, it doesn't distinguish this tool from sibling tools like 'search_google' or 'read_gdrive_file', which might have overlapping or related 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?

The description provides no guidance on when to use this tool versus alternatives. With sibling tools like 'search_google' (possibly broader search) and 'read_gdrive_file' (reading specific files), there's no indication of context, prerequisites, or exclusions for this search tool.

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