Skip to main content
Glama
KaiQin04

Instagram Download MCP Server

by KaiQin04

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

TableJSON Schema
NameRequiredDescriptionDefault
urlYes
usernameNo
passwordNo
save_metadataNo
save_captionNo
download_rootNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • 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)}
  • 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.")
  • 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,
        )
  • Instantiates the FastMCP server object 'mcp' to which all tools, including 'download_instagram_video', are registered via decorators.
    mcp = FastMCP("ig-download-mcp")
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden. It mentions authentication options and file-saving behaviors but lacks critical details: whether authentication bypasses rate limits, what happens if files already exist, error handling, or local filesystem permissions needed. 'Download to local filesystem' implies write operations but doesn't specify risks.

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?

Well-structured with a clear opening sentence followed by Args/Returns sections. Every sentence adds value: the first states purpose, Args explain parameters, Returns specifies output format. Slightly verbose but efficiently organized.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 6 parameters, no annotations, and an output schema (which covers return values), the description is moderately complete. It explains parameters well but lacks behavioral context about authentication benefits, file conflicts, or error conditions that would be crucial for a download tool with write operations.

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

Parameters4/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. It provides clear semantic explanations for all 6 parameters: url purpose, optional auth fields, metadata/caption saving behaviors, and download directory override. This adds substantial value beyond the bare schema with only titles.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Download') and target resource ('Instagram video's media files') with destination ('to the local filesystem'). It distinguishes from siblings by specifying 'video' content rather than highlights, posts, profile pictures, or stories.

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 Instagram videos via URLs (posts/reels/tv) but doesn't explicitly state when to use this vs. sibling tools like 'download_instagram_post' which might overlap. It mentions optional authentication but doesn't explain when authentication is needed or beneficial.

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/KaiQin04/ig-download-mcp'

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