Skip to main content
Glama

download_resource

Download Moodle course materials like PPTs and PDFs from a URL to your computer. Specify a custom folder or use the default download location.

Instructions

Download Moodle resource file(s) (PPT, PDF, etc.) from a URL. Supports saving to a custom local directory.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
resource_urlYesThe exact Moodle resource URL to download from.
download_pathNoThe absolute folder path string (e.g. '/Users/cosmos/Desktop'). IMPORTANT: This must be a STRING value, NOT a boolean. WRONG: true, false. RIGHT: '/path/to/folder'. If not provided, it uses the default system download folder.

Implementation Reference

  • The primary handler function for downloading Moodle resources. It uses Selenium to load the resource page, extracts download links (pluginfile.php), transfers session cookies to requests library, downloads files while skipping existing ones, and returns details on downloaded and skipped files.
    def download_resource(self, resource_url: str, download_path: Optional[str] = None) -> Dict[str, Any]:
        """
        Download resource(s) from Moodle using the authenticated session."""
    
        resolved_download_path = download_path or DOWNLOAD_DIR
        self._ensure_driver()
    
        if not self.logged_in:
            if not self.login():
                raise Exception("Login required to download resources.")
        
    
        self.heartBeat()
        try:
            # Navigate to the resource page to get the actual download URL
            self.driver.get(resource_url)
            
            # Wait for the page to load and find download links
            WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "a[onclick*='target='], a[href*='pluginfile.php']"))
            )
    
            # Find all direct download links
            download_links = self.driver.find_elements(By.CSS_SELECTOR, "a[onclick*='target='], a[href*='pluginfile.php']")
            if not download_links:
                return {"error": "No download links found on the resource page"}
            
            # Get cookies from Selenium session for requests
            cookies = {}
            for cookie in self.driver.get_cookies():
                cookies[cookie['name']] = cookie['value']
            self.heartBeat()
            # Download headers
            headers = {
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
            }
            self.heartBeat()
            downloaded_files = []
            skipped_files = []
            errors = []
            self.heartBeat()
            # Create download directory
            Path(resolved_download_path).mkdir(parents=True, exist_ok=True)
            self.heartBeat()
            for i, link in enumerate(download_links):
                try:
                    download_url = link.get_attribute('href')
                    if not download_url or not download_url.startswith('http'):
                        continue
                    self.heartBeat()
                    # Skip non-file links
                    if 'pluginfile.php' not in download_url:
                        continue
                    self.heartBeat()
                    # Extract filename from URL or link text
                    filename = None
                    try:
                        # Try to get filename from the link text first
                        link_text = link.text.strip()
                        if link_text and '.' in link_text and len(link_text) < 200:
                            filename = link_text
                        else:
                            # Extract from URL
                            parsed_url = urllib.parse.urlparse(download_url)
                            path_parts = parsed_url.path.split('/')
                            for part in reversed(path_parts):
                                if '.' in part and len(part) < 200:
                                    filename = urllib.parse.unquote(part)
                                    break
                    except Exception:
                        pass
                    self.heartBeat()
                    if not filename:
                        filename = f"download_{int(time.time())}_{i}"
    
                    # Skip if file exists
                    file_path = Path(resolved_download_path) / filename
                    if file_path.exists():
                        skipped_files.append(filename)
                        continue
                    
                    # Download the file
                    response = requests.get(download_url, cookies=cookies, headers=headers, stream=True)
                    response.raise_for_status()
                    
                    # Write file
                    with open(file_path, 'wb') as f:
                        for chunk in response.iter_content(chunk_size=8192):
                            f.write(chunk)
                    
                    file_size = file_path.stat().st_size
                    
                    downloaded_files.append({
                        "filename": file_path.name,
                        "file_path": str(file_path),
                        "file_size": file_size,
                        "download_url": download_url
                    })
                    
                except requests.exceptions.RequestException as e:
                    errors.append(f"Failed to download {download_url}: {str(e)}")
                except Exception as e:
                    errors.append(f"Unexpected error downloading file {i+1}: {str(e)}")
            
            if downloaded_files or skipped_files:
                result = {
                    "success": True,
                    "total_downloaded": len(downloaded_files),
                    "total_skipped": len(skipped_files),
                    "downloaded_files": downloaded_files,
                    "skipped_files": skipped_files,
                }
                if errors:
                    result["errors"] = errors
                return result
            else:
                return {"error": f"No files were downloaded. Errors: {'; '.join(errors)}"}
            
        except Exception as e:
            return {"error": f"Unexpected error during download: {str(e)}"}
  • main.py:53-70 (schema)
    The input schema definition for the download_resource tool, defining parameters resource_url (required string) and optional download_path (string or null).
        inputSchema={
            "type": "object",
            "properties": {
                "resource_url": {
                    "type": "string",
                    "description": "The exact Moodle resource URL to download from.",
                },
                "download_path": {
                    "type": ["string", "null"],
                    "description": "The absolute folder path string (e.g. '/Users/cosmos/Desktop'). \nIMPORTANT: This must be a STRING value, NOT a boolean. \nWRONG: true, false. \nRIGHT: '/path/to/folder'. \nIf not provided, it uses the default system download folder.",
                },
            },
            "required": ["resource_url"],
        },
    ),
    Tool(
        name="open_URL_with_authorization",
        description="Open a URL in a new authorized browser window after Moodle login (show to user).",
  • main.py:213-214 (registration)
    Registration and dispatching logic in the MCP server's call_tool handler, which maps the tool name to its wrapper function execution.
    if name == "download_resource":
        return _wrap_json(tool_download_resource(args["resource_url"], args.get("download_path")))
  • Thin wrapper function around the core download_resource method, adding error handling and integrating with the MCP server response format.
    def tool_download_resource(resource_url: str, download_path: Optional[str] = None) -> Dict[str, Any]:
        try:
            return muster_client.download_resource(resource_url, download_path)
        except Exception as e:
            return {"error": f"Failed to download resource: {str(e)}"}
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 states the tool downloads files and supports custom directories, but fails to mention critical behaviors such as authentication requirements (implied by Moodle context), error handling (e.g., invalid URLs), file overwriting risks, or rate limits. This leaves significant gaps for a tool that interacts with external resources.

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 front-loaded with the core purpose in the first sentence and adds a supporting detail in the second. It avoids redundancy and wastes no words, making it efficient. However, it could be slightly more structured by separating key behaviors, but overall it's appropriately concise for its content.

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 tool's complexity (involving external downloads and file system operations), no annotations, and no output schema, the description is incomplete. It lacks details on authentication, error responses, file naming, or success indicators, which are crucial for safe and effective use. The schema covers parameters well, but behavioral aspects are underspecified.

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

Parameters3/5

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

Schema description coverage is 100%, with clear documentation for both parameters (resource_url and download_path), including format examples and default behavior. The description adds marginal value by mentioning 'Moodle resource' and 'custom local directory,' which contextualizes the parameters but doesn't provide additional semantic details beyond what the schema already covers.

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 ('Download') and resource ('Moodle resource file(s)'), specifying file types like PPT and PDF. It distinguishes from siblings by focusing on downloading rather than retrieving information (e.g., get_course_content) or opening URLs. However, it doesn't explicitly differentiate from open_URL_with_authorization, which might also involve URL access, leaving slight ambiguity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for downloading files from Moodle URLs, but provides no explicit guidance on when to use this tool versus alternatives like open_URL_with_authorization for URL access or get_course_content for content retrieval. It mentions saving to a custom directory, which hints at context for file storage, but lacks clear when-not-to-use or prerequisite information.

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

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/Cosmostima/MUSTer_MCP'

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