Skip to content

Add MCP edit_config and hash preconditions for config writes - #3044

Open
FuNK3Y wants to merge 5 commits into
esphome:mainfrom
FuNK3Y:mcp-edit-config
Open

FuNK3Y wants to merge 5 commits into
esphome:mainfrom
FuNK3Y:mcp-edit-config

Conversation

@FuNK3Y

@FuNK3Y FuNK3Y commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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_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_config with_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_config expected_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
  • Refactor (no behaviour change) — refactor
  • Documentation only — docs
  • Maintenance / chore — maintenance
  • CI / workflow change — ci
  • Dependencies bump — dependencies

Frontend coordination

  • No frontend change needed
  • Companion frontend PR: esphome/device-builder-frontend#

Checklist

  • The code change is tested and works locally.
  • Pre-commit hooks pass (ruff, codespell, yaml/json/python checks).
  • 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.

🤖 Generated with Claude Code

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.
@github-actions github-actions Bot added the new-feature New feature label Nov 6, 2026
@codspeed

codspeed Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 28 untouched benchmarks
⏩ 1 skipped benchmark1


Comparing FuNK3Y:mcp-edit-config (ed1afbd) with main (67382cc)

Open in CodSpeed

Footnotes

  1. 1 benchmark was skipped, so the baseline result was used instead. If it was deleted from the codebase, click here and archive it to remove it from the performance reports. ↩

@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ 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.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #3044   +/-   ##
=======================================
  Coverage   99.77%   99.77%           
=======================================
  Files         300      300           
  Lines       26562    26613   +51     
=======================================
+ Hits        26501    26552   +51     
  Misses         61       61           
Flag Coverage Δ
py3.12 99.73% <100.00%> (+<0.01%) ⬆️
py3.14 99.62% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
esphome_device_builder/api/mcp/tools.py 100.00% <100.00%> (ø)
...home_device_builder/controllers/devices/helpers.py 99.51% <100.00%> (+0.05%) ⬆️
esphome_device_builder/helpers/text.py 100.00% <100.00%> (ø)

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions github-actions Bot added enhancement Improvement to an existing feature and removed new-feature New feature labels Nov 6, 2026
@esphbot

ESPHome Bot (esphbot) commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

No blocking issues found — ready to merge.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

1 open issue
What changed in this PR

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.
File Description
tests/​controllers/​devices/​test_get_update_config.py Cover real-controller persistence, empty-file updates, and empty-result rejection.
tests/​api/​test_mcp_tools.py Cover MCP hashing, ordered edits, and refusal paths.
esphome_device_builder/​helpers/​text.py Add SHA-256 hashing that ignores trailing newlines.
esphome_device_builder/​controllers/​devices/​helpers.py Add hash checks and unique-match text replacements, including overlapping matches.
esphome_device_builder/​api/​mcp/​tools.py Register edit_config and extend configuration read/write arguments.
docs/​API.md Document tool arguments, preconditions, and version-history recovery.

Review effort: Max

Comment thread esphome_device_builder/api/mcp/tools.py Resolved
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.
@esphbot

ESPHome Bot (esphbot) commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

No blocking issues found — ready to merge.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Stop searching after finding a second matching occurrence

esphome_device_builder/​controllers/​devices/​helpers.py:156

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.

Review effort: Max

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.
@FuNK3Y
FuNK3Y marked this pull request as ready for review November 7, 2026 09:29
@bdraco
J. Nick Koston (bdraco) requested review from ESPHome Bot (esphbot) and a max review from Copilot November 7, 2026 20:17

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

No open issues 🎉

1 resolved since last review

Review effort: Max

@esphbot

ESPHome Bot (esphbot) commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

No blocking issues found — ready to merge.

…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.
@FuNK3Y

FuNK3Y commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Human assessment is needed to evaluate untested concurrent hash enforcement and rollback promises that may exceed the versions actually recorded in history.

A test was added to cover for that

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

No open issues 🎉

Review effort: Max

@esphbot

Copy link
Copy Markdown
Contributor

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.

@esphbot

Copy link
Copy Markdown
Contributor

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)
  • Single write path through rewrite_yaml
  • Tests cover new branches and edge cases
  • Docs updated (docs/API.md)

Automated review by Kōan (Claude) HEAD=ed1afbd 20s

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

No blocking issues found — ready to merge.

@FuNK3Y

FuNK3Y commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

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.

  1. 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.
  2. 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.
  3. 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.

@FuNK3Y
FuNK3Y marked this pull request as draft November 20, 2026 10:25
@FuNK3Y

FuNK3Y commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Code mode (https://code.claude.com/docs/en/code-mode) could be another way around the problem.

Still, it is not widespread, and the hash approach offers some tangible benefits. I have been using this feature for a while and it really helps.

@FuNK3Y
FuNK3Y marked this pull request as ready for review November 20, 2026 10:29
@esphbot

Copy link
Copy Markdown
Contributor

Note

No code changes since the last review (ed1afbd) — skipping. Push new commits or re-request a review to run again.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

2 open issues

Review effort: Max

Comment on lines +266 to +267
await persist_if_unchanged(
_devices(db),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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.

new_text = apply_text_edits(current, args["edits"], configuration)
return new_text, {"sha256": text_hash(new_text)}

return await _devices(db).rewrite_yaml(configuration, _rewrite, message=f"Edit {configuration}")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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.

@FuNK3Y FuNK3Y mentioned this pull request Nov 27, 2026
7 of 16 tasks
@FuNK3Y

FuNK3Y commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Improvement to an existing feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants