Skip to main content
Glama
b3nw
by b3nw

Upload Files to Input Element

browser_file_upload

Upload files to web page file input elements using selectors for automated testing and form submission.

Instructions

Upload files to file input elements on the page

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
selectorYes
pathsYes

Implementation Reference

  • The core handler function that parses input, validates the file input element and file paths, then uses Playwright's page.locator().setInputFiles() to upload the files.
    async (params: any) => {
      try {
        const input = z.object({
          selector: z.string(),
          paths: z.array(z.string()).min(1)
        }).parse(params);
        await this.playwright.ensureConnected();
        
        const page = this.playwright.getPage();
        
        // Validate that the element exists and is a file input
        const element = page.locator(input.selector);
        const elementType = await element.getAttribute('type');
        
        if (elementType !== 'file') {
          throw new Error('Target element is not a file input (type="file")');
        }
        
        // Validate that files exist (for absolute paths)
        const fs = await import('fs');
        const path = await import('path');
        
        const validatedPaths = [];
        for (const filePath of input.paths) {
          try {
            // Convert relative paths to absolute paths
            const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
            
            // Check if file exists
            if (!fs.existsSync(absolutePath)) {
              throw new Error(`File not found: ${filePath}`);
            }
            
            // Check if it's actually a file (not directory)
            const stats = fs.statSync(absolutePath);
            if (!stats.isFile()) {
              throw new Error(`Path is not a file: ${filePath}`);
            }
            
            validatedPaths.push(absolutePath);
          } catch (fileError) {
            throw new Error(`File validation failed for ${filePath}: ${fileError instanceof Error ? fileError.message : String(fileError)}`);
          }
        }
        
        // Upload the files
        await element.setInputFiles(validatedPaths);
        
        return {
          content: [{
            type: 'text',
            text: `Successfully uploaded ${validatedPaths.length} file(s) to element: ${input.selector}`
          }]
        };
      } catch (error) {
        return {
          content: [{
            type: 'text',
            text: `File upload failed: ${error instanceof Error ? error.message : String(error)}`
          }],
          isError: true
        };
      }
    }
  • src/server.ts:481-491 (registration)
    Registers the 'browser_file_upload' tool with the MCP server, providing title, description, and inline input schema. The handler function follows immediately.
    // Browser file upload tool
    this.server.registerTool(
      'browser_file_upload',
      {
        title: 'Upload Files to Input Element',
        description: 'Upload files to file input elements on the page',
        inputSchema: {
          selector: z.string(),
          paths: z.array(z.string()).min(1)
        }
      },
  • Zod schema defining the input structure for the browser_file_upload tool: selector (string) and paths (array of strings, min 1).
    export const BrowserFileUploadInputSchema = z.object({
      selector: z.string(),
      paths: z.array(z.string()).min(1)
    });
  • TypeScript type inferred from the BrowserFileUploadInputSchema for type safety.
    export type BrowserFileUploadInput = z.infer<typeof BrowserFileUploadInputSchema>;
Behavior2/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 states the action ('upload files') but lacks critical details: whether this requires specific page states, if it waits for elements to be visible, what happens on failure, or if it triggers page changes. For a browser interaction tool with zero annotation coverage, this is insufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero waste. It's front-loaded with the core action and resource, making it easy to scan and understand quickly.

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 complexity of browser file uploads (interacting with UI elements, handling local files), no annotations, no output schema, and poor parameter documentation, the description is incomplete. It should address prerequisites, error handling, or behavioral nuances to be adequate for safe use.

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

Parameters2/5

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

The schema has 0% description coverage, so parameters 'selector' and 'paths' are undocumented in the schema. The description adds no meaning beyond the tool name—it doesn't explain what 'selector' refers to (e.g., CSS selector for file input) or that 'paths' are local file paths. This fails to compensate for the schema gap.

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 ('upload') and resource ('files to file input elements on the page'), making the purpose immediately understandable. It doesn't explicitly differentiate from sibling tools like browser_type or browser_click, but the specificity of 'file input elements' provides some implicit distinction.

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

Usage Guidelines2/5

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

No guidance is provided on when to use this tool versus alternatives. The description doesn't mention prerequisites (e.g., needing a page loaded with file input elements), exclusions, or comparisons to sibling tools like browser_type for text input or browser_click for general interactions.

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/b3nw/playwright-mcp-server'

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