Skip to main content
Glama

replace_hwp_text

Find and replace specified text in HWPX files. Provide file path, old text, new text, and optional output path.

Instructions

Find and replace text in an HWPX file. v0.2: only .hwpx is supported as input/output. Args: file_path, old_text, new_text, output_path (optional).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
old_textYes
new_textYes
output_pathNo

Implementation Reference

  • Main handler function for replace_hwp_text tool. Validates input file existence, format compatibility, rejects .hwp files (v0.2 limitation), then delegates to mutateHwpxText() for the actual replacement logic.
    export async function replaceHwpText(args: ReplaceTextArgs): Promise<string> {
      if (!existsSync(args.file_path)) {
        return `파일을 찾을 수 없습니다 (file not found): ${args.file_path}`;
      }
      let inFmt;
      try {
        inFmt = getFormatFromPath(args.file_path);
      } catch (e) {
        return (e as Error).message;
      }
      const outputPath =
        args.output_path && args.output_path.length > 0
          ? args.output_path
          : defaultOutputPath(args.file_path, "modified");
      try {
        ensureSameFormat(args.file_path, outputPath);
      } catch (e) {
        return (e as Error).message;
      }
      const reject = rejectIfHwp(args.file_path);
      if (reject) return reject;
    
      // .hwpx path — direct mutation, no rhwp export needed.
      try {
        const r = await mutateHwpxText(args.file_path, outputPath, {
          [args.old_text]: args.new_text,
        });
        return `'${args.old_text}' → '${args.new_text}': ${r.total}건 교체 (replaced ${r.total})\n저장 (saved): ${outputPath}`;
      } catch (e) {
        return `텍스트 교체 오류 (replace error): ${(e as Error).message}`;
      }
    }
  • TypeScript interface defining input arguments: file_path, old_text, new_text (required), and output_path (optional).
    export interface ReplaceTextArgs {
      file_path: string;
      old_text: string;
      new_text: string;
      output_path?: string;
    }
  • Core mutation engine that reads a .hwpx ZIP, performs text replacement inside <hp:t> XML text nodes across section*.xml and header.xml, then writes the modified .hwpx back to disk. Only replaces within text nodes to avoid corrupting XML structure.
    export async function mutateHwpxText(
      inputPath: string,
      outputPath: string,
      replacements: Record<string, string>
    ): Promise<MutationResult> {
      const bytes = await readFile(inputPath);
      const zip = await JSZip.loadAsync(bytes);
    
      const counts: Record<string, number> = {};
      let total = 0;
    
      // Mutate every XML carrying body content: section*.xml, header.xml (HF blocks),
      // and master pages. mimetype/content.hpf are excluded.
      const sectionFiles = Object.keys(zip.files).filter((n) =>
        /^Contents\/(section\d+|header)\.xml$/i.test(n)
      );
    
      for (const fname of sectionFiles) {
        const file = zip.files[fname];
        let xml = await file.async("string");
        for (const [key, value] of Object.entries(replacements)) {
          const escapedXml = xmlEscape(value);
          // Only replace inside <hp:t>...</hp:t> text nodes, to avoid touching
          // tag names or attribute values.
          const pattern = new RegExp(
            "(<hp:t(?:\\s[^>]*)?>)([^<]*)(" +
              escapeRegex(key) +
              ")([^<]*)(</hp:t>)",
            "g"
          );
          let didReplace = true;
          while (didReplace) {
            didReplace = false;
            xml = xml.replace(pattern, (_match, open, pre, _hit, post, close) => {
              counts[key] = (counts[key] ?? 0) + 1;
              total += 1;
              didReplace = true;
              return open + pre + escapedXml + post + close;
            });
            // Loop because a single node may contain multiple occurrences;
            // String.replace with /g consumes from current position, so one pass
            // catches all non-overlapping. Set didReplace=false after one pass.
            break;
          }
        }
        zip.file(fname, xml);
      }
    
      // mimetype must remain stored (uncompressed); JSZip preserves per-file
      // compression options if we re-set them.
      if (zip.files["mimetype"]) {
        const mt = await zip.files["mimetype"].async("string");
        zip.file("mimetype", mt, { compression: "STORE" });
      }
    
      const out = await zip.generateAsync({
        type: "uint8array",
        compression: "DEFLATE",
        compressionOptions: { level: 6 },
      });
      await writeFile(outputPath, out);
    
      for (const k of Object.keys(replacements)) {
        if (counts[k] === undefined) counts[k] = 0;
      }
      return { total, perKey: counts };
    }
  • src/server.ts:92-106 (registration)
    Tool registration in the TOOLS array with name 'replace_hwp_text', description, and JSON Schema input definition listing file_path, old_text, new_text as required and output_path as optional.
    {
      name: "replace_hwp_text",
      description:
        "Find and replace text in an HWPX file. v0.2: only .hwpx is supported as input/output. Args: file_path, old_text, new_text, output_path (optional).",
      inputSchema: {
        type: "object",
        properties: {
          file_path: { type: "string" },
          old_text: { type: "string" },
          new_text: { type: "string" },
          output_path: { type: "string" },
        },
        required: ["file_path", "old_text", "new_text"],
      },
    },
  • src/server.ts:515-515 (registration)
    Handler mapping in the HANDLERS record that associates the 'replace_hwp_text' tool name string with the replaceHwpText function imported from write.ts.
    replace_hwp_text: replaceHwpText,
Behavior2/5

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

No annotations are provided, so the description must cover behavioral traits. It states the action but does not disclose whether the original file is modified when output_path is omitted, whether replacement is global or first occurrence, or any side effects. This is a significant gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is brief (two sentences) and front-loads the main purpose. The version and argument list are included without excessive detail. It is concise, though the argument listing could be more structured (e.g., using bullet points).

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 (4 parameters, no output schema), the description lacks crucial context: return value, replacement scope, overwrite behavior, encoding, error handling, and intended use with sibling tools. It is incomplete for an agent to fully understand the tool's behavior.

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?

With 0% schema description coverage, the description must add meaning. It lists the four parameters but provides no additional explanation (e.g., file_path semantics, old_text format, output_path behavior). The names are somewhat self-explanatory, but the description fails to add value beyond the schema.

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 performs find-and-replace in HWPX files. The verb 'find and replace' and resource 'text in an HWPX file' are specific. However, it does not explicitly differentiate from siblings like set_hwp_paragraph_text, but the distinct verb helps.

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 mentions that only .hwpx format is supported, which is a usage constraint. However, it provides no guidance on when to use this tool versus siblings like set_hwp_cell_text or apply_hwp_text_style, nor does it describe prerequisites or conditional usage.

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/treesoop/hwp-mcp'

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