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
| Name | Required | Description | Default |
|---|---|---|---|
| page_size | No | ||
| page_token | No | ||
| query | Yes |
Input Schema (JSON Schema)
{
"properties": {
"page_size": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"default": 10,
"title": "Page Size"
},
"page_token": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"title": "Page Token"
},
"query": {
"title": "Query",
"type": "string"
}
},
"required": [
"query"
],
"title": "search_gdriveArguments",
"type": "object"
}
Implementation Reference
- server.py:788-893 (handler)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", )
- server.py:789-804 (schema)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"