Skip to main content
Glama

replace_hwp_image

Replace an embedded image inside a .hwpx file by overwriting its BinData/ ZIP entry with a new image file. Specify the target image by basename or full path.

Instructions

Replace an embedded image inside an .hwpx by overwriting its BinData/ ZIP entry with new file contents. target accepts either basename ('image1.bmp') or full entry path ('BinData/image1.bmp'). Args: file_path, target, source_path, output_path (optional).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
targetYes
source_pathYes
output_pathNo

Implementation Reference

  • Main handler function for replace_hwp_image tool. Validates inputs (file existence, .hwpx format), calls replaceHwpxImages from the core module, and returns a user-facing result message.
    export async function replaceHwpImage(args: ReplaceImageArgs): Promise<string> {
      if (!existsSync(args.file_path)) {
        return `파일을 찾을 수 없습니다 (file not found): ${args.file_path}`;
      }
      if (!existsSync(args.source_path)) {
        return `대체 이미지 파일을 찾을 수 없습니다 (replacement file not found): ${args.source_path}`;
      }
      let fmt;
      try {
        fmt = getFormatFromPath(args.file_path);
      } catch (e) {
        return (e as Error).message;
      }
      if (fmt !== "hwpx") {
        return "v0.2은 .hwpx 이미지 교체만 지원합니다 (image replace supports .hwpx only in v0.2).";
      }
      const outputPath =
        args.output_path && args.output_path.length > 0
          ? args.output_path
          : defaultOutputPath(args.file_path, "img");
      try {
        const r = await replaceHwpxImages(args.file_path, outputPath, {
          [args.target]: args.source_path,
        });
        if (r.total === 0) {
          const entries = await listHwpxBinDataEntries(args.file_path);
          return [
            `대상 이미지를 찾지 못했습니다 (target not found): ${args.target}`,
            `사용 가능한 BinData 엔트리:`,
            ...entries.map((e) => `  - ${e}`),
          ].join("\n");
        }
        const rep = r.replaced[0];
        return `이미지 교체 완료 (replaced): ${rep.entry} ← ${rep.from} (${rep.bytes} bytes)\n저장 (saved): ${outputPath}`;
      } catch (e) {
        return `이미지 교체 오류 (image replace error): ${(e as Error).message}`;
      }
    }
  • ReplaceImageArgs interface defining input schema: file_path (target .hwpx), target (BinData entry name), source_path (replacement file), and optional output_path.
    export interface ReplaceImageArgs {
      file_path: string;
      target: string;
      source_path: string;
      output_path?: string;
    }
  • src/server.ts:175-188 (registration)
    Tool registration entry in the TOOLS array: defines name 'replace_hwp_image', description, and inputSchema with required properties (file_path, target, source_path) and optional output_path.
      name: "replace_hwp_image",
      description:
        "Replace an embedded image inside an .hwpx by overwriting its BinData/ ZIP entry with new file contents. `target` accepts either basename ('image1.bmp') or full entry path ('BinData/image1.bmp'). Args: file_path, target, source_path, output_path (optional).",
      inputSchema: {
        type: "object",
        properties: {
          file_path: { type: "string" },
          target: { type: "string" },
          source_path: { type: "string" },
          output_path: { type: "string" },
        },
        required: ["file_path", "target", "source_path"],
      },
    },
  • src/server.ts:525-525 (registration)
    Handler mapping: maps the tool name 'replace_hwp_image' to the imported replaceHwpImage function in the HANDLERS record.
    replace_hwp_image: replaceHwpImage,
  • Core helper function replaceHwpxImages that performs the actual image replacement inside the .hwpx ZIP archive by overwriting BinData entries with new file bytes and writing the modified ZIP.
    export async function replaceHwpxImages(
      inputPath: string,
      outputPath: string,
      replacements: ImageReplaceMap
    ): Promise<ImageReplaceResult> {
      const bytes = await readFile(inputPath);
      const zip = await JSZip.loadAsync(bytes);
    
      const entryNames = Object.keys(zip.files).filter((n) => n.startsWith("BinData/"));
      const result: ImageReplaceResult = { total: 0, replaced: [], skipped: [] };
    
      for (const [target, sourcePath] of Object.entries(replacements)) {
        const fullEntry = target.includes("/") ? target : `BinData/${target}`;
        const match = entryNames.find(
          (n) => n === fullEntry || n.endsWith("/" + target) || n === target
        );
        if (!match) {
          result.skipped.push(target);
          continue;
        }
        const newBytes = await readFile(sourcePath);
        zip.file(match, newBytes);
        result.replaced.push({ entry: match, from: sourcePath, bytes: newBytes.byteLength });
        result.total += 1;
      }
    
      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);
      return result;
    }
Behavior2/5

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

No annotations provided; description mentions 'overwrites' implying mutation but lacks details on side effects, error handling, or whether original file is modified vs new file created. Optional output_path suggests new file possible, but unclear.

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?

Two sentences efficiently convey purpose and key parameter usage. No fluff, but could be more structured with separate sections.

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?

Lacks explanation of return values, error cases, prerequisites, or file handling behavior. For a mutation tool with no output schema and no annotations, more detail is needed.

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?

Adds value by explaining target accepts basename or full entry path and that output_path is optional. However, file_path and source_path are not described. Schema coverage is 0%, so partial compensation.

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?

Clearly states the action ('Replace'), resource ('embedded image inside an .hwpx'), and method ('overwriting its BinData/ ZIP entry'). Distinguishes from sibling tools like insert, delete, extract, and replace_hwp_text.

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 explicit guidance on when to use this tool vs alternatives. Only mentions parameter formats (target accepts basename or full path) but no context for selection among siblings.

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