Skip to main content
Glama
zhiwei5576

Excel MCP Server

by zhiwei5576

analyzeExcelStructure

Read an Excel file to extract sheet names and column headers, outputting them as JSON. Specify the file path and optional header row count.

Instructions

Get Excel file structure including sheet list and column headers in JSON format

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileAbsolutePathYesThe absolute path of the Excel file
headerRowsNoNumber of header rows to read (default: 1)

Implementation Reference

  • Core handler function that reads an Excel file, builds a structure with sheet list and per-column header fields. Uses workbookCache to get the workbook, iterates over sheets, and extracts header rows (configurable count) per column.
    export async function analyzeExcelStructure(
        filePathWithName: string,
        headerRows: number = 1
    ): Promise<ExcelStructure> {
        try {
            const workbookResult: EnsureWorkbookResult = workbookCache.ensureWorkbook(filePathWithName);
            let workbook: XLSX.WorkBook;
    
            if (!workbookResult.success) {
                const readResult = await readAndCacheFile(filePathWithName);
                if (!readResult.success) {
                    throw new Error(`Failed to read file: ${readResult.data.errors}`);
                }
                workbook = workbookCache.get(filePathWithName)!;
            } else {
                workbook = workbookResult.data as XLSX.WorkBook;
            }
    
            const result: ExcelStructure = {
                sheetList: [],
                sheetField: []
            };
    
            result.sheetList = workbook.SheetNames.map((sheetName, index) => ({
                SheetNo: index + 1,  // 添加从1开始的序号
                SheetName: sheetName
            }));
            // 遍历所有工作表
            for (const sheetName of workbook.SheetNames) {
                const worksheet = workbook.Sheets[sheetName];
                
                // 获取原始数据
                const rawData = XLSX.utils.sheet_to_json(worksheet, {
                    raw: true,
                    defval: '',
                    header: 1
                });
    
                if (rawData.length === 0) {
                    continue;
                }
                // 获取每列的数据
                const columnCount = (rawData[0] as any[]).length;
                for (let colIndex = 0; colIndex < columnCount; colIndex++) {
                    const fieldInfo: any = {
                        SheetName: sheetName
                    };
    
                    // 根据 headerRows 获取指定数量的表头行
                    for (let i = 1; i <= headerRows; i++) {
                        const headerIndex = i - 1;
                        if (rawData.length > headerIndex) {
                            const rowData = rawData[headerIndex] as any[];
                            fieldInfo[`Field${i}`] = rowData[colIndex] || '';
                        } else {
                            fieldInfo[`Field${i}`] = '';
                        }
                    }
    
                    result.sheetField = result.sheetField || [];
                    result.sheetField.push(fieldInfo);
                }
            }
    
            return  result
            // {
            //     // 修改 sheetList 的映射,添加 SheetNo
            //     sheetList: workbook.SheetNames.map((sheetName, index) => ({ 
            //         SheetNo: index + 1,  // 添加从1开始的序号
            //         SheetName: sheetName 
            //     })),
            //     sheetField: result.sheetField || []
            // };
    
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            throw new Error(`Failed to get Excel structure: ${errorMessage}`);
        }
    }
  • Type definition for ExcelStructure, the return type of analyzeExcelStructure. Contains sheetList (array of {SheetNo, SheetName}) and sheetField (array of {SheetName, Field1...FieldN}).
    export interface ExcelStructure {
        sheetList: Array<{
            SheetNo: number;
            SheetName: string;
        }>;
        sheetField: Array<{
            SheetName: string;
            [key: `Field${number}`]: string;
        }>;
    }
  • Registration of the 'analyzeExcelStructure' tool on the MCP server. Defines the Zod schema for parameters (fileAbsolutePath, headerRows) and the handler callback that normalizes path, checks file existence, calls the handler, and returns JSON result.
    import { z } from "zod";
    import { fileExists, normalizePath } from "../utils/utils.js";
    import { analyzeExcelStructure, exportExcelStructure } from '../handlers/excelHandlers.js'
    
    export const structureTools = (server: any) => {
        server.tool("analyzeExcelStructure", 'Get Excel file structure including sheet list and column headers in JSON format',
            {
                fileAbsolutePath: z.string().describe("The absolute path of the Excel file"),
                headerRows: z.number().default(1).describe("Number of header rows to read (default: 1)")
            },
            async (params: {
                fileAbsolutePath: string;
                headerRows: number;
            }) => {
                try {
                    const normalizedPath = await normalizePath(params.fileAbsolutePath);
                    if (normalizedPath === 'error') {
                        return {
                            content: [{
                                type: "text",
                                text: JSON.stringify({
                                    error: `Invalid file path: ${params.fileAbsolutePath}`,
                                    suggestion: "Please verify the file path and name"
                                })
                            }]
                        };
                    }
    
                    if (!(await fileExists(normalizedPath))) {
                        return {
                            content: [{
                                type: "text",
                                text: JSON.stringify({
                                    error: `File not found: ${params.fileAbsolutePath}`,
                                    suggestion: "Please verify the file path and name"
                                })
                            }]
                        };
                    }
    
                    const result = await analyzeExcelStructure(normalizedPath, params.headerRows);
    
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify(result)
                        }]
                    };
    
                } catch (error) {
                    return {
                        content: [{
                            type: "text",
                            text: JSON.stringify({
                                error: `Failed to get Excel structure: ${error}`,
                                suggestion: "Please verify all parameters"
                            })
                        }]
                    };
                }
            }
        );
  • Compiled JS version of the registration (same logic as src/tools/structureTools.ts).
    import { z } from "zod";
    import { fileExists, normalizePath } from "../utils/utils.js";
    import { analyzeExcelStructure, exportExcelStructure } from '../handlers/excelHandlers.js';
    export const structureTools = (server) => {
        server.tool("analyzeExcelStructure", 'Get Excel file structure including sheet list and column headers in JSON format', {
            fileAbsolutePath: z.string().describe("The absolute path of the Excel file"),
            headerRows: z.number().default(1).describe("Number of header rows to read (default: 1)")
        }, async (params) => {
            try {
                const normalizedPath = await normalizePath(params.fileAbsolutePath);
Behavior3/5

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

With no annotations, the description is the sole source of behavioral information. It states the output format (JSON) but does not disclose limitations such as file size, hidden sheet handling, or whether the file must be closed. It is adequate but not thorough for a read-only tool.

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 sentence with no superfluous words. It conveys the essential information efficiently.

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?

For a simple tool with complete schema coverage and no output schema, the description is adequate but lacks detail on file format support, hidden sheets, and the exact shape of the returned JSON. It meets minimal requirements but could be more comprehensive.

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 coverage is 100%, so both parameters already have descriptions. The tool description adds no additional meaning beyond what the schema provides, such as clarifying the purpose of headerRows in relation to structure extraction. Context signals indicate 100% schema description coverage, baseline is 3.

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 tool gets the Excel file structure including sheet list and column headers in JSON format. It uses specific verbs and resource, and distinguishes from sibling tools like readSheetData or readSheetNames which focus on data retrieval rather than structure.

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 such as exportExcelStructure or readSheetData. There is no mention of prerequisites, context, or exclusions.

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/zhiwei5576/excel-mcp-server'

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