list_merge_fields
Extract merge field names from Word documents to identify template variables for data integration and document automation workflows.
Instructions
Extract all MERGEFIELD names from a document or template.
Args: filepath: Path to the document
Returns: Dictionary with list of merge field names
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filepath | Yes |
Implementation Reference
- src/docx_mcp/server.py:348-390 (handler)The `list_merge_fields` tool implementation which uses `safe_open_document` to load the document and parses the XML structure to find `MERGEFIELD` field codes.
@app.tool() def list_merge_fields(filepath: str) -> dict[str, Any]: """ Extract all MERGEFIELD names from a document or template. Args: filepath: Path to the document Returns: Dictionary with list of merge field names """ logger.info("Listing merge fields", extra={"tool": "list_merge_fields", "filepath": filepath}) try: doc = safe_open_document(filepath) merge_fields = set() # Search for MERGEFIELD fields in document for paragraph in doc.paragraphs: for run in paragraph.runs: # Look for field codes if run.element.xpath(".//w:instrText"): for instr in run.element.xpath(".//w:instrText"): text = instr.text or "" if "MERGEFIELD" in text: # Extract field name parts = text.split() if len(parts) > 1: merge_fields.add(parts[1]) return { "status": "success", "filepath": filepath, "merge_fields": list(sorted(merge_fields)), "count": len(merge_fields), } except DocxMcpError as e: logger.warning(e.message, extra={"tool": "list_merge_fields", "error_code": e.error_code}) return {"status": "error", "error": e.message, "error_code": e.error_code} except Exception as e: logger.error(f"Unexpected error listing merge fields: {str(e)}") return {"status": "error", "error": str(e)}