download_instagram_video
Download Instagram videos, reels, and TV content to your local filesystem with optional metadata and caption extraction.
Instructions
Download an Instagram video's media files to the local filesystem.
Args: url: Instagram post/reel/tv URL. username: Optional Instagram username for authenticated access. password: Optional Instagram password for authenticated access. save_metadata: Save JSON metadata files when available. save_caption: Save caption into a text file when available. download_root: Optional override for download directory.
Returns: A JSON-serializable dict containing download results.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| url | Yes | ||
| username | No | ||
| password | No | ||
| save_metadata | No | ||
| save_caption | No | ||
| download_root | No |
Implementation Reference
- src/ig_download_mcp/server.py:230-288 (handler)The primary handler function for the 'download_instagram_video' MCP tool. It orchestrates shortcode extraction, Instaloader configuration, authentication, video download, and result reporting. Also serves as the registration point via the @mcp.tool() decorator.@mcp.tool() def download_instagram_video( url: str, username: str | None = None, password: str | None = None, save_metadata: bool = True, save_caption: bool = True, download_root: str | None = None, ) -> dict[str, Any]: """Download an Instagram video's media files to the local filesystem. Args: url: Instagram post/reel/tv URL. username: Optional Instagram username for authenticated access. password: Optional Instagram password for authenticated access. save_metadata: Save JSON metadata files when available. save_caption: Save caption into a text file when available. download_root: Optional override for download directory. Returns: A JSON-serializable dict containing download results. """ try: shortcode = extract_shortcode(url) target_root = _resolve_download_root(download_root) loader = _build_instaloader( target_root, download_pictures=False, download_videos=True, save_metadata=save_metadata, save_caption=save_caption, ) user, pwd = _resolve_credentials(username, password) _login_if_needed(loader, user, pwd) video_files = _download_videos_for_shortcode( loader, shortcode, target_root, ) download_dir = target_root / shortcode after = _snapshot_files(download_dir) metadata_files = _collect_paths_by_suffixes(after, {".json"}) caption_files = _collect_paths_by_suffixes(after, {".txt"}) return { "success": True, "shortcode": shortcode, "download_dir": str(download_dir), "video_files": [str(path) for path in video_files], "metadata_files": metadata_files, "caption_files": caption_files, } except instaloader.exceptions.InstaloaderException as exc: return { "success": False, "error": f"Instaloader error: {exc.__class__.__name__}: {exc}", } except Exception as exc: return {"success": False, "error": str(exc)}
- src/ig_download_mcp/server.py:33-58 (helper)Helper function to parse Instagram URLs and extract the post shortcode using regex, essential for targeting specific content.def extract_shortcode(url: str) -> str: """Extract an Instagram shortcode from a supported URL. Supported formats include: - https://www.instagram.com/p/<shortcode>/ - https://www.instagram.com/reel/<shortcode>/ - https://www.instagram.com/tv/<shortcode>/ Args: url: Instagram post/reel/tv URL. Returns: The extracted shortcode. Raises: ValueError: If the shortcode cannot be extracted. """ pattern = ( r"(?:https?://)?(?:www\.)?(?:m\.)?instagram\.com/" r"(?:p|reel|tv)/([A-Za-z0-9_-]+)" ) match = re.search(pattern, url) if not match: raise ValueError("Unsupported Instagram URL format.") return match.group(1)
- Core helper that performs the actual Instaloader download for a shortcode, filters for video files (.mp4), and returns their paths.def _download_videos_for_shortcode( loader: instaloader.Instaloader, shortcode: str, download_root: Path, ) -> list[Path]: download_root.mkdir(parents=True, exist_ok=True) download_dir = download_root / shortcode before = _snapshot_files(download_dir) post = instaloader.Post.from_shortcode(loader.context, shortcode) if not _post_has_video(post): raise ValueError("The Instagram post does not contain video content.") loader.download_post(post, target=shortcode) after = _snapshot_files(download_dir) new_files = after - before video_files = sorted( [path for path in new_files if path.suffix.lower() == ".mp4"], key=lambda p: p.stat().st_mtime, reverse=True, ) if video_files: return video_files all_videos = sorted( [path for path in after if path.suffix.lower() == ".mp4"], key=lambda p: p.stat().st_mtime, reverse=True, ) if all_videos: return all_videos raise RuntimeError("Download completed but no video files were found.")
- src/ig_download_mcp/server.py:60-81 (helper)Helper to configure and instantiate Instaloader with tool-specific download options, directory patterns, and metadata settings.def _build_instaloader( download_root: Path, download_pictures: bool = False, download_videos: bool = True, save_metadata: bool = False, save_caption: bool = False, ) -> instaloader.Instaloader: dirname_pattern = str(download_root / "{target}") post_metadata_txt_pattern = "{caption}" if save_caption else "" return instaloader.Instaloader( quiet=True, dirname_pattern=dirname_pattern, download_pictures=download_pictures, download_videos=download_videos, download_video_thumbnails=False, download_geotags=False, download_comments=False, save_metadata=save_metadata, compress_json=False, post_metadata_txt_pattern=post_metadata_txt_pattern, )
- src/ig_download_mcp/server.py:227-227 (registration)Instantiates the FastMCP server object 'mcp' to which all tools, including 'download_instagram_video', are registered via decorators.mcp = FastMCP("ig-download-mcp")