Skip to main content
Glama
cindyloo

Dropbox MCP Server

by cindyloo

list_files

Browse and view files and folders stored in your Dropbox directory to organize and access your cloud content.

Instructions

List files and folders in a Dropbox directory.

Args: folder_path: Path to the folder (empty string for root) max_files: Maximum number of items to return

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
folder_pathNo
max_filesNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Handler function for the 'list_files' tool. Lists files and folders in a specified Dropbox directory using the Dropbox API, generates content previews for text files by calling get_file_content helper, and returns a list of FileInfo objects. Decorated with @mcp.tool() for automatic registration.
    @mcp.tool()
    def list_files(folder_path: str = "", max_files: int = 20) -> List[FileInfo]:
        """
        List files and folders in a Dropbox directory.
        
        Args:
            folder_path: Path to the folder (empty string for root)
            max_files: Maximum number of items to return
        """
        if not dropbox_client:
            initialize_dropbox_client()
        
        try:
            # Ensure path starts with / if not empty
            if folder_path and not folder_path.startswith('/'):
                folder_path = '/' + folder_path
            
            # List folder contents
            result = dropbox_client.files_list_folder(
                folder_path,
                limit=max_files
            )
            
            files = []
            for entry in result.entries:
                if isinstance(entry, dropbox.files.FileMetadata):
                    # Get preview for text files
                    preview = None
                    if entry.name.lower().endswith(('.txt', '.md', '.py', '.js')):
                        try:
                            content = get_file_content(entry.path_lower)
                            preview = content[:200] + "..." if len(content) > 200 else content
                        except:
                            preview = "[Could not load preview]"
                    
                    files.append(FileInfo(
                        name=entry.name,
                        path=entry.path_lower,
                        size=entry.size,
                        modified=entry.server_modified.isoformat(),
                        is_folder=False,
                        content_preview=preview
                    ))
                elif isinstance(entry, dropbox.files.FolderMetadata):
                    files.append(FileInfo(
                        name=entry.name,
                        path=entry.path_lower,
                        size=0,
                        modified="",
                        is_folder=True
                    ))
            
            return files
            
        except Exception as e:
            raise ValueError(f"Failed to list files: {e}")
  • Pydantic model (BaseModel) defining the output schema for file listing tools including list_files, get_file_info. Used as return type annotation.
    class FileInfo(BaseModel):
        """File information structure."""
        name: str
        path: str
        size: int
        modified: str
        is_folder: bool
        content_preview: Optional[str] = None
  • Duplicate handler function for the 'list_files' tool with identical implementation to dropbox_server.py.
    @mcp.tool()
    def list_files(folder_path: str = "", max_files: int = 20) -> List[FileInfo]:
        """
        List files and folders in a Dropbox directory.
        
        Args:
            folder_path: Path to the folder (empty string for root)
            max_files: Maximum number of items to return
        """
        if not dropbox_client:
            initialize_dropbox_client()
        
        try:
            # Ensure path starts with / if not empty
            if folder_path and not folder_path.startswith('/'):
                folder_path = '/' + folder_path
            
            # List folder contents
            result = dropbox_client.files_list_folder(
                folder_path,
                limit=max_files
            )
            
            files = []
            for entry in result.entries:
                if isinstance(entry, dropbox.files.FileMetadata):
                    # Get preview for text files
                    preview = None
                    if entry.name.lower().endswith(('.txt', '.md', '.py', '.js')):
                        try:
                            content = get_file_content(entry.path_lower)
                            preview = content[:200] + "..." if len(content) > 200 else content
                        except:
                            preview = "[Could not load preview]"
                    
                    files.append(FileInfo(
                        name=entry.name,
                        path=entry.path_lower,
                        size=entry.size,
                        modified=entry.server_modified.isoformat(),
                        is_folder=False,
                        content_preview=preview
                    ))
                elif isinstance(entry, dropbox.files.FolderMetadata):
                    files.append(FileInfo(
                        name=entry.name,
                        path=entry.path_lower,
                        size=0,
                        modified="",
                        is_folder=True
                    ))
            
            return files
            
        except Exception as e:
            raise ValueError(f"Failed to list files: {e}")
  • Helper function to initialize the global Dropbox client used by list_files and other tools.
    def initialize_dropbox_client():
        """Initialize Dropbox client with access token from environment."""
        global dropbox_client
        
        access_token = os.getenv('DROPBOX_ACCESS_TOKEN')
        if not access_token:
            raise ValueError(
                "DROPBOX_ACCESS_TOKEN environment variable is required. "
                "Get your token from https://www.dropbox.com/developers/apps"
            )
        
        try:
            dropbox_client = dropbox.Dropbox(access_token)
            # Test the connection
            dropbox_client.users_get_current_account()
            logger.info("Dropbox client initialized successfully")
        except AuthError as e:
            raise ValueError(f"Invalid Dropbox access token: {e}")
        except Exception as e:
            raise ValueError(f"Failed to initialize Dropbox client: {e}")
  • Helper function called by list_files to generate content previews for text files, and by read_file.
    def get_file_content(file_path: str) -> str:
        """Download and extract text content from a Dropbox file."""
        if not dropbox_client:
            raise ValueError("Dropbox client not initialized")
        
        try:
            # Download file content
            _, response = dropbox_client.files_download(file_path)
            file_content = response.content
            
            # Extract text based on file extension
            file_ext = file_path.lower().split('.')[-1]
            
            if file_ext == 'pdf':
                return extract_text_from_pdf(file_content)
            elif file_ext in ['docx', 'doc']:
                return extract_text_from_docx(file_content)
            elif file_ext in ['txt', 'md', 'py', 'js', 'html', 'css', 'json', 'csv']:
                # Text files
                try:
                    return file_content.decode('utf-8')
                except UnicodeDecodeError:
                    try:
                        return file_content.decode('latin-1')
                    except UnicodeDecodeError:
                        return "[Binary file - cannot display as text]"
            else:
                return f"[Unsupported file type: {file_ext}]"
                
        except ApiError as e:
            raise ValueError(f"Dropbox API error: {e}")
        except Exception as e:
            raise ValueError(f"Error reading file: {e}")

Tool Definition Quality

Score is being calculated. Check back soon.

Install Server

Other 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/cindyloo/dropbox-mcp-server'

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