Skip to main content
Glama

xpath

Query and extract specific data from XML content using XPath syntax. Input XML and the XPath query to retrieve targeted information efficiently.

Instructions

Select query XML content using XPath

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
mimeTypeNoThe MIME type (e.g. text/xml, application/xml, text/html, application/xhtml+xml)text/html
queryYesThe XPath query to execute
xmlYesThe XML content to query

Implementation Reference

  • Handler logic for the 'xpath' tool: validates arguments with Zod schema, parses XML content, checks for parsing errors, executes XPath query using xpath.select, handles empty results and errors, and returns formatted text content.
    if (name === "xpath") {
        const { xml, query, mimeType } = XPathArgumentsSchema.parse(args);
    
        try {
            // Parse XML
            const firstOpeningTag = xml.indexOf("<");
            const lastClosingTag = xml.lastIndexOf(">");
            const sanitizedXml = xml.substring(firstOpeningTag, lastClosingTag + 1);
            const parsedXml = parser.parseFromString(sanitizedXml, mimeType);
            
            // Check for parsing errors
            const errors = xpath.select('//parsererror', parsedXml);
            if (Array.isArray(errors) && errors.length > 0) {
                return {
                    content: [{ type: "text", text: "XML parsing error: " + resultToString(errors[0]) }]
                };
            }
            
            const result = xpath.select(query, parsedXml);
            
            // If result is an empty array, provide more information
            if (Array.isArray(result) && result.length === 0) {
                return {
                    content: [{ type: "text", text: "No nodes matched the query." }]
                };
            }
            
            return {
                content: [{ type: "text", text: resultToString(result) }]
            };
        } catch (error: unknown) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            return {
                content: [{ type: "text", text: `Error processing XPath query: ${errorMessage}` }]
            };
        }
  • index.ts:78-99 (registration)
    Registration of the 'xpath' tool in the listTools response, including name, description, and JSON input schema.
        name: "xpath",
        description: "Select query XML content using XPath",
        inputSchema: {
            type: "object",
            properties: {
                xml: {
                    type: "string",
                    description: "The XML content to query",
                },
                query: {
                    type: "string",
                    description: "The XPath query to execute",
                },
                mimeType: {
                    type: "string",
                    description: "The MIME type (e.g. text/xml, application/xml, text/html, application/xhtml+xml)",
                    default: "text/html"
                }
            },
            required: ["xml", "query"],
        },
    },
  • Zod schema used for runtime validation of 'xpath' tool arguments in the handler.
    const XPathArgumentsSchema = z.object({
        xml: z.string().describe("The XML content to query"),
        query: z.string().describe("The XPath query to execute"),
        mimeType: z.string()
        .describe("The MIME type (e.g. text/xml, application/xml, text/html, application/xhtml+xml)")
        .default("text/html")
    });
  • Helper function to convert XPath selection results (nodes, arrays, primitives) to a string representation for the tool output.
    function resultToString(result: string | number | boolean | Node | Node[] | null): string {
        if (result === null) {
            return "null";
        } else if (Array.isArray(result)) {
            return result.map(resultToString).join("\n");
        } else if (typeof result === 'object' && result.nodeType !== undefined) {
            // Handle DOM nodes
            if (result.nodeType === 1) { // Element node
                const serializer = new XMLSerializer();
                return serializer.serializeToString(result);
            } else if (result.nodeType === 2) { // Attribute node
                return `${result.nodeName}="${result.nodeValue}"`;
            } else if (result.nodeType === 3) { // Text node
                return result.nodeValue || "";
            } else {
                // Default fallback for other node types
                try {
                    const serializer = new XMLSerializer();
                    return serializer.serializeToString(result);
                } catch (e) {
                    return String(result);
                }
            }
        } else {
            return String(result);
        }
    }
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 action ('Select query') but doesn't describe what the tool returns (e.g., nodes, values, errors), performance characteristics, or any constraints like input size limits. This leaves significant gaps in understanding the tool's behavior beyond basic functionality.

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: 'Select query XML content using XPath'. It's front-loaded with the core purpose, has zero waste, and is appropriately sized for a straightforward tool. Every word earns its place.

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 tool's complexity (XML querying with XPath), no annotations, and no output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., extracted data, error handling), which is critical for an agent to use it correctly. The description should compensate for the lack of structured output information but fails to do so.

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 schema already documents all parameters (xml, query, mimeType) with clear descriptions. The description adds no additional meaning beyond what the schema provides, such as examples or usage notes for parameters. Baseline 3 is appropriate as 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: 'Select query XML content using XPath'. It specifies the verb ('Select query') and resource ('XML content'), though it doesn't explicitly distinguish it from its sibling 'xpathwithurl', which likely handles URLs instead of direct XML input. The purpose is clear but lacks sibling differentiation.

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 'xpathwithurl' or any other tools, nor does it specify prerequisites or exclusions. Usage is implied from the purpose but lacks explicit context or 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

Related 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/thirdstrandstudio/mcp-xpath'

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