Skip to content

feat(mcp): worker agents read patches through their agent tools - #886

Merged
allisonmahmood merged 5 commits into
mainfrom
mcp/854-read-patch
Oct 23, 2026
Merged

allisonmahmood merged 5 commits into
mainfrom
mcp/854-read-patch

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 22, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #885 (ticket #853); merges with the rest of #833's stack, not alone.

What changed

A person's worker agent can now read a patch through its agent tools: read_patch { patch, tool, args } runs a query or read-only action as the person, on the version served when the call arrives, and answers { result, version }. Until now the door refused it as not built.

Closes #854

Look at

  • One version per call (packages/mcp/src/Calls.ts, reach). The patch is resolved among those the person can open, then the tool's existence, its kind and its arguments are all checked against the version the list read, and Invocation.callAgent runs on that same LoadedVersion. A test publishes a version that flips the tool to a mutation while the call runs: the call still ran on the read's version, and the next call is refused wrong_kind, naming the tools there are now and open_patch.
  • The recheck before every company callback (Calls.recheck, AgentConnections.current). It reads the connection, the person and agent access on the database's clock without stamping last used, and answers the person as they are now, so a role change shows. On real workerd, a call whose connection is disconnected between its shared-table read and its Postgres read gets { first: 2, second: "access_denied" }, and the next call gets 401.
  • Caps measured once. A read's compact JSON text over 100,000 characters is refused too_large ("Narrow the call; the patch's owner, Priya Shah, can add paging."). The door fits every tool's refusal into the same cap in one place: past it, a refusal keeps its code, its words and any retry wait and leaves its details out, and refusals repeat at most 128 characters of a tool name, so what they say to do always arrives. Arguments over the runtime's argument cap are refused before anything starts the patch. The read cap lives in @patchy/api beside the other shared shapes, so the catalogue and patchy dev agent use the same number.
  • Server wiring. Server.ts now merges the host's invocation into the server's services so the door finds the same instance Runtime uses (provideMerge instead of provide); a host that runs no patch code answers source_unavailable. The new apps/server test fails without that line.

