You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add MCP edit_config and hash preconditions for config writes - #3044
Using the mcp to update large files does not work reliably. Either claude refuses because it knows that it will mangle the file content, or it fails. The proposed solution is a new tool: edit_config to solve exactly that.
MCP tool arguments pass through the model, so a small change to a large config currently means sending the whole file twice with update_config: once as content, once as expected. On a 60 KB config that is slow and costly, and can exceed what a client will carry.
edit_config (new): applies {old_text, new_text} replacements on the server under the write lock. Edits apply in order, up to 64 per call. Each old_text must match exactly once when its turn comes, overlapping matches included; otherwise precondition_failed and nothing is written. expected_hash is required, so a tool cannot edit a file it has not read. Returns {sha256}.
get_configwith_hash: returns {yaml, sha256}. The hash covers the text as a read returns it (LF line endings) and ignores trailing newlines, as expected comparison already does.
update_configexpected_hash: an alternative to expected, so the guard no longer costs a second copy of the file. Exactly one of the two is required.
An empty or whitespace-only file has nothing to match, so edit_config refuses it and points at update_config. An edit that would empty a file is refused by the existing rewrite_yaml check. While version history is on, both tools keep landing in it.
Related issue or feature (if applicable):
None
Types of changes
Bugfix (non-breaking change which fixes an issue) — bugfix
New feature (non-breaking change which adds functionality) — new-feature
Enhancement to an existing feature — enhancement
Breaking change (fix or feature that would cause existing functionality to not work as expected) — breaking-change
Tests have been added or updated under tests/ where applicable.
components.index.json / definitions/components/*.json have not been hand-edited (regenerate via script/sync_components.py if a sync is needed).
Architecture-level changes are reflected in docs/ARCHITECTURE.md and/or docs/API.md.
Testing
On Python 3.14 with esphome-constraints.txt (esphome 2026.11.0b2):
Unit: 10019 passed, 10 skipped (tests/benchmarks and tests/real_compile not run)
tests/e2e without slow: 46 passed
tests/e2e/slow/mcp (MCP SDK interop): 2 passed
The overlap test was confirmed to fail against the previous str.count check. The concurrent-write test (two writes from one read: one saves, the other gets precondition_failed) was confirmed to fail without the file's write lock.
On a real install, through the Home Assistant MCP connector:
edit_config with expected_hash applied 19, 62 and 9 edits to an 80 KB config; each returned sha256 matched a get_config read-back. The last batch ran on 01fd925, the others before the review fixes.
The config saved by the last batch passes validate_config, and firmware built from it flashed and booted on the device.
On 01fd925, edit_config refused a missing hash and a non-unique old_text, and update_config refused a stale hash.
update_config with the correct expected_hash saved a config, and a read-back returned the same hash.
Tool arguments pass through the model, so changing a large config with
update_config means sending the whole file, twice. edit_config applies
exact-text replacements on the server, and expected_hash replaces the
expected text with its SHA-256 from get_config with_hash.
✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.77%. Comparing base (ac518df) to head (ed1afbd). ⚠️ Report is 23 commits behind head on main.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Edits introducing CRLF or bare-CR line endings return a hash inconsistent with normalized reads, causing subsequent guarded edits to reject unchanged files with precondition_failed.
Adds targeted MCP configuration edits and hash-based write guards, reducing large-file payloads while reusing the dashboard’s locked YAML persistence and version history.
Changes:
Add edit_config for ordered, exact-text replacements with optional hash protection.
Extend get_config with hash output and update_config with an alternative hash precondition.
Add regression coverage and document the new tool contracts.
edit_config now requires expected_hash, so a tool cannot edit a file it
has not read, matching the guarantee update_config documents.
text_hash normalizes line endings the way a read does. An edit inserting
CRLF or a bare CR used to return a hash that the next read could not
match, so the next guarded edit refused an unchanged file.
update_config's hash path goes through persist_if_unchanged, which now
takes the check as a parameter, rather than repeating it in the MCP layer.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The edit-matching loop scans all overlapping occurrences after a second match establishes non-uniqueness, causing avoidable delays while holding the file’s write lock.
After a second match, the edit must fail, but this loop still scans every overlapping occurrence. For a repetitive 85 KB scalar and a 40 KB old_text, it performs about 45,000 searches and took 1.6 seconds in a standalone check, while holding the file's write lock. Find only the first two occurrences in apply_text_edits and report "2 or more" for a non-unique match.
Counting every overlapping match of a long old_text in repetitive text
took about a second while holding the file's write lock, though the edit
was already going to fail at the second match. The error now says
"2 or more times" rather than the exact count.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed to evaluate untested concurrent hash enforcement and rollback promises that may exceed the versions actually recorded in history.
…wording
Two hash-guarded writes from the same read, run concurrently against the
real controller, must leave exactly one saved and the other refused with
precondition_failed. The test fails if rewrite_yaml stops holding the
file's write lock.
The tool descriptions and API docs promised the previous text always
stays in version history; that only holds while version history is on.
Human assessment is needed to evaluate untested concurrent hash enforcement and rollback promises that may exceed the versions actually recorded in history.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because cancellation and path-locking races can overwrite concurrent edits, while incomplete history capture can leave prior YAML contents unrecoverable.
FuNK3Y: > Human assessment is needed to evaluate untested concurrent hash enforcement and rollback promises ...
Confirmed. test_two_writes_from_the_same_read_cannot_both_land covers both write paths. Exactly one write saves; the other gets PRECONDITION_FAILED. Version-history wording now says "when it is on". Resolved.
PR Review — Add MCP edit_config and hash preconditions for config writes
Ready to merge. All earlier review comments are fixed, and I found no new problems in this pass.
Strengths:
Copilot's CRLF comment is fixed.text_hash converts CRLF and bare CR to LF before hashing, so the hash edit_config returns matches a later read. test_text_edit_hash_stays_valid_after_inserting_other_line_endings checks this against the real controller: it inserts \r\n and \r, then makes a second guarded edit with the returned hash.
Two writes from one read cannot both land. The new test_two_writes_from_the_same_read_cannot_both_land is parametrized over both write paths: persist_if_unchanged with require_hash_unchanged, and rewrite_yaml with edits. It slows the hash check inside the locked callback and asserts that exactly one write saves and the other gets PRECONDITION_FAILED. This covers the concern the author answered in the thread.
No partial writes. I confirmed in controllers/devices/controller.py:922-941 that the hash check, the edits and the new hash all run inside one rewrite_yaml callback, under _yaml_write_lock. The secrets-file refusal and the empty-write refusal still apply.
The uniqueness check stops early._non_unique_match makes at most two find calls, and a test counts them.
Inputs are checked at the boundary.edits has maxItems=64, old_text has minLength=1, empty edits is refused, update_config takes exactly one of expected and expected_hash, and edit_config requires the hash.
Non-blocking note:
api/mcp/tools.py is 774 lines, near the repo's 800-line soft cap. Split it before the next tool is added.
Checklist
No hardcoded secrets
Input validation at boundaries
No partial writes on failure
Concurrent writes from one read cannot both land
Returned hash matches what a later read returns (CRLF/CR)
On Copilot's "needs a closer look" (cancellation, path locking, history capture): I went through each one. None comes from this PR. The write path is unchanged; edit_config and expected_hash are new callers of rewrite_yaml, which already exists on main.
Cancellation:rewrite_yaml holds the per-file asyncio.Lock across await run_in_executor(...). If the caller is cancelled (a client timeout or disconnect), the lock is released but the thread still checks and writes. I reproduced this with persist_if_unchanged (update_config with expected on main): a second write made from the same read was accepted and reported "Saved", then the cancelled write landed over it. _persist_yaml_mutation has the same pattern. Possible fix: run the locked read, check, write and commit as a task the caller can't cancel, e.g. asyncio.shield.
History capture: an outside edit (VS Code, HA File Editor) is committed only after the 2 s debounce. A dashboard save within that window commits its own result, and discard_pending drops the queued entry, so the outside edit never reaches history. Possible fix: commit the current file under the lock before writing; git does nothing if it's unchanged.
Lock key:os.path.normpath(configuration) is case-sensitive, so Kitchen.yaml and kitchen.yaml get separate locks on Windows and macOS. Possible fix: casefold() the key.
This PR adds a test showing two hash-guarded writes from the same read can't both land when neither is cancelled. It also changes the docs to say writes are recorded in version history only while it's on.
J. Nick Koston (@bdraco) would you rather have these fixed in their own PR? They touch shared controller code that existed before this PR and affect the editor save too. I'm happy to open it.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Concurrent writes can silently overwrite newer configuration because create/import overwrite paths bypass the per-file lock and case-equivalent Windows filenames acquire different locks.
The reason will be displayed to describe this comment to others. Learn more.
Pre-existing on main: devices/create(overwrite=True) and the bundle import skip the lock for every rewrite_yaml caller, the editor save included, not just this PR's tools. Fixed in #3116, which holds the file's write lock across both overwrites and their history commits.
The reason will be displayed to describe this comment to others. Learn more.
Pre-existing on main: _yaml_write_lock keys on normpath for every caller, the editor save and update_config with expected included. Fixed in #3116, which case-folds the key and dedupes multi-file lock sets so a case-only rename can't deadlock, with a test for case variants.
The pre-existing locking and cancellation issues from my earlier comment now have their own PR: #3116. It covers:
Lock keys: case-insensitive, so Kitchen.yaml and kitchen.yaml share one lock.
Overwrites:devices/create with overwrite and the bundle import now take the per-file lock.
Cancellation: locked writes run to completion even when their caller is cancelled.
Shutdown: waits for writes still in flight and refuses new ones.
This PR doesn't depend on it: edit_config and expected_hash are new callers of rewrite_yaml, which #3116 hardens for every caller. Whichever merges second needs a rebase over one small conflict in the imports of tests/controllers/devices/test_get_update_config.py.
Recording an outside edit in version history before a dashboard save overwrites it isn't in #3116; that's a separate change.
This branch has not been deployed
No deployments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this implement/fix?
Using the mcp to update large files does not work reliably. Either claude refuses because it knows that it will mangle the file content, or it fails. The proposed solution is a new tool:
edit_configto solve exactly that.MCP tool arguments pass through the model, so a small change to a large config currently means sending the whole file twice with
update_config: once ascontent, once asexpected. On a 60 KB config that is slow and costly, and can exceed what a client will carry.edit_config(new): applies{old_text, new_text}replacements on the server under the write lock. Edits apply in order, up to 64 per call. Eachold_textmust match exactly once when its turn comes, overlapping matches included; otherwiseprecondition_failedand nothing is written.expected_hashis required, so a tool cannot edit a file it has not read. Returns{sha256}.get_configwith_hash: returns{yaml, sha256}. The hash covers the text as a read returns it (LF line endings) and ignores trailing newlines, asexpectedcomparison already does.update_configexpected_hash: an alternative toexpected, so the guard no longer costs a second copy of the file. Exactly one of the two is required.An empty or whitespace-only file has nothing to match, so
edit_configrefuses it and points atupdate_config. An edit that would empty a file is refused by the existingrewrite_yamlcheck. While version history is on, both tools keep landing in it.Related issue or feature (if applicable):
Types of changes
bugfixnew-featureenhancementbreaking-changerefactordocsmaintenancecidependenciesFrontend coordination
Checklist
ruff,codespell, yaml/json/python checks).tests/where applicable.components.index.json/definitions/components/*.jsonhave not been hand-edited (regenerate viascript/sync_components.pyif a sync is needed).docs/ARCHITECTURE.mdand/ordocs/API.md.Testing
On Python 3.14 with
esphome-constraints.txt(esphome 2026.11.0b2):tests/benchmarksandtests/real_compilenot run)tests/e2ewithoutslow: 46 passedtests/e2e/slow/mcp(MCP SDK interop): 2 passedThe overlap test was confirmed to fail against the previous
str.countcheck. The concurrent-write test (two writes from one read: one saves, the other getsprecondition_failed) was confirmed to fail without the file's write lock.On a real install, through the Home Assistant MCP connector:
edit_configwithexpected_hashapplied 19, 62 and 9 edits to an 80 KB config; each returnedsha256matched aget_configread-back. The last batch ran on01fd925, the others before the review fixes.validate_config, and firmware built from it flashed and booted on the device.01fd925,edit_configrefused a missing hash and a non-uniqueold_text, andupdate_configrefused a stale hash.update_configwith the correctexpected_hashsaved a config, and a read-back returned the same hash.🤖 Generated with Claude Code