Skip to main content
Glama
kmexnx

Excel to PDF Converter

by kmexnx

convert_excel_to_pdf

Convert Excel files (.xls, .xlsx) to PDF format for sharing, printing, or archiving documents while preserving formatting.

Instructions

Converts Excel files (.xls, .xlsx) to PDF format

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
input_pathYesRelative path to the Excel file (.xls, .xlsx) to convert
output_formatNoOutput format (currently only PDF is supported)pdf

Implementation Reference

  • Core handler function that validates input, checks for LibreOffice, reads Excel file, converts to PDF using libreoffice-convert, saves to temp file, and returns the relative path.
    export const handleConvertExcelFunc = async (
      args: unknown
    ): Promise<{ content: { type: string; text: string }[] }> => {
      // Ensure LibreOffice is installed
      const libreOfficeInstalled = await checkLibreOfficeInstalled();
      if (!libreOfficeInstalled) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'LibreOffice is not installed or not found in PATH. Please install LibreOffice to use this tool.'
        );
      }
    
      // Parse and validate arguments
      let parsedArgs: ConvertExcelArgs;
      try {
        parsedArgs = ConvertExcelArgsSchema.parse(args);
      } catch (error) {
        if (error instanceof z.ZodError) {
          throw new McpError(
            ErrorCode.InvalidParams,
            `Invalid arguments: ${error.errors.map(e => `${e.path.join('.')} (${e.message})`).join(', ')}`
          );
        }
        const message = error instanceof Error ? error.message : String(error);
        throw new McpError(ErrorCode.InvalidParams, `Argument validation failed: ${message}`);
      }
    
      try {
        // Ensure temp directory exists - now await because the function is async
        const tempDir = await ensureTempDir();
        
        // Resolve input path
        const inputPath = resolvePath(parsedArgs.input_path);
        
        // Check file extension
        const ext = path.extname(inputPath).toLowerCase();
        if (ext !== '.xlsx' && ext !== '.xls') {
          throw new McpError(
            ErrorCode.InvalidParams,
            'Invalid file format. Only .xlsx and .xls files are supported.'
          );
        }
        
        // Read the input file
        const fileContent = await fs.readFile(inputPath);
        
        // Create output path
        const outputPath = createTempFilePath(path.basename(inputPath));
        await fs.mkdir(path.dirname(outputPath), { recursive: true });
        
        // Convert to PDF
        const pdfBuffer = await libreConvert(fileContent, '.pdf', undefined);
        
        // Write the output file
        await fs.writeFile(outputPath, pdfBuffer);
        
        // Create a relative path for the result
        const relativeOutputPath = path.relative(process.cwd(), outputPath);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                success: true,
                output_path: relativeOutputPath,
                message: 'Excel file successfully converted to PDF',
              }, null, 2),
            },
          ],
        };
      } catch (error) {
        console.error('[Excel to PDF MCP] Error in conversion:', error);
        
        // Handle specific errors
        if (error instanceof McpError) {
          throw error; // Re-throw MCP errors
        }
        
        if (error instanceof Error) {
          if ('code' in error && error.code === 'ENOENT') {
            throw new McpError(ErrorCode.InvalidParams, `File not found: ${parsedArgs.input_path}`);
          }
          
          throw new McpError(
            ErrorCode.InvalidRequest,
            `Error converting Excel to PDF: ${error.message}`
          );
        }
        
        // Generic error
        throw new McpError(
          ErrorCode.InvalidRequest,
          `Unknown error during Excel to PDF conversion`
        );
      }
    };
  • Zod schema for tool input parameters: input_path (string) and output_format (pdf).
    const ConvertExcelArgsSchema = z.object({
      input_path: z.string().min(1).describe('Relative path to the Excel file (.xls, .xlsx) to convert'),
      output_format: z.enum(['pdf']).default('pdf').describe('Output format (currently only PDF is supported)')
    }).strict();
  • ToolDefinition object that registers the tool with name, description, schema, and handler function.
    export const convertExcelToolDefinition: ToolDefinition = {
      name: 'convert_excel_to_pdf',
      description: 'Converts Excel files (.xls, .xlsx) to PDF format',
      schema: ConvertExcelArgsSchema,
      handler: handleConvertExcelFunc,
    };
  • Aggregation of all tool definitions into an array used by the MCP server.
    export const allToolDefinitions: ToolDefinition[] = [
      convertExcelToolDefinition,
      convertNumbersToolDefinition
    ];
  • Helper function to verify LibreOffice installation before attempting conversion.
    export async function checkLibreOfficeInstalled(): Promise<boolean> {
      try {
        const isWindows = process.platform === 'win32';
        const command = isWindows ? 'where' : 'which';
        const possibleCommands = isWindows ? ['soffice.exe'] : ['libreoffice', 'soffice'];
        
        const { exec } = await import('node:child_process');
        const execPromise = promisify(exec);
        
        // Try with multiple possible command names
        for (const commandArg of possibleCommands) {
          try {
            await execPromise(`${command} ${commandArg}`);
            console.error(`[Excel to PDF MCP] Found LibreOffice at: ${commandArg}`);
            return true;
          } catch {
            // Continue with next command
          }
        }
        
        console.error('[Excel to PDF MCP] LibreOffice not found in PATH');
        return false;
      } catch (error) {
        console.error('[Excel to PDF MCP] Error checking for LibreOffice:', error);
        return false;
      }
    }
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 conversion action but lacks details on permissions, side effects, rate limits, or output handling. For a file conversion tool with zero annotation coverage, this is a significant gap in transparency, as it doesn't describe what happens during or after conversion.

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 appropriately sized and front-loaded, directly stating the tool's purpose without unnecessary elaboration, making it easy for an agent to parse 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 file conversion (which may involve permissions, errors, or format constraints), no annotations, and no output schema, the description is incomplete. It doesn't address potential behavioral aspects or output details, leaving gaps that could hinder correct tool invocation by an AI agent.

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%, so the input schema fully documents both parameters (input_path and output_format). The description adds no additional parameter semantics beyond what's in the schema, such as format details or usage examples. Baseline 3 is appropriate when the schema does the heavy lifting.

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 tool's purpose: converting Excel files to PDF format, specifying the supported input file types (.xls, .xlsx). It uses a specific verb ('Converts') and identifies the resource (Excel files). However, it doesn't explicitly differentiate from the sibling tool 'convert_numbers_to_pdf' beyond the file format mention, which might imply differentiation but isn't explicit.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention the sibling tool 'convert_numbers_to_pdf' or any other conversion tools, nor does it specify prerequisites, contexts, or exclusions for usage. This leaves the agent without clear direction on tool selection.

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/kmexnx/excel-to-pdf-mcp'

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