Handling Multiple expected_replacements in MCP edit_block: A Complete Guide
DesktopCommanderMCP validates every edit_block operation against an explicit expected_replacements count, rejecting the request when the actual occurrence count does not match the declared value.
The edit_block command in wonderwhy-er/DesktopCommanderMCP provides atomic file editing capabilities that prevent accidental overwrites by requiring callers to declare exactly how many instances of a search string should be replaced. This safety mechanism ensures predictable edits across both plain text files and structured Microsoft Word documents.
How expected_replacements Validation Works in edit_block
The validation pipeline separates file-type-specific logic from the generic edit dispatcher, ensuring consistent behavior whether you are editing .txt files or .docx archives.
The Core Logic in performSearchReplace
In src/tools/edit.ts, the performSearchReplace function implements the primary validation flow. The function first normalizes the search string, then iterates through the file content using indexOf to count exact matches.
The validation occurs at lines 42-53: if the counted occurrences exceed zero and exactly equal expectedReplacements, the replacement proceeds. Otherwise, the operation aborts before any modifications are written to disk.
Exact Match Counting and Validation
The counting mechanism uses a normalized version of the search string to ensure consistent matching across different line-ending formats. When expectedReplacements > 1, the code replaces all found occurrences using split(normalizedSearch).join(newStr) (lines 84-89 in edit.ts).
This approach guarantees that the number of replacements performed always matches the number promised in the request, eliminating ambiguity about which instances were modified.
Handling Multiple Replacements vs Single Replacements
DesktopCommanderMCP treats single and multiple replacements differently at the implementation level to optimize performance and reporting accuracy.
Single replacement (expected_replacements: 1): The system performs a targeted splice operation that replaces only the first occurrence and returns a detailed preview of the specific edit location.
Multiple replacements (expected_replacements: N): The system uses a global split-join strategy that replaces every instance simultaneously. This ensures atomicity—either all N replacements occur, or the entire operation fails with a validation error.
Error Handling When Occurrence Counts Mismatch
When the actual occurrence count diverges from the declared expectation, DesktopCommanderMCP returns a descriptive error message that includes both the expected and actual counts.
According to lines 124-132 in src/tools/edit.ts, the error format follows this pattern:
Expected 1 occurrences but found 4 in /path/to/file.txt.
Double check and make sure you understand all occurrences...
This feedback loop allows AI agents and developers to adjust their search strings—perhaps by adding surrounding context—to achieve the desired specificity before retrying the operation.
DOCX File Support for expected_replacements
The expected_replacements contract extends beyond plain text to Microsoft Word documents through DocxFileHandler.editRange in src/utils/files/docx.ts.
The DOCX handler extracts the XML representation of the document and applies the same counting logic via countOccurrences (lines 86-95). Because DOCX files store content across multiple XML files internally, the handler validates that the total count across all document parts matches the expected_replacements value before performing the replacement.
For DOCX edits with multiple expected replacements, the handler uses the same split-join strategy (lines 98-105) to ensure consistent semantics across file types.
Practical Code Examples
Basic edit_block with Multiple Replacements
To replace exactly four instances of a repeating line in a text file:
{
"command": "edit_block",
"file_path": "/path/to/file.txt",
"old_string": "This is a repeating line.",
"new_string": "This line has been replaced correctly.",
"expected_replacements": 4
}
DesktopCommanderMCP replies with a preview of the edited region and confirms that 4 edits were applied.
Handling Mismatch Errors
If you declare fewer replacements than actually exist, the operation fails safely:
{
"command": "edit_block",
"file_path": "/path/to/file.txt",
"old_string": "This is a repeating line.",
"new_string": "Changed line.",
"expected_replacements": 1
}
When the file contains four matches, the server returns:
Expected 1 occurrences but found 4 in /path/to/file.txt.
Double check and make sure you understand all occurrences...
DOCX Edit with Expected Count
For Microsoft Word documents, the syntax remains identical:
{
"command": "edit_block",
"file_path": "/path/to/document.docx",
"old_string": "Old paragraph text.",
"new_string": "New paragraph text.",
"expected_replacements": 2
}
If the DOCX XML contains exactly two matches, the edit succeeds; otherwise, the error message mirrors the text-file case.
Programmatic Usage in Node.js
You can invoke the handler directly from your application:
import { handleEditBlock } from './dist/handlers/edit-search-handlers.js';
const result = await handleEditBlock({
file_path: '/tmp/multi.txt',
old_string: 'repeat',
new_string: 'changed',
expected_replacements: 3
});
console.log(result.content[0].text);
Summary
- Explicit counting: DesktopCommanderMCP requires an
expected_replacementsparameter to prevent accidental overwrites when search strings appear multiple times. - Validation location: Core logic resides in
src/tools/edit.ts(performSearchReplace) andsrc/utils/files/docx.ts(editRange). - Atomic replacements: When
expected_replacements > 1, the system replaces all instances usingsplit(...).join(...)only after confirming the count matches exactly. - Clear feedback: Errors specify both the expected and actual occurrence counts, enabling precise query adjustments.
- Cross-format consistency: Both plain-text and DOCX handlers enforce identical validation semantics.
Frequently Asked Questions
What happens if expected_replacements exceeds actual occurrences?
DesktopCommanderMCP aborts the operation and returns an error message indicating that fewer occurrences were found than expected. According to the test suite in test/test-edit-block-occurrences.js, this validation prevents partial edits when the search string is unexpectedly rare in the target file.
Does DesktopCommanderMCP support partial replacements?
No. The edit_block command operates on an all-or-nothing basis. If the actual occurrence count does not exactly match expected_replacements, the system returns an error without modifying the file, ensuring that callers cannot accidentally replace only a subset of matches.
How does fuzzy search interact with expected_replacements?
When no exact matches are found (count === 0), DesktopCommanderMCP triggers runFuzzySearchInWorker to find similar strings using a threshold of FUZZY_THRESHOLD = 0.7. However, the fuzzy fallback only suggests alternatives—it does not bypass the expected_replacements validation. You must still provide an accurate count after confirming the correct search string.
Are expected_replacements validated differently for DOCX files?
No. The validation logic in src/utils/files/docx.ts mirrors the plain-text implementation exactly. Both handlers use countOccurrences to validate against the declared expectation before performing the replacement, ensuring consistent behavior across file formats.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →