Skip to main content
Glama

docx-openFile

Open a .docx file from disk into memory for editing and management within the DOCX MCP Server, returning a file ID for subsequent operations.

Instructions

Open a .docx file from disk into memory and return id.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
idNo
pathYes

Implementation Reference

  • Main handler for 'docx-openFile' tool: validates args, parses DOCX file to JSON using helper, generates ID if needed, registers in DocRegistry, returns ID.
    case "docx-openFile": {
      const { id, path: filePath } = parseArgs<{ id?: string; path: string }>(args, tools["docx-openFile"].inputSchema);
      const json = await parseDocxFileToJson(filePath);
      const docId = id ?? nanoid();
      registry.open(docId, json);
      return ok({ id: docId });
    }
  • Input schema definition for 'docx-openFile' tool, requiring 'path' and optional 'id'.
    "docx-openFile": {
      description: "Open a .docx file from disk into memory and return id.",
      inputSchema: { type: "object", required: ["path"], properties: { id: { type: "string" }, path: { type: "string" } } }
    },
  • src/index.ts:101-103 (registration)
    Registers the listTools endpoint which exposes 'docx-openFile' via the tools object.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: Object.entries(tools).map(([name, t]) => ({ name, description: t.description, inputSchema: t.inputSchema as any }))
    }));
  • Core helper: Parses DOCX ZIP buffer to structured JSON (metadata + content blocks like paragraphs, tables). Called indirectly by handler.
    export async function parseDocxBufferToJson(buf: Uint8Array): Promise<DocxJSON> {
      const zip = await JSZip.loadAsync(buf as any);
    
      // Parse core properties
      const coreXml = await zip.file("docProps/core.xml")?.async("string");
      const appXml = await zip.file("docProps/app.xml")?.async("string");
      const meta: DocxJSON["meta"] = {};
      if (coreXml) {
        const core = await parseStringPromise(coreXml);
        const c = core["cp:coreProperties"] || {};
        meta.title = textOf(c["dc:title"]?.[0]);
        meta.subject = textOf(c["dc:subject"]?.[0]);
        meta.creator = textOf(c["dc:creator"]?.[0]);
        meta.description = textOf(c["dc:description"]?.[0]);
        meta.keywords = textOf(c["cp:keywords"]?.[0]);
        meta.lastModifiedBy = textOf(c["cp:lastModifiedBy"]?.[0]);
        meta.category = textOf(c["cp:category"]?.[0]);
        const created = textOf(c["dcterms:created"]?.[0]);
        const modified = textOf(c["dcterms:modified"]?.[0]);
        if (created) meta.createdAt = created;
        if (modified) meta.modifiedAt = modified;
      }
      if (appXml) {
        // company/manager sometimes in app.xml (not always)
        const app = await parseStringPromise(appXml);
        const a = app.Properties || {};
        meta.company = textOf(a.Company?.[0]);
        meta.manager = textOf(a.Manager?.[0]);
      }
    
      // Parse document.xml to extract paragraphs/tables at a basic level
      const docXml = await zip.file("word/document.xml")?.async("string");
      const content: any[] = [];
      if (docXml) {
        const doc = await parseStringPromise(docXml);
        const body = doc["w:document"]?.["w:body"]?.[0];
        const children: any[] = body ? Object.values(body).flat() as any[] : [];
        // xml2js gives arrays keyed by tags; iterate in original order via a custom approach
        // Fallback: manually scan body._children is not available, so we reconstruct by looking at known sequences
        const seq = [] as any[];
        for (const key of Object.keys(body || {})) {
          const arr = (body as any)[key];
          if (Array.isArray(arr)) {
            for (const item of arr) seq.push({ tag: key, node: item });
          }
        }
        for (const item of seq) {
          if (item.tag === "w:p") {
            const p = item.node;
            const pPr = p["w:pPr"]?.[0];
            let headingLevel: number | undefined;
            const styleVal = pPr?.["w:pStyle"]?.[0]?.["$"]?.["w:val"];
            if (typeof styleVal === "string") {
              const m = /Heading([1-6])/.exec(styleVal);
              if (m) headingLevel = parseInt(m[1], 10);
            }
            const runs = [] as any[];
            for (const r of p["w:r"] || []) {
              const t = textOf(r["w:t"]?.[0]);
              if (t) {
                const rPr = r["w:rPr"]?.[0] || {};
                runs.push({
                  type: "text",
                  text: t,
                  bold: rPr["w:b"] ? true : undefined,
                  italics: rPr["w:i"] ? true : undefined,
                  underline: rPr["w:u"] ? true : undefined,
                });
              }
            }
            content.push(headingLevel ? { type: "heading", level: headingLevel, children: runs } : { type: "paragraph", children: runs });
          } else if (item.tag === "w:tbl") {
            const tbl = item.node;
            const rows = [] as any[];
            for (const tr of tbl["w:tr"] || []) {
              const cells = [] as any[];
              for (const tc of tr["w:tc"] || []) {
                const paras = [] as any[];
                for (const p of tc["w:p"] || []) {
                  const runs = [] as any[];
                  for (const r of p["w:r"] || []) {
                    const t = textOf(r["w:t"]?.[0]);
                    if (t) runs.push({ type: "text", text: t });
                  }
                  paras.push({ type: "paragraph", children: runs });
                }
                cells.push({ children: paras });
              }
              rows.push({ cells });
            }
            content.push({ type: "table", rows });
          }
        }
      }
    
      const json: DocxJSON = { meta, content };
      return json;
    }
  • DocRegistry.open: Registers the parsed JSON as a managed document by calling create.
    open(id: DocId, json: DocxJSON): ManagedDoc {
      // open means register from existing JSON (e.g., load from disk by caller)
      return this.create(id, json);
    }
Behavior2/5

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

With no annotations, the description carries the full burden of behavioral disclosure. It states the tool opens a file and returns an id, but doesn't cover critical aspects like error handling (e.g., if the file doesn't exist), memory implications, or whether the operation is read-only or modifies the file. This leaves significant gaps for agent understanding.

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 that directly states the tool's purpose without unnecessary words. It is front-loaded and appropriately sized for its simple function, with no wasted verbiage.

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 moderate complexity (file I/O operation), lack of annotations, no output schema, and low parameter coverage, the description is incomplete. It doesn't address behavioral traits, parameter details, or return value implications, making it inadequate for reliable agent 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 for its 2 parameters (id and path), and the description adds no information about them. It doesn't explain what 'path' should contain (e.g., file path format) or what 'id' is used for, failing to compensate for the low schema coverage.

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 action ('Open a .docx file from disk into memory') and the outcome ('return id'), distinguishing it from siblings like docx-create or docx-save. However, it doesn't explicitly differentiate from docx-open (a similar-named sibling), which slightly reduces clarity.

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 like docx-open or docx-create, nor does it mention prerequisites such as file existence or permissions. It implies usage for opening files but lacks context about alternatives 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/lihongjie0209/docx-mcp'

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