Skip to main content
Glama
goonoo
by goonoo

upload_file_to_notion

Upload files to Notion via API with custom naming and authentication. Supports files up to 20MB and returns upload IDs for further integration.

Instructions

Upload a file to Notion using the Notion API.

Args:
    file_path: Path to the file to upload
    notion_token: Notion API token for authentication (optional if NOTION_API_TOKEN env var is set)
    file_name: Optional custom filename (defaults to original filename)
    
Returns:
    The file upload ID from Notion (use upload_and_attach_file_to_page for URL)
    
Raises:
    Exception: If file doesn't exist, exceeds size limit, or API call fails

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
notion_tokenNo
file_nameNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function for the 'upload_file_to_notion' tool. It uploads a file to Notion via their API, handling authentication, validation, and the multi-step upload process. Decorated with @mcp.tool() for automatic registration.
    @mcp.tool()
    async def upload_file_to_notion(
        file_path: str,
        notion_token: Optional[str] = None,
        file_name: Optional[str] = None
    ) -> str:
        """
        Upload a file to Notion using the Notion API.
        
        Args:
            file_path: Path to the file to upload
            notion_token: Notion API token for authentication (optional if NOTION_API_TOKEN env var is set)
            file_name: Optional custom filename (defaults to original filename)
            
        Returns:
            The file upload ID from Notion (use upload_and_attach_file_to_page for URL)
            
        Raises:
            Exception: If file doesn't exist, exceeds size limit, or API call fails
        """
        # Get token from parameter or environment variable
        token = notion_token or os.environ.get('NOTION_API_TOKEN')
        if not token:
            raise Exception("Notion API token is required. Pass it as a parameter or set NOTION_API_TOKEN environment variable")
        # Validate file exists
        file_path_obj = Path(file_path)
        if not file_path_obj.exists():
            raise Exception(f"File not found: {file_path}")
        
        # Check file size (max 20MB)
        file_size = file_path_obj.stat().st_size
        max_size = 20 * 1024 * 1024  # 20MB in bytes
        if file_size > max_size:
            raise Exception(f"File size ({file_size / 1024 / 1024:.2f}MB) exceeds 20MB limit")
        
        # Use custom filename if provided, otherwise use original
        upload_filename = file_name or file_path_obj.name
        
        # Notion API headers
        headers = {
            "Authorization": f"Bearer {token}",
            "Notion-Version": "2022-06-28"
        }
        
        async with httpx.AsyncClient() as client:
            try:
                # Step 1: Create file upload object
                create_upload_response = await client.post(
                    "https://api.notion.com/v1/file_uploads",
                    headers={**headers, "Content-Type": "application/json"},
                    json={"name": upload_filename}
                )
                create_upload_response.raise_for_status()
                
                upload_data = create_upload_response.json()
                file_upload_id = upload_data.get("id")
                upload_url = upload_data.get("upload_url")
                
                if not file_upload_id or not upload_url:
                    raise Exception("Failed to get upload ID or URL from Notion API")
                
                # Step 2: Upload file contents to the upload URL
                with open(file_path, 'rb') as f:
                    files = {"file": (upload_filename, f)}
                    upload_response = await client.post(
                        upload_url,
                        headers=headers,
                        files=files
                    )
                    upload_response.raise_for_status()
                
                # Step 3: Complete the upload and get the final file object
                complete_response = await client.get(
                    f"https://api.notion.com/v1/file_uploads/{file_upload_id}",
                    headers=headers
                )
                complete_response.raise_for_status()
                
                final_data = complete_response.json()
                
                # Return the file_upload_id instead of URL (URL is only available after attachment to page)
                return file_upload_id
                
            except httpx.HTTPStatusError as e:
                raise Exception(f"Notion API error: {e.response.status_code} - {e.response.text}")
            except Exception as e:
                raise Exception(f"Upload failed: {str(e)}")
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions authentication requirements (Notion API token with environment variable fallback), potential errors (file existence, size limits, API failures), and the return value purpose. However, it doesn't specify rate limits, timeout behavior, or what happens to existing files with the same name.

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 well-structured with clear sections (Args, Returns, Raises) and front-loaded purpose statement. While efficient, the 'Raises' section could be more concise by listing error conditions without the generic 'Exception' prefix. Every sentence adds value, but minor verbosity exists.

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

Completeness4/5

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

Given no annotations, 3 parameters with 0% schema coverage, and an output schema present, the description does a good job covering purpose, parameters, errors, and return value interpretation. However, it doesn't mention file format restrictions, size limits in concrete terms, or how the upload ID relates to Notion's internal structure, leaving some gaps for a mutation tool.

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

Parameters5/5

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

With 0% schema description coverage, the description fully compensates by explaining all three parameters: 'file_path' (path to upload), 'notion_token' (authentication with env var fallback), and 'file_name' (optional custom name with default behavior). Each parameter's purpose and constraints are clearly documented beyond what the bare schema provides.

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 ('Upload a file') and target resource ('to Notion using the Notion API'), distinguishing it from the sibling tool 'upload_and_attach_file_to_page' which appears to have a different purpose. The verb+resource combination is precise and unambiguous.

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

Usage Guidelines4/5

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

The description provides clear context about when to use this tool (uploading files to Notion) and mentions an alternative tool ('upload_and_attach_file_to_page') for obtaining URLs, but doesn't explicitly state when NOT to use this tool or compare it directly with the sibling. The guidance is helpful but not fully comprehensive regarding alternatives.

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/goonoo/mcp_notion_upload'

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