Skip to main content
Glama

apply_plan

Destructive

Apply validated edit steps to a DOCX document in a single batch operation, ensuring all changes pass validation before implementation.

Instructions

Validate and apply a batch of edit steps (replace_text, insert_paragraph) to a document in one call. Validates all steps first; applies only if all pass. Accepts inline steps or a plan_file_path. Compatible with merge_plans output.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesPath to the DOCX file.
stepsNoJSON array of edit steps. Each step needs step_id, operation, and operation-specific fields.
plan_file_pathNoPath to a .json file containing an array of edit steps. Mutually exclusive with steps.

Implementation Reference

  • The main entry point for the `apply_plan` tool. It handles loading, normalizing, validating, and executing a sequence of steps (replace_text or insert_paragraph) on a DOCX file.
    export async function applyPlan(
      manager: SessionManager,
      params: {
        file_path?: string;
        steps?: unknown[];
        plan_file_path?: string;
      },
    ): Promise<ToolResponse> {
      try {
        // Validate mutual exclusivity of steps and plan_file_path
        if (params.steps && params.plan_file_path) {
          return err(
            'INVALID_PARAMS',
            'Cannot provide both steps and plan_file_path. Use one or the other.',
          );
        }
    
        if (!params.steps && !params.plan_file_path) {
          return err(
            'INVALID_PARAMS',
            'Must provide either steps (JSON array) or plan_file_path.',
          );
        }
    
        // Load steps
        let rawSteps: unknown[];
        if (params.plan_file_path) {
          const loaded = await loadStepsFromFile(params.plan_file_path);
          if (loaded.error) return loaded.error;
          rawSteps = loaded.steps;
        } else {
          rawSteps = params.steps!;
        }
    
        // Normalize steps
        const { steps, errors: normErrors } = normalizeSteps(rawSteps);
        if (normErrors.length > 0) {
          return err(
            'NORMALIZATION_ERROR',
            `Step normalization failed with ${normErrors.length} error(s): ${normErrors.join('; ')}`,
          );
        }
    
        if (steps.length === 0) {
          return err('EMPTY_PLAN', 'Plan contains no valid steps.');
        }
    
        // Resolve session
        const resolved = await resolveSessionForTool(manager, params, { toolName: 'apply_plan' });
        if (!resolved.ok) return resolved.response;
        const { session } = resolved;
    
        // Validation phase — check ALL steps before applying
        const validations = validateSteps(steps, session.doc);
        const overallValid = validations.every((v) => v.valid);
    
        if (!overallValid) {
          return {
            success: false,
            error: {
              code: 'VALIDATION_FAILED',
              message: `Plan validation failed: ${validations.filter((v) => !v.valid).length} of ${steps.length} step(s) have errors.`,
              hint: 'Fix the reported errors and resubmit.',
            },
            overall_valid: false,
            steps: validations,
          };
        }
    
        // Collect warnings
        const allWarnings = validations.flatMap((v) => v.warnings.map((w) => ({ step_id: v.step_id, warning: w })));
    
        // Apply phase — execute steps sequentially
        const result = await executeSteps(manager, manager.normalizePath(session.originalPath), steps);
    
        if (result.failed_step_id !== undefined) {
          return {
            success: false,
            error: {
              code: 'APPLY_PARTIAL_FAILURE',
              message: `Plan execution stopped at step '${result.failed_step_id}' (index ${result.failed_step_index}).`,
              hint: 'Completed steps have already been applied. Reapply to original DOCX if rollback is needed.',
            },
            file_path: manager.normalizePath(session.originalPath),
            completed_count: result.completed_step_ids.length,
            completed_step_ids: result.completed_step_ids,
            failed_step_id: result.failed_step_id,
            failed_step_index: result.failed_step_index,
            failed_step_error: result.failed_step_error,
            step_results: result.step_results,
            ...(allWarnings.length > 0 ? { warnings: allWarnings } : {}),
          };
        }
    
        return ok({
          file_path: manager.normalizePath(session.originalPath),
          edit_count: session.editCount,
          completed_count: result.completed_step_ids.length,
          completed_step_ids: result.completed_step_ids,
          step_results: result.step_results,
          ...(allWarnings.length > 0 ? { warnings: allWarnings } : {}),
        });
      } catch (e: unknown) {
        return err('APPLY_PLAN_ERROR', `Failed to apply plan: ${errorMessage(e)}`);
      }
    }
Behavior4/5

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

Annotations declare destructiveHint=true and readOnlyHint=false. Description adds crucial transactional behavior: 'Validates all steps first; applies only if all pass' (all-or-nothing semantics). No contradictions with annotations.

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?

Four sentences, zero waste: sentence 1 defines core function, sentence 2 explains validation behavior, sentence 3 describes input modes, sentence 4 notes integration with merge_plans. Front-loaded with the most critical information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a complex batch-destructive tool with no output schema, description covers purpose, atomicity, and input formats well. Minor gap: does not describe return value structure or specific error behavior when validation fails.

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 has 100% description coverage, establishing baseline 3. Description adds concrete examples of step operations (replace_text, insert_paragraph) which map to sibling tools, but schema already documents mutual exclusivity and step structure comprehensively.

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?

Description uses specific verbs (validate and apply) and resource (document), explicitly mentions supported operation types (replace_text, insert_paragraph), and distinguishes itself as a batch operation against individual edit siblings.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Describes input alternatives (inline steps vs plan_file_path) and notes compatibility with merge_plans output (a sibling tool). Mentions atomic validation behavior. Could explicitly contrast when to use this versus individual replace_text/insert_paragraph calls.

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/UseJunior/safe-docx'

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