Decisions the spec left open, picked the way #844 picked unknown_tool and invalid_args:

  • wrong_kind for a change tool named on read_patch (and, for Worker agents change patches, and a retried change is applied once #855, a read on change_patch).
  • patch_retired for the retired refusal, the code publishing already uses: "new-business was retired by Priya Shah on 12 Oct 2026; they can restore it. Tell the person."
  • patchy dev agent refuses a read over the cap too, since it answers what the door would.

How it was verified

  • packages/mcp/src/Calls.test.ts, the door over a migrated database with Runtime's invocation as an alternate layer: success shape and what the door hands Runtime (person, ctx.agent, version), refusals before anything runs, publishes between and during calls, retired versus not found (other company, Openability closed, deleted), both caps, a patch's own refusal and Runtime's, and the recheck through a role change, agent access off and on, disconnect and deactivation.
  • packages/mcp/src/Calls.workerd.test.ts, on real workerd: an agent reads its own table and a shared table as the person with ctx.agent; a read-only action reads company Postgres, attributed to the person; forced writes in read-only actions are refused (invalid_query, sqlstate 25006, no row written; access_denied "A read-only action cannot write."); the shared table's live check refuses the whole read once its source is retired and passes again on restore; a disconnect mid-call stops at the next callback. The request event carries agentTool, agentToolKind, handler, kind, outcome and queue, guest and database milliseconds, and no arguments or results.
  • apps/server/src/McpDoor.test.ts: a dev-mode server publishes a tier 2 patch with an agent area and read_patch runs it through the server's own invocation.
  • AgentConnections.current, wrongKindRefusal, readAnswer, fitRefusal and patchy dev agent's cap have focused tests; Door.test.ts checks every tool's refusal keeps the read cap.
  • The head, 8d83b9f, is 9b14bea rebased onto the base's one new commit, a docs edit to patchy-server's skill outside the paragraph this PR adds; the skill's tests pass on it. pnpm verify passed on 9b14bea (2,260 tests, Postgres concurrency, CLI and tier 2 smoke, 81 browser tests). CI is green on the same head after a re-run of clerk-live and tier2-smoke, which had hit their job time limits on slow runners.
  • Rollback rehearsal: the PR's rollback-rehearsal check runs against production's commit, which doesn't yet have Tier 2 readers accept handler descriptions, read-only actions and agent tools, and enforce them #837 and Deactivation and Disconnect everything end pending device logins and record when a person's credentials ended #838. Rehearsed instead against main at e4243ff, which has both: pnpm test:rollback-rehearsal --live e4243ff passed e4243ff → 9b14bea → e4243ff → 9b14bea on one set of data, in 169 s.
  • Codex 0.163.0 on a dev instance read a patch through its agent tools, on both revisions, and recovered from a publish between calls. Transcripts below.
Codex on a dev instance, transcripts

A pnpm dev up brightline environment. New Business (tier 2, sample data) gained an agent/deals.ts with two reads, dealsInStage (a query) and forecast (a read-only action), published from the environment's workspace. Allison turned agent access on at Company. Codex ran as Jordan Lee, a member, with a token from pnpm dev mcp-token jordan --client Codex, from a temp dir outside $HOME: codex exec --json --ephemeral --ignore-user-config -s read-only -c 'mcp_servers.patchy.url="<instance>/mcp"' -c 'mcp_servers.patchy.bearer_token_env_var="PATCHY_MCP_TOKEN"'. Tool results are cut here.

Asked: "Using the patchy MCP server: find our new-business pipeline patch and open it. Then tell me which deals are in negotiation right now, with each one's value and owner, and what the weighted forecast is for the whole open pipeline."

Codex's default revision (2025-06-18):

agent: I’ll find the new-business pipeline in Patchy, open it, and check the negotiation deals and weighted forecast.
(Codex read the machine's global Patchy skill)
(Codex read the machine's global Patchy skill)
agent: I’m using the Patchy skill with the MCP server you requested.
mcp_tool_call patchy.find_patches({"search": "new business", "detail": "tools"}) -> completed: {"actingFor":{"person":"Jordan Lee","company":"Brightline Studio"},"total":1,"patches":[{"name":"new-business","description":"Brightline's new-business pipeline: track every pitch from first lead to signed work, with own…
mcp_tool_call patchy.open_patch({"patch": "new-business"}) -> completed: {"name":"new-business","description":"Brightline's new-business pipeline: track every pitch from first lead to signed work, with owners, stage rules and a live board the whole studio shares.","owner":"Allison Mahmood","a…
mcp_tool_call patchy.read_patch({"patch": "new-business", "tool": "forecast", "args": {}}) -> completed: {"result":[{"stage":"lead","deals":4,"value":105000,"weighted":10500},{"stage":"discovery","deals":3,"value":178000,"weighted":44500},{"stage":"proposal","deals":3,"value":179000,"weighted":89500},{"stage":"negotiation",…
mcp_tool_call patchy.read_patch({"patch": "new-business", "tool": "dealsInStage", "args": {"stage": "negotiation"}}) -> completed: {"result":[{"id":"01a164fa-7643-7655-84ce-ed9812d73dd0","client":"Atlas Outdoor Co.","title":"E-commerce rebuild","value":140000,"owner":"Marcus Chen","nextStep":"Send a revised timeline with two releases","expectedClose…
agent: Opened the [new-business pipeline](<instance>/brightline/new-business).

Currently in negotiation:

| Deal | Value (USD) | Owner |
|---|---:|---|
| Atlas Outdoor Co. — E-commerce rebuild | $140,000 | Marcus Chen |
| Bluebird Pediatrics — Clinic signage and wayfinding | $26,000 | Sofia Alvarez |

The **weighted forecast for the whole open pipeline is $269,000 USD**, across 12 deals with a total unweighted value of $628,000.

With --enable mcp_2026_07_28 it made the same calls, with the same answer:

agent: I’ll find and open the pipeline patch, then check the negotiation deals and weighted forecast.
(Codex read the machine's global Patchy skill)
mcp_tool_call patchy.find_patches({"search": "new business", "detail": "tools"}) -> completed: {"actingFor":{"person":"Jordan Lee","company":"Brightline Studio"},"total":1,"patches":[{"name":"new-business","description":"Brightline's new-business pipeline: track every pitch from first lead to signed work, with own…
agent: I found Brightline’s `new-business` patch, owned by Allison Mahmood. I’m using the Patchy skill with the MCP server to read its pipeline data.
mcp_tool_call patchy.open_patch({"patch": "new-business"}) -> completed: {"name":"new-business","description":"Brightline's new-business pipeline: track every pitch from first lead to signed work, with owners, stage rules and a live board the whole studio shares.","owner":"Allison Mahmood","a…
mcp_tool_call patchy.read_patch({"patch": "new-business", "tool": "forecast", "args": {}}) -> completed: {"result":[{"stage":"lead","deals":4,"value":105000,"weighted":10500},{"stage":"discovery","deals":3,"value":178000,"weighted":44500},{"stage":"proposal","deals":3,"value":179000,"weighted":89500},{"stage":"negotiation",…
mcp_tool_call patchy.read_patch({"patch": "new-business", "tool": "dealsInStage", "args": {"stage": "negotiation"}}) -> completed: {"result":[{"id":"01a164fa-7643-7655-84ce-ed9812d73dd0","client":"Atlas Outdoor Co.","title":"E-commerce rebuild","value":140000,"owner":"Marcus Chen","nextStep":"Send a revised timeline with two releases","expectedClose…
agent: Opened the [new-business pipeline](<instance>/brightline/new-business).

Two deals are in negotiation:

| Deal | Value (USD) | Owner |
|---|---:|---|
| Atlas Outdoor Co. — E-commerce rebuild | $140,000 | Marcus Chen |
| Bluebird Pediatrics — Clinic signage and wayfinding | $26,000 | Sofia Alvarez |

The **weighted forecast for the whole open pipeline is $269,000 USD**, across 12 deals with a total estimated value of $628,000.

Then forecast was renamed weightedForecast and published as version 3. Asked: "Using the patchy MCP server, call read_patch with patch new-business, tool forecast and args {} — that's the tool I used yesterday — and tell me the weighted forecast for the open pipeline."

agent: I’ll check the forecast through the Patchy MCP server.
(Codex read the machine's global Patchy skill)
agent: I’m using the Patchy skill for this read.
mcp_tool_call patchy.read_patch({"patch": "new-business", "tool": "forecast", "args": {}}) -> failed: new-business has no tool forecast. Its tools now: dealsInStage, weightedForecast. Call open_patch to see what each does and takes.
mcp_tool_call patchy.open_patch({"patch": "new-business"}) -> completed: {"name":"new-business","description":"Brightline's new-business pipeline: track every pitch from first lead to signed work, with owners, stage rules and a live board the whole studio shares.","owner":"Allison Mahmood","address":"<instance>/brightline/new-business","tools":[{"name":"dealsInStage","kind":"read","description":"List the deals in one pipeline stage, most recent activity first: each dea…
mcp_tool_call patchy.read_patch({"patch": "new-business", "tool": "weightedForecast", "args": {}}) -> completed: {"result":[{"stage":"lead","deals":4,"value":105000,"weighted":10500},{"stage":"discovery","deals":3,"value":178000,"weighted":44500},{"stage":"proposal","deals":3,"value":179000,"weighted":89500},{"stage":"negotiation","deals":2,"value":166000,"weighted":124500}],"version":3}
agent: The weighted forecast for the open pipeline is **$269,000 USD**, across 12 deals with a total estimated value of $628,000.

Yesterday’s `forecast` tool is now called `weightedForecast`; I used the current tool to retrieve this.

The door's request events for the last four read_patch calls (selected fields; none carries arguments or results):

{"status": 200, "outcome": "success", "mcpTool": "read_patch", "agentTool": "forecast", "agentToolKind": "read", "handler": "agent.forecast", "kind": "action", "protocolEra": "modern", "clientName": "Codex", "patchRef": "name", "queueWaitMs": 1, "guestMs": 9, "dbMs": 1.06489, "callbacks": 1, "argsBytes": 2, "resultBytes": 254}
{"status": 200, "outcome": "success", "mcpTool": "read_patch", "agentTool": "dealsInStage", "agentToolKind": "read", "handler": "agent.dealsInStage", "kind": "query", "protocolEra": "modern", "clientName": "Codex", "patchRef": "name", "queueWaitMs": 0, "guestMs": 11, "dbMs": 13.928742, "callbacks": 2, "argsBytes": 23, "resultBytes": 445}
{"status": 200, "outcome": "refused", "code": "unknown_tool", "mcpTool": "read_patch", "agentTool": "forecast", "protocolEra": "legacy", "clientName": "Codex", "patchRef": "name"}
{"status": 200, "outcome": "success", "mcpTool": "read_patch", "agentTool": "weightedForecast", "agentToolKind": "read", "handler": "agent.weightedForecast", "kind": "action", "protocolEra": "legacy", "clientName": "Codex", "patchRef": "name", "queueWaitMs": 1, "guestMs": 7, "dbMs": 0.909001, "callbacks": 1, "argsBytes": 2, "resultBytes": 254}

Release impact

  • Breaking — requires action from anyone already running this
  • Not breaking — no action required

No migration and no new rows: read_patch answers on a door that ships with the rest of #833's stack.

  • What does a revert leave behind? Nothing: no schema, no stored shapes, no configuration.
  • Does the release before it still work with that? Yes.

Built by Claude Opus 5.5 (xhigh) in Claude Code on T3 Code; reviewed and accepted by GPT-6.1-Sol (xhigh).

@github-actions github-actions Bot added area:server Touches the server area area:cli Touches the cli area area:docs Touches the docs area size:xl Over 1,000 changed lines; review in multiple passes labels Oct 22, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Review: GPT-6.1-Sol (xhigh), four rounds

Each round reviewed git diff origin/mcp/853-your-machines...HEAD against #854's Done means, the spec's door sections, #833's invariants and CLAUDE.md, with the threat model spelled out: a change tool reached through read_patch; a forced write inside a read-only action; a publish between the checks and the invocation; a connection, person or agent access ending mid-call; shared tables and integrations under an agent; a retired patch leaking who retired it; size caps measured once; events leaking arguments or results. No round found anything blocking. Every round confirmed those properties hold, except the read cap, which took four rounds to close for every kind of refusal.

Round Head Finding Outcome
1 cba78af Should-fix: refusals bypassed the 100,000-character read cap (a 120,041-character patch refusal reached the caller). Fixed in dc5bcdd: past the cap a refusal keeps its code, words and retry wait and leaves its details out.
1 cba78af Should-fix: the door's 128-character tool-name bound was stricter than publishing, so a published tool could be listed but not called. Fixed in dc5bcdd: the bound is agentToolsBytes, which no published name can exceed; the event keeps 128 characters.
1 cba78af Performance: two sequential recheck queries per company callback. Fixed in dc5bcdd: they run concurrently, one round trip.
1 cba78af Performance: a company-wide Patches.read per call, per-call argument schema compile, Runtime's manifest-identity cache not helping across requests. Dismissed: the same read and cost model as #852's open_patch, bounded by the company's patches (narrowing it belongs to Patches and the catalogue together, with #857's data); a small struct compile next to several round trips, cacheable by immutable version id if ever measured; the cache limitation is pre-existing for page calls. Round 2 agreed, noting #857 should also measure retained version history.
2 dc5bcdd Should-fix: refusals made before invocation (wrong_kind, unknown_tool) could repeat a 50,000-character tool name past the cap. Fixed in c0b2a8a with fitRefusal.
— dc5bcdd pnpm turbo run build --filter=@patchy/mcp failed: TS28 "any in the error channel" in the recheck against the built declaration files (reported by #855's lane, and red CI). Fixed in c0b2a8a; round 3 confirmed CompanyNotFound → die is sound, since foreign keys keep a company while its people's connections exist.
3 c0b2a8a Should-fix: agent_access_off with a huge admin list skipped the cap. Fixed in 6b39d81: the door fits every tool's refusal once, for all four tools.
3 c0b2a8a Should-fix: cutting a refusal could drop its instructions when a tool name was huge. Fixed in 6b39d81: refusals repeat at most 128 characters of a tool name and 2,000 of a schema's words.
4 6b39d81 Should-fix: a patch's own refusal still repeated the full tool name before its words. Fixed in 9b14bea: the same shortening.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Acceptance: PASS with notes

Checked 8d83b9ff4930a33303dee8090b8156b8fa2033f3 (base 8153299018f7ed7d6d96d6f6ee25bde438fbe188, mcp/853-your-machines) on fresh brightline data and disposable test databases, by GPT-6.1-Sol (xhigh) in the Codex harness on T3 Code.

Done means

  • Codex reads a patch through its agent tool: passed. Codex CLI 0.163.0 found and opened New Business, then read dealsInStage and the read-only forecast action at version 2 as Jordan Lee, a member, via Codex. It returned the two negotiation deals and the expected $269,000 weighted forecast.
  • Read-only action reads Postgres and refuses a forced write: passed on real workerd (Calls.workerd.test.ts). The Postgres read returned the fixture rows and was attributed to the member; forced INSERT returned invalid_query / SQLSTATE 25006, with no row added. A forced primitive write returned access_denied.
  • Publish between calls: passed. Renamed forecast to weightedForecast and published version 3: the old name returned unknown_tool, naming the current tools and open_patch; Codex recovered and read version 3. Calls.test.ts also passed the publish-during-invocation kind flip and subsequent kind, existence and argument refusals on the same loaded version.
  • Disconnect mid-call stops the next callback: passed on real workerd. The asserted answer was { first: 2, second: "access_denied" }; the next call returned HTTP 401.
  • Shared-table and integration invariants: passed. Agent reads used the person's authority; retiring the shared source refused the whole read, and restoring it recovered. Rechecks also passed role changes, agent access off/on, disconnect and deactivation.

Golden journeys

  • Sign in: passed. Signed-out company page returned 401 with the sign-in door and private/no-store headers; Jordan signed in and Home listed the scenario patches. Browser session, expiry and principal-switch checks passed.
  • Publish a page; share/unshare; retire/restore: passed in packed CLI/browser suites. Direct MCP retirement named Allison and the date; restore made the same address and read work with the original data.
  • Find/open a tool: passed. Jordan's Home search found one Kudos result and opened its populated frame.
  • Tier 1 live tools: passed. Browser two-viewer subscriptions and the packed tier 1 journey passed.
  • Tier 2 tools: passed. Jordan moved a sample deal, Allison read its new stage, and Jordan moved it back. Spend refused Jordan's own approval with own_approval. Packed and browser two-viewer tier 2 sync passed.
  • Machine login and invite/join are not touched by this diff.

Other risks and verification

  • 103 focused tests passed, including the actual server's invocation wiring, read/refusal shapes, caps, retired/foreign/closed/deleted visibility and the no-invocation refusal.
  • Read calls passed on 2025-06-18 and 2026-07-28. Direct boundary checks also passed: compact Unicode JSON at exactly 100,000 characters succeeded; 100,001 returned too_large with owner/paging guidance. Wrong-kind, non-agent tool, invalid/excess arguments, patch-owned refusal details and agent access off/on all passed. Runtime argument-cap and oversized-refusal tests passed.
  • pnpm verify: format, lint, typecheck, synth, Postgres concurrency (28 tests), CLI smoke, tier 2 smoke and all 81 browser tests passed. Offline tests were 2,259 passed / 1 local environment failure; see Notes. The installer suite then passed 7/7 with the explicit Node 24.20.0 executable.
  • All CI checks on this head are green, including live Clerk and Node 22/24/26 tests.
  • Request events carried the outer/inner tool and kind, outcome and timings, without argument/result fields. Wire/docs, CLI README/ADR, glossary and project skill mirrors are present; no migration, new resource, rendered-page or package-layout change applies.

Rollback answers: match the diff. No new schema, persisted shape, infrastructure or incompatible write is introduced; a revert restores the previous read refusal. No one-way label is needed. The green rollback check explicitly skipped rehearsal because no migration or handler descriptor changed.

Not run

  • Live Clerk locally: not rerun; the head's clerk-live CI check passed.
  • Live ECS execution: not run; execution checks used disposable local workerd, without touching production.

Notes

  • The host's Node 26 directory contains a global patchy. The installer's “bin not on PATH” case therefore received the correct “another copy comes first” refusal instead. Installer source/tests are unchanged by this PR; the same seven tests passed using Node 24.20.0, whose directory has no global patchy. The original pnpm verify invocation still exited nonzero for that assertion.
  • The standalone environment CLI lacked workerd/package.json; even republishing the unchanged tier 2 patch failed inspection before loading its bundle. The scenario runner's repo CLI has the pinned dependency. I supplied that exact workerd package only in the throwaway CLI environment, then published the agent fixture and its rename successfully. No PR source, branch, body or labels were changed.
Independent Codex transcripts (scenario data; instance address normalized)
I’ll find the new-business pipeline in Patchy, check the negotiation deals, and calculate the weighted forecast without changing anything.
find_patches {"search":"new business","detail":"tools"} -> completed
open_patch {"patch":"new-business"} -> completed
read_patch {"patch":"new-business","tool":"forecast","args":{}} -> completed
read_patch {"patch":"new-business","tool":"dealsInStage","args":{"stage":"negotiation"}} -> completed
Opened the [new-business pipeline](<instance>/brightline/new-business).

Deals in negotiation:

| Deal | Value (USD) | Owner |
|---|---:|---|
| Bluebird Pediatrics — Clinic signage and wayfinding | $26,000 | Sofia Alvarez |
| Atlas Outdoor Co. — E-commerce rebuild | $140,000 | Marcus Chen |

The entire open pipeline has **12 deals** totaling **$628,000**, with a **weighted forecast of $269,000 USD**.

No changes were made.

After publishing the rename:

I’ll check the forecast through Patchy and use its discovery tools if the forecast tool has changed.
read_patch {"patch":"new-business","tool":"forecast","args":{}} -> failed
open_patch {"patch":"new-business"} -> completed
read_patch {"patch":"new-business","tool":"weightedForecast","args":{}} -> completed
The current weighted forecast is **$269,000 USD** across 12 open deals.

The tool is now called `weightedForecast`; I recovered through Patchy’s tools. Nothing was changed.
Selected successful request event
{
  "mcpTool": "read_patch",
  "agentTool": "weightedForecast",
  "agentToolKind": "read",
  "handler": "agent.weightedForecast",
  "kind": "action",
  "outcome": "success",
  "queueWaitMs": 0,
  "guestMs": 9,
  "dbMs": 0.955429
}

@allisonmahmood allisonmahmood mentioned this pull request Oct 23, 2026
Base automatically changed from mcp/853-your-machines to main October 23, 2026 15:42
read_patch runs a patch's read tool, a query or read-only action, through
Runtime's agent invocation as the person, on the version served when the call
arrived. The tool's existence, kind and arguments are checked against that same
version before anything runs, and every company callback rechecks the
connection, the person and agent access on the database's clock. Results come
back as { result, version } within 100,000 characters of compact JSON; a change
tool is refused naming change_patch, and a retired patch says who retired it
to whoever could open it. The call path is shared, so change_patch can reuse it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…led, and a recheck is one round trip

A read's refusal past 100,000 characters now keeps its code, its words and any
retry wait and leaves its details out, as the agent reads every answer whole.
The door takes any tool name a publish can produce, since a patch's tools fit
in 60 KiB, and its event keeps 128 characters of it. A callback's recheck reads
the connection and agent access at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…package builds against its dependencies' types

A refusal the door makes before anything runs can repeat a long tool name or a
schema's words about long arguments, so it now passes through the same limiter
as the patch's and Runtime's refusals. The recheck's agent access read no
longer leaves an any in the error channel when built against the declaration
files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The door now fits every refusal it answers into the read cap in one place,
agent_access_off naming many admins included. A refusal repeats at most 128
characters of a tool name the agent sent and 2,000 of a schema's words, so
what it says to do next always reaches the agent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood merged commit 2853256 into main Oct 23, 2026
25 of 26 checks passed
@allisonmahmood
allisonmahmood deleted the mcp/854-read-patch branch October 23, 2026 15:59
allisonmahmood added a commit that referenced this pull request Oct 23, 2026
…ied once (#887)

Stacked on #886 (ticket #855); merges with the rest of #833's stack, not
alone.

## What changed

A worker agent can now change a patch through `change_patch`, and
retrying a change never applies it twice. Until now the door refused
`change_patch` as not built.

Each change carries a change key, any string the agent picks, such as
`import-monday`. Patchy keeps it for 24 hours, per agent connection and
patch, in a new `change_keys` table. Every host replica therefore
answers a retry the same way:

- A mutation's first try gets a fresh Runtime mutation key, and every
retry reuses it. A committed change is answered again with `replayed:
true` and runs nothing. A try that ended any other way,
`unknown_outcome` included, runs again under the same mutation key, so
Runtime commits it at most once. When Runtime's own record answers that
retry, it carries `replayed: true` too.
- An action's key runs once. Any later try is refused unrun.
- A try while the key's first try is still running is refused `busy`
with `retryAfterSeconds: 1`. The same key for another tool or other
arguments is refused, and so is a retry after a publish.
- A change whose result is too large for an agent to read succeeds with
the result left out.

Closes #855

## Look at

- **`packages/mcp/src/ChangeKeys.ts`**, the record. It is three
statements on the database's clock.
  - The claim inserts the key, or takes over one past its 24 hours.
- A retry of the same mutation takes over a record that no try holds and
Patchy hasn't seen commit.
- A read decides the rest: conflict, version changed, busy, used, or
replay.

It stores only hashes of the key (as JSON, so lone surrogates stay
distinct) and of the arguments' canonical JSON. Key order and how a
number is written don't make two changes of one.
- **`Calls.change`** in `packages/mcp/src/Calls.ts`. It claims the key
only after every check passes, and only on a host that runs patch code,
so a refusal before running leaves the key free. The request calls
Runtime itself, as `read_patch` does, so a hang-up reaches Runtime and
the request's event keeps its measurements. A try that ends settles its
key, time-bounded. A try whose agent hung up keeps the key held until
its lease runs out (the spec's `busy` while it may still be running),
and a retry then resolves through Runtime's record.

**Codex on a dev instance**, with two server processes over one
database. `pnpm dev up` (team scenario), then a tier 2 `call-log` patch
with an `agent/` area (`logCalls` takes a list, `listCalls`,
`sendDigest`, and later `slowLog` and `exportCalls`), published from the
environment's workspace. Ada turned agent access on at Company.

"Another replica" is a **second server process**
(`apps/server/src/start.ts`) started against the same dev database and
storage on its own port. Its `PATCHY_PUBLIC_BASE_URL` was its own
address, because the door answers only its own `Host`. Codex had both as
MCP servers: `patchy` (the instance's server) and `patchy_b` (the second
process). Both servers' own events confirm it: the first wrote
`replayed: false` and the second `replayed: true`.

Codex ran as Ada with a token from `pnpm dev mcp-token ada --client
Codex`, from a temp dir outside `$HOME`: `codex exec --json --ephemeral
--ignore-user-config -s read-only -c 'mcp_servers.patchy.url=…' -c
'mcp_servers.patchy.bearer_token_env_var="PATCHY_MCP_TOKEN"'`, and the
same two settings for `patchy_b`. Codex honoured `change_patch`'s
destructive mark: under `exec` with no approver it refused every change
("MCP tool call requires approval, but approval policy is never"). So
the runs add `-c
'mcp_servers.<server>.tools.change_patch.approval_mode="approve"'`. Tool
results are cut here.

<details><summary>Three calls in one change, then the retry on the other
replica</summary>

~~~text
agent: I’ll find and open the call-log patch, add the three calls in one
change, then repeat the identical request through patchy_b and check the
rows.
(Codex read the machine's global Patchy skill)
mcp_tool_call patchy.find_patches({"search": "call"}) -> completed:
{"actingFor": {"person": "Ada Park", "company": "Acme Co"}, "total": 1,
"patches": [{"name": "call-log", "description": "Logs sales calls;
people's agents log a day's calls at once.", "owner": "Ada Park",
"address": "<instance>…
mcp_tool_call patchy.open_patch({"patch": "call-log"}) -> completed:
{"name": "call-log", "description": "Logs sales calls; people's agents
log a day's calls at once.", "owner": "Ada Park", "address":
"<instance>/acme/call-log", "tools": [{"name": "listCalls", "kind":
"read", "description
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool":
"logCalls", "key": "import-monday", "args": {"calls": [{"who": "Grace
Hopper at Globex", "note": "Wants a renewal quote."}, {"who": "Linus
Pauling at Initech", "note": "Churn risk; call back Friday."}, {"who":
"Ada Lovelace at Hooli", "note": "New lead; send a deck."}]}}) ->
completed: {"result": {"logged": 3}, "version": 1}
mcp_tool_call patchy_b.change_patch({"patch": "call-log", "tool":
"logCalls", "key": "import-monday", "args": {"calls": [{"who": "Grace
Hopper at Globex", "note": "Wants a renewal quote."}, {"who": "Linus
Pauling at Initech", "note": "Churn risk; call back Friday."}, {"who":
"Ada Lovelace at Hooli", "note": "New lead; send a deck."}]}}) ->
completed: {"result": {"logged": 3}, "version": 1, "replayed": true}
mcp_tool_call patchy.read_patch({"patch": "call-log", "tool":
"listCalls", "args": {}}) -> completed: {"result": [{"id":
"01a16526-7270-7d76-9fed-296f59a0e27f", "who": "Ada Lovelace at Hooli",
"note": "New lead; send a deck.", "createdAt":
"2026-10-22T19:46:20.913143Z", "updatedAt":
"2026-10-22T19:46:20.913143Z"}, {"id":
"01a16526-7269-78ed-a19b-fc0cb9cfdce9",
agent: There are **3 rows**, one for each call. The identical retry with
key `import-monday` created no duplicates.

- **patchy:** `{"result":{"logged":3},"version":1}`
- **patchy_b:** `{"result":{"logged":3},"version":1,"replayed":true}`
~~~

</details>

<details><summary>A reused key for another change, and an action's key
used twice</summary>

~~~text
agent: I’ll find the call-log patch, run the three calls separately with
your exact keys, and report each response verbatim.
(Codex read the machine's global Patchy skill)
mcp_tool_call patchy.find_patches({"search": "call-log"}) -> completed:
{"actingFor": {"person": "Ada Park", "company": "Acme Co"}, "total": 1,
"patches": [{"name": "call-log", "description": "Logs sales calls;
people's agents log a day's calls at once.", "owner": "Ada Park",
"address": "<instance>…
mcp_tool_call patchy.open_patch({"patch": "call-log"}) -> completed:
{"name": "call-log", "description": "Logs sales calls; people's agents
log a day's calls at once.", "owner": "Ada Park", "address":
"<instance>/acme/call-log", "tools": [{"name": "listCalls", "kind":
"read", "description
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool":
"logCalls", "key": "import-monday", "args": {"calls": [{"who":
"Katherine Johnson at Pied Piper", "note": "asked for pricing"}]}}) ->
failed: {"error": {"code": "key_conflict", "from": "patchy", "message":
"That key was used for a different change to call-log; pick a new one. A
key names one change: one tool with the same arguments."}}
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool":
"sendDigest", "args": {}, "key": "digest-1"}) -> completed: {"result":
{"calls": 3}, "version": 1}
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool":
"sendDigest", "args": {}, "key": "digest-1"}) -> failed: {"error":
{"code": "key_used", "from": "patchy", "message": "sendDigest is an
action, and it already ran with this key; an action that writes is not
safe to retry, so Patchy never runs its key twice. Read what it changes
first, then retry with a new key if it
agent: 1) `logCalls`, key `"import-monday"`:
```text
That key was used for a different change to call-log; pick a new one. A key names one change: one tool with the same arguments.
```

2) `sendDigest`, key `"digest-1"`:
```json
{"result":{"calls":3},"version":1}
```

3) `sendDigest`, key `"digest-1"`:
```text
sendDigest is an action, and it already ran with this key; an action that writes is not safe to retry, so Patchy never runs its key twice. Read what it changes first, then retry with a new key if it still needs doing.
```
~~~

</details>

<details><summary>After a second publish: the retry is refused, and a
large result is left out</summary>

~~~text
agent: I’ll check the Patchy instructions, then make each requested call
once and report its response verbatim.

(Codex read the machine's global Patchy skill)
mcp_tool_call patchy.open_patch({"patch": "call-log"}) -> completed:
{"name": "call-log", "description": "Logs sales calls; people's agents
log a day's calls at once.", "owner": "Ada Park", "address":
"<instance>/acme/call-log", "tools": [{"name": "exportCalls", "kind":
"change", "descrip
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool":
"logCalls", "key": "import-monday", "args": {"calls": [{"who": "Grace
Hopper at Globex", "note": "Wants a renewal quote."}, {"who": "Linus
Pauling at Initech", "note": "Churn risk; call back Friday."}, {"who":
"Ada Lovelace at Hooli", "note": "New lead; send a deck."}]}}) ->
failed: {"error": {"code": "version_changed", "from": "patchy",
"message": "call-log was published since your first try with this key;
read before retrying. If the change still needs making, make it with a
new key."}}
mcp_tool_call patchy.open_patch({"patch": "call-log"}) -> completed:
{"name": "call-log", "description": "Logs sales calls; people's agents
log a day's calls at once.", "owner": "Ada Park", "address":
"<instance>/acme/call-log", "tools": [{"name": "exportCalls", "kind":
"change", "descrip
mcp_tool_call patchy.change_patch({"patch": "call-log", "tool":
"exportCalls", "args": {}, "key": "export-1"}) -> completed: {"version":
2, "resultLeftOut": "exportCalls succeeded, but its result came to
120,029 characters, more than the 100,000 an agent reads in one answer,
so it was left out. Read what you need of the change through the patch's
read tools."}
agent: 1) `import-monday`

```text
call-log was published since your first try with this key; read before retrying. If the change still needs making, make it with a new key.
```

2) `export-1`

```json
{"version":2,"resultLeftOut":"exportCalls succeeded, but its result came to 120,029 characters, more than the 100,000 an agent reads in one answer, so it was left out. Read what you need of the change through the patch's read tools."}
```

Neither call was retried.
~~~

</details>

<details><summary>busy: two tries of one key racing on the two processes
(curl, same token)</summary>

One Codex session can't send two calls at once, so this race used curl
with Codex's token. `slowLog` waits three seconds before it writes.

~~~text
B during it: {"error": {"code": "busy", "from": "patchy", "message":
"The first try with this key is still running. Try again in a second
with the same key.", "retryAfterSeconds": 1}}
A first try: {"result": {"id": "01a16527-f852-7428-be04-21bf0028408e"},
"version": 2}
B after it: {"result": {"id": "01a16527-f852-7428-be04-21bf0028408e"},
"version": 2, "replayed": true}
~~~

</details>

Afterwards, `change_keys` held four rows, each with a 64-hex key hash
and none with a key in clear. Neither server's log contains
`import-monday`.

## How it was verified

- **`ChangeKeys.test.ts`** drives the door against an alternate Runtime
layer, with two doors over one database as two replicas:
- a fresh mutation key of Runtime's shape on a first try, and a replay
on the other replica with arguments reordered and `1.0` for `1`;
- two replicas racing one key: one runs, and the other is `busy`, or
replayed if its claim lands after the commit;
- `key_conflict` for other arguments and for another tool, and
`version_changed` after a publish;
- `unknown_outcome`, then a patch refusal, then a success, all under one
mutation key, then a replay;
- an action runs once, a timed-out action says it may have partly
happened, and a result over 100,000 characters is left out;
  - keys scoped per connection and per patch;
- only hashes stored, a key just inside 24 hours still replayed, a key
past 24 hours treated as a new change, and the sweep;
- bad keys, `wrong_kind` and a host without patch code all leave no row.
- **`ChangeKeys.workerd.test.ts`** runs on real workerd with two
invocations and doors over one database:
  - three rows written once;
  - the retry on the other replica writes nothing;
- a retry whose result the door never recorded resolves through
Runtime's own mutation key, still three rows;
  - the action runs once.
- **Unit and wiring tests:** `changeAnswer` in `agentTools.test.ts`, the
hourly sweep in `SweepSchedules.test.ts`, and the migration record's
ids.
- **Targeted runs:** `packages/mcp` (65 tests), `packages/api`
`agentTools` (26), `patchy dev agent` (6), the server's sweep and
migrations (5).
- **Typecheck and lint:** `pnpm turbo run build --filter=@patchy/server
--filter=patchy`, `tsc -p tsconfig.test.json`, and eslint and prettier
on the changed files.
- **Rollback rehearsal:** the new table is composed into
`apps/server/src/migrations.ts`, which the vitest template and the
rehearsal both apply.
- The rehearsal now stores a change key. At step 2, HEAD turns agent
access on and makes a `change_patch` through `/mcp`. At step 4, after
the live release ran on that data, the same key must answer `replayed:
true` with the first result.
- Until #837 and #838 are both live, the `rollback-rehearsal` check
against production's commit fails, as #833 says. Runs against `main`'s
e4243ff, which has both, are recorded in comments below.

### Choices where the spec is silent

- **Codes:** `key_conflict` (same key, another tool or arguments),
`version_changed` (a retry after a publish), `key_used` (a later try
with an action's key) and `key_expired` (below). `busy` is the spec's.
- **Result left out:** `{ version, resultLeftOut }`. It has no `result`,
and `resultLeftOut` says the change succeeded and to read through the
patch's read tools. `changeAnswer` in `@patchy/api` gives `patchy dev
agent` the same shape.
- **A retry Patchy hasn't seen commit stops a few minutes before 24
hours.** It runs under the first try's mutation key only while Runtime
is sure to keep that key's outcome. The window is the mutation key's own
24 hours, aged from the time in it as Runtime ages it, less one try's
longest run and Runtime's allowed clock skew (about 6 minutes in all).
After that it is `key_expired`, saying to read first and use a new key,
because a later retry could find Runtime's outcome swept and write
twice. A change Patchy saw commit is answered from its own record for
the full 24 hours.
- **An action's key is spent by any try that reached Runtime**,
including one Runtime refused `busy` before starting. An action's
refusal can't say whether it started (a callback's `busy` can surface
after a write), so the literal rule is the safe one: the agent retries
with a new key.

**One Runtime change.** `Invocation.callAgent` takes an optional
`onReplay`, carried on the `Binding`. Invocation calls it when a
top-level mutation answers with its key's outcome stored by another
invocation. That lets the door, and `patchy dev agent`, put `replayed:
true` on a retry that Runtime's own record answered, such as one after
an `unknown_outcome`. Mutation keys and page calls are unchanged.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

It adds a table (`0024_change_keys`) and a door tool that was refused
until now.

- **What does a revert leave behind?** The `change_keys` table and any
rows in it: hashes of keys, version ids, and committed mutation results
of at most 64 KiB. Its foreign keys to `agent_connections` and `patches`
cascade on delete.
- **Does the release before it still work with that?** Yes. Nothing
before it reads the table, and the cascades keep a patch purge or a
connection's removal working on any release.

Built by Claude Opus 5.5 (xhigh) in Claude Code on T3 Code; reviewed and
accepted by GPT-6.1-Sol (xhigh).
allisonmahmood added a commit that referenced this pull request Oct 23, 2026
## What changed

This PR adds release 17's What's new entry, written from `5dd94f3`. It
covers everything merged since release 16's `through` (`dd3f41f`), and
it sets the `patchy` release to `0.17.0` in
`packages/patchy/package.json` and `CURRENT_RELEASE`. With this release,
people's agents can use their company's patches through Patchy MCP
(#833).

| Change | PRs |
| --- | --- |
| New: Your AI agent can use your company's tools | #873, #878, #880,
#881, #882, #883, #884, #886, #887 |
| New: Admins choose whether agents can use the company's tools | #871 |
| Improved: Your machines shows your agents too (Revoke all machines is
now Disconnect everything) | #885, #879 |
| New: See what agents can do with a tool | #876 |
| New: The log says when an agent made a change | #888 |
| New: Your agent can make a tool ready for agents | #869, #870, #872,
#875, #896 |
| Behind the scenes: agents' calls have their own limits, and a server
only an agent uses rests a minute after its last call | #889, #892 |
| Behind the scenes: New and Improved changes are public, for
patchyhq.com | #893 |
| Behind the scenes: library updates | #899 |

Five merged PRs get no line:
- #874 is release 16's own entry.
- #894 is dev tooling: worker agent launchers and scenario data. Its one
CLI fix lets a `patchy` installed outside a tier 2 repo publish it. The
skills have agents use the repo's pinned `pnpm patchy` instead, so that
path is off the documented one.
- #900 is CI.
- #901 rewords an internal skill.

## Look at

- **The entry**, at the top of `releases` in
`packages/core/src/whatsNew.ts`.
- It names only Claude Code and Codex. Both have connected through real
consent against dev instances. Hosted clients (Claude.ai, ChatGPT) are
checked in production only (`docs/product.md` › Patchy MCP ›
Acceptance).
- Its labels are the pages' own: Agent access on Company, Your machines,
What agents can do, Disconnect everything, and "Jordan Lee via Claude".
- **Rollback safety, from the live commit `e4243ff` to `5dd94f3`.**
- No PR in the range is labelled `one-way`, and every PR answers both
Release impact questions with "Yes".
  - Migrations 0020–0025 are all additive:
    - three defaulted or nullable columns on `companies`;
- `agent_name` on the runtime log, with a widened `credential_kind`
check;
    - the agent connection tables, `agent_consents` and `change_keys`;
    - two columns on execution bindings.

The new tables reference `users` without a cascade, but no release
deletes users or companies. Release 16 reads the runtime log only for
credential kinds it knows, so rows from agents can't break it.
- `rollback-rehearsal` on #892 rehearsed the whole stack, since #892
adds the last migration and the rest of the stack sits below it:
`Exercised rollback paths passed: e4243ff → c8bede4 → e4243ff → c8bede4,
in 238s.` #896's run skipped, because it changes no migration or handler
descriptor.
- #883 turns on the load balancer's host header preservation, which the
Deploy workflow's app stack deploy applies. A rollback leaves it on.
That's harmless, because release 16's server never reads `Host`.
- A rollback takes `/mcp` and `/whats-new.json` away. Connected agents
get a 404 until this release returns, and then their connections work
again, unless one ended in between. Agent tools published in between
stay refused to pages, because #837 already shipped in release 16.

## How it was verified

- `pnpm check` on `2d528b1`: format, lint, typecheck and synth passed.
In the test step, 2,300 of 2,301 tests passed. The one failure was
`packages/sdk/src/install.test.ts` › "says how to reach patchy when the
prefix's bin is not on PATH", which timed out at 180 s while the shared
machine was loaded. Rerun alone, that file passes all 7 tests in 62 s.
The release's own tests pass too: `whatsNew.test.ts`, `schemas.test.ts`
and `WhatsNewPages.test.ts`.
- The live commit was pinned from `/healthz/deep`: `e4243ff`, release
16. The Deploy run updated last succeeded, and none is unfinished.
- Each PR in the range was read with `gh pr view`, including its Release
impact answers.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

This PR changes only the changelog text and the `patchy` version. As
with every release, a CLI installed before this deploy is told to
upgrade.

- **What does a revert leave behind?** Nothing. People whose seen marker
reached 17 would just see no new release.
- **Does the release before it still work with that?** Yes.

If this release misbehaves, roll back to
`e4243ff54d2acbbc88b60eeb0cf9b82a26dc9d5d` (release 16).

Prepared by Claude Opus 5.5 (xhigh) in Claude Code on T3 Code.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Touches the cli area area:docs Touches the docs area area:server Touches the server area size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Worker agents read patches through their agent tools

1 participant