Skip to content

feat(mcp): agent connections, the work credential, with rotating refresh tokens - #878

Merged
allisonmahmood merged 2 commits into
mainfrom
mcp/846-agent-connections
Oct 23, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
mcp/846-agent-connections

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 22, 2026 •

Copy link
Copy Markdown
Owner

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

What changed

People's agents had no credential of their own: the only bearer was a machine token, which opens the CLI's API. This adds the agent connection, the work credential that Patchy MCP's door (#851) will take, with its storage and tokens. Consent (#849) creates connections and #847 ends them; this is the credential itself.

Closes #846

Look at

The one recoverable secret. A retry within a minute of a rotation gets the same new tokens, so they must be kept recoverable for that minute. They're encrypted (AES-256-GCM) under a key derived (HKDF) from the refresh token that was rotated, not under a server key. Only whoever presents that old token can read the copy. The database holds its hash, which yields no key, so a database leak alone reveals nothing, and no keyring or PATCHY_CREDENTIAL_KEYS dependency enters Auth. Whether a copy is served is decided by the database's clock alone. The server's sweeper also drops every copy past its minute, every 15 seconds whatever the traffic, so none is stored much past it. See packages/auth/src/AgentConnections.ts and the sweeper in apps/server/src/Server.ts.

Reuse detection keeps every refresh token a connection issued (as hashes, in agent_connection_refresh_tokens), not just the previous one. Otherwise someone who copied a token and rotated twice could make the real client's later reuse look "unknown", and keep the connection. A partial unique index keeps one current token per connection: the one chain.

Everything runs on the database's clock. The hour, the retry minute, the 30 idle days and the comparison with #838's credentials-ended stamp are all clock_timestamp() in the statement that uses them, so app servers whose clocks disagree can't move any boundary. The tests move time by backdating stored stamps rather than with TestClock. The work bearer check is one UPDATE … RETURNING: it checks the token and stamps last used on every admitted call, so last used is the last call and 30 idle days are exact.

The bearer check takes its purpose. Authorization.identify("build" | "work") maps each purpose to its own store and identity type, with no casts. The API guard and dev reads now ask for "build". Agent tokens are never stored as machine tokens, so any release's API refuses them as unknown.

$ pnpm --silent dev mcp-token [email protected] --client Codex
Codex can act as Patchy Dev at Patchy Dev.
  Token       pwa_…
  Connection  agc_ks84kxpmpsg6alxmkpbsazx3
$ curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $agent_token" $url/api/me
401
$ curl -s -w "\n%{http_code}\n" -H "Authorization: Bearer patchy-dev-token" $url/api/me
{"user":{"id":"usr_dev",…},"machine":{"id":"tok_dev","name":"Dev Machine"}}
200
$ pnpm --silent dev mcp-token [email protected] --client Codex
Nobody with the email [email protected] is in this instance's database yet; sign in as them once first.

In the dev database the minted connection holds only 64-character hashes, nothing in machine_tokens, and an access lifetime of 365 days.

How it was verified

Surfaces. Migrations: 0022_agent_connections, above the stack's 0021. The vitest template takes the tables through apps/server's migration record, and its seed rows are unchanged, so tests mint their own. docs/DEVELOPMENT.md and the patchy-dev-loop skill cover pnpm dev mcp-token. The Auth glossary's Agent connection, Purpose and Machine token already read as built, so they're unchanged. No route, CLI command or docs/API.md change.

Release impact

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

Three new tables; nothing existing changes shape.

  • What does a revert leave behind? The three agent connection tables and any rows in them (only dev-minted ones until consent ships).
  • Does the release before it still work with that? Yes. It never reads those tables, and an agent connection's token is unknown to its API.

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:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area area:integrations Company connections and integration implementations size:xl Over 1,000 changed lines; review in multiple passes labels Oct 22, 2026
@allisonmahmood
allisonmahmood force-pushed the mcp/845-card-agent-panel branch from 4739933 to 31862c3 Compare October 22, 2026 13:33
@allisonmahmood
allisonmahmood force-pushed the mcp/846-agent-connections branch from 30cefb7 to 82a05f4 Compare October 22, 2026 13:43
@allisonmahmood

Copy link
Copy Markdown
Owner Author

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

Round 1 (at 223af6a). Nothing blocking. Two should-fix findings, both fixed in the commit now at 82a05f4 (30cefb7 before the restack):

  1. Retry copies outlived their minute without activity. They were cleared only by the connection's next call or rotation, so on a quiet connection the old refresh token plus the database's ciphertext could still recover the successor.
    Fixed: AgentConnections.sweepRetries, run by the server's sweeper every 15 seconds whatever the traffic. The partial index now covers rotated_at, and serving is still decided only by the database's one-minute cutoff.
  2. Last used was an hourly sample, so a connection could end up to an hour before 30 days without a call.
    Fixed: the work bearer check is one UPDATE … RETURNING that checks and stamps on every admitted call.

Sol confirmed the rest of the threat model:

  • an access token replays only within its hour;
  • concurrent refreshes serialize on the connection;
  • reuse, including tokens several rotations old, ends the connection before the refusal;
  • the user → connection lock order holds, with no inversion against company → device login → user;
  • all four boundaries use the database's clock;
  • the separate stores keep work and build tokens apart on this release and the one before.

It judged both design choices sound: the HKDF-from-the-old-token key for the retry copy, and keeping every refresh hash.

Also fixed, found while making those fixes: the client-name regex and its test held raw bidirectional and line-separator characters where \u escapes were meant. They are escapes now.

Round 2 (at 30cefb7, code identical to 82a05f4). No findings at any severity. Both fixes are correct and complete. Sol checked the UPDATE … FROM joins for uniqueness and behaviour behind refresh and revocation locks in Postgres, and ran 16 concurrent authentications. It saw no blocker in the per-call write at the door's limits; that was not a load benchmark.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Acceptance: PASS with notes

Checked 82a05f46753ab9d647264d1025cda8015a8b9b51 (stack base 31862c3850faa0fb3931be59912fe91ebb27d21c) on a fresh team instance, by GPT-6.1-Sol (xhigh) in the Codex harness on T3 Code. No PR code, body, branch or labels changed.

Done means

  • Ordinary work credential and rotation: passed. The local 12-case AgentConnections suite passes. An independent probe against the instance's real Postgres verified one-hour issuance, refusal at expiry, successful refresh, 16 simultaneous refreshes returning the same successor, and an in-minute retry returning that successor. Reuse of a token two rotations back committed revocation before returning RefreshRefused; the latest access token was then refused.
  • Dev mint: passed. pnpm dev mcp-token resolves a scenario key, first name and email, cleans the client name, stores only token hashes outside machine_tokens, and gives access more than 364 days of remaining lifetime. The minted token passes the work check. An unknown person is refused. A POST to /dev/mcp-token returns 404 and creates no connection.
  • Purposes remain separate: passed. The minted work token receives 401 from both /api/me and an unmatched /api/* route. Existing machine authentication completes login, publishing, sharing and lifecycle operations. The suite also verifies that a machine token fails the work check.

Additional risks

  • Lifetime and endings: passed. The probe verified a year-old connection still works with recent use, refresh does not update last used, and exactly 30 idle days refuse access and refresh. Ada's signed-in “Revoke all machines” action ends her existing work token, leaves Ben's working, and permits a newly created connection. The local suite covers deactivation, disconnected retries, per-call last-used stamping and the credentials-ended boundary.
  • Running sweeper: passed. Without invoking the sweep manually, an expired retry copy disappeared within 20 seconds while a copy still inside its minute remained. The local schedule test also passes for independent hourly deletion/orphan sweeps and the 15-second retry sweep.
  • Dev reads and API guard: passed. Their affected suites pass in the focused local run.

Golden journeys

  • Sign in: passed locally. Ben's Home responds 401 signed out, 200 signed in, then 401 after sign-out.
  • Log a machine in: passed locally. CLI handoff → Ada confirms the displayed code → whoami names “Acceptance machine”; logout returns whoami to refusal.
  • Publish a page: passed locally. Ada publishes; Ben reads the page and finds it on Home. Retire/restore and delete/restore preserve its working address.
  • Share and unshare: passed locally using the team page: anonymous 401 → public 200 with public, max-age=60 → company 401.
  • Find and open a tool: passed in CI. The 83-case PortalPages suite includes Home search and discovery; local Home discovery/open also worked for the published page.
  • Use a tier 1 tool live: passed in CI. The browser job includes a colleague's write updating another subscribed screen.
  • Use a tier 2 tool: passed in CI. The browser job includes two-viewer server subscriptions; packed tier2-smoke passes two-viewer sync, keyed retry, sharing, files and tier changes.
  • Invite and join: passed through automated coverage. Local CompanyPage/AuthPages suites pass; CI's company/portal suites cover membership and deactivation/reactivation, and clerk-live passes real invitations, the login door and device confirmation/revocation.
Verification evidence

Local command:

pnpm exec vitest run packages/auth apps/server packages/integrations/src/DevReads.test.ts scripts/dev

Test Files  36 passed (36)
     Tests  287 passed (287)

Reviewed CI run for this exact PR head: all checks pass, including 2,107 offline tests on Node 24, 81 browser cases, live Clerk, packed CLI/tier 2, concurrency and rollback rehearsal. The rollback job actually rehearsed the upgrade and rollback, rather than skipping: all three steps passed.

Every environment CLI invocation explicitly removed PATCHY_API_URL and PATCHY_API_TOKEN and selected that environment's cli-state. Before teardown, every recorded process's cwd was verified inside this checkout. After pnpm dev down, all three recorded PIDs were gone and both instance/scenario directories were removed. The checkout remains clean at the checked head.

Rollback answers: Match the diff. Migration 0022 adds three isolated tables and their indexes; it changes no existing row shape. Reverting leaves those rows behind, but the previous release ignores them and cannot recognize their tokens in its machine-token store. No one-way label is needed.

Not run / notes

@allisonmahmood
allisonmahmood force-pushed the mcp/845-card-agent-panel branch from 31862c3 to f74b681 Compare October 23, 2026 02:09
@allisonmahmood
allisonmahmood force-pushed the mcp/846-agent-connections branch from 82a05f4 to 39527c5 Compare October 23, 2026 02:09
@allisonmahmood allisonmahmood mentioned this pull request Oct 23, 2026
@allisonmahmood
allisonmahmood force-pushed the mcp/845-card-agent-panel branch from f74b681 to 45c2e4a Compare October 23, 2026 12:53
Base automatically changed from mcp/845-card-agent-panel to main October 23, 2026 13:09
…esh tokens

People's agents get their own credential beside machine tokens. An agent
connection keeps its client's id, name and site, and its tokens: access
tokens last an hour and are checked on every call; a refresh token rotates
on every use, a retry within a minute gets the same new tokens, and any
later reuse ends the connection before it is refused. A connection ends
after 30 days without a call and honours the credentials-ended stamp. The
bearer check takes the purpose it opens for, and `pnpm dev mcp-token`
mints one straight into a dev database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… copies after their minute

Hourly stamping let a connection end up to an hour before 30 days without a
call, and a retry copy outlived its minute until the connection's next call
or rotation. Every admitted call now stamps last used in the statement that
checks it, and the server sweeps retry copies every 15 seconds whatever the
traffic. The client name's invisible characters are escapes in the source.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood force-pushed the mcp/846-agent-connections branch from 39527c5 to 18cac61 Compare October 23, 2026 13:09
@allisonmahmood
allisonmahmood merged commit 726adc2 into main Oct 23, 2026
25 of 26 checks passed
@allisonmahmood
allisonmahmood deleted the mcp/846-agent-connections branch October 23, 2026 13:25
allisonmahmood added a commit that referenced this pull request Oct 23, 2026
… connections (#879)

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

## What changed

A person ends an agent connection in several ways: they disconnect it,
press Disconnect everything, leave it 30 days without a call, or have
its refresh token reused. Deactivation ends it too, and reactivation
brings nothing back. Each of these now ends what the spec's endings
table says, in one transaction, and the next call sees it. That includes
a rollback to the release before the stack. ADR-0008 now reads as
decided, retitled *Every bearer is somebody: machine tokens and agent
connections*.

Closes #847

## Look at

**Disconnect everything and deactivation end agent connections through
#838's stamp alone.** Neither writes an `agent_connections` row. #846's
check already treats a connection made at or before
`users.credentials_ended_at` as dead, and both endings already set the
stamp in their own transaction, under the person's row lock. Release 16
sets the same stamp and knows nothing of agent connections, so a
rollback that ends credentials still ends connections. This PR keeps
that one mechanism rather than adding a second. Only
`MachineTokens.revokeAll` and `Users.deactivate` change, and only in
their comments. `revokeAll` needs no machine token to exist, as #853
will rely on.

**The one new write is `AgentConnections.disconnect({ id, userId })`**,
for Your machines' Disconnect (#853 wires the route). It is one `UPDATE
… RETURNING` scoped to the owner. Another person's id, an admin's
included, is `AgentConnectionNotFound`. Disconnecting a connection that
has already ended keeps its first stamp. The statement takes only the
connection's row, which refresh also holds `FOR UPDATE` while it
rotates. It holds no lock before or after that one, so it can't invert
refresh's user-then-connection order.

**The races, tested deterministically.** Each test holds one side's
transaction open, waits until the other blocks on a lock in
`pg_stat_activity`, then commits:

- *A connection made racing a deactivation.* When the deactivation
commits first, the exchange waits on the person's row and is refused
`UserUnavailable`, so reactivation finds nothing to bring back. When the
exchange commits first, the deactivation's stamp comes later on the
database's clock and ends the connection. With `create`'s `FOR SHARE`
removed, the first case fails: the exchange returns a live connection
made against a committed deactivation, and it survives reactivation.
- *A refresh racing Disconnect everything.* When the ending commits
first, the refresh waits and is refused `ended`. When the refresh
commits first, what it issued dies with the connection.

Every comparison is `clock_timestamp()` against `credentials_ended_at`,
both written under the person's row lock, so no app server's clock
enters it.

**The rollback rehearsal now runs four steps: live → HEAD → live →
HEAD.**

1. At step 2, HEAD mints agent connections for the publisher, Jordan and
Priya.
2. At step 3, release 16 ends credentials as people do, in Chromium:
- Priya collects one device login's machine token, approves a second
without collecting it, and presses Disconnect everything (*Revoke all
machines* on that release);
- the admin deactivates Jordan and reactivates them through Company's
confirmation pages.
3. At step 4, back at HEAD:
- HEAD's own `work` check refuses Jordan's and Priya's connections and
still accepts the publisher's;
- Priya's approved device login answers `unknown`. An `expired` answer
would show nothing, so it fails as well;
   - her machine token gets 401.

## How it was verified

- `packages/auth/src/Endings.test.ts`, one test per row of the endings
table. Each asserts the next call and the next refresh:
- disconnecting one agent ends only it, including the minute's retry,
and nobody else can, an admin included;
- Disconnect everything ends both connections, the machine token and an
approved device login, and needs no machine token to end a connection;
  - 30 days without a call ends that connection only;
  - a refresh token reused after its minute ends that connection only;
- deactivation ends every credential and pending approval, and a new
connection is refused;
  - reactivation brings none back, and a fresh connection works;
  - plus the two race tests above.
- Red before green: on #846's code, only the disconnect row failed
(`connections.disconnect is not a function`). The stamp rows passed
already, which is the point of the first item under Look at.
- The auth suites (`Endings`, `AgentConnections`, `DeviceLogins`,
`MachineTokens`, `DevicePages`) and the companies `Users` suite pass.
Typecheck and lint pass.
- `pnpm test:rollback-rehearsal --live e4243ff` (release 16, live since
2026-10-22, with #837 and #838) passed:

  ```
  Rehearsing e4243ff → 9358530 → e4243ff → 9358530 on one set of data.
  ▶ Step 3: the live commit (e4243ff) comes back
    passed in 38s
  ▶ Step 4: HEAD (9358530) comes back
    passed in 36s
Exercised rollback paths passed: e4243ff → 9358530 → e4243ff → 9358530,
in 288s.
  ```

Step 4 also fails when it should. A throwaway commit whose `work` check
ignores the stamp fails step 4, naming both members. Its device poll
still answered `410 unknown` and the machine token `401`:

  ```
Step 4 of 4, HEAD (55e7c42) comes back, failed while checking what the
live release ended.
HEAD accepts Jordan Lee's agent connection after the live release
deactivated and reactivated them
HEAD accepts Priya Shah's agent connection after they pressed Disconnect
everything on the live release
  ```

That run also exercised the head's sturdier `press`, which waits for the
new document after a form's POST. CI's `rollback-rehearsal` rehearses
the head against production, which is release 16.

**Surfaces.** ADR-0008 has the decided text word for word. Its device
login and confirmation paragraphs stay as they are, and so do the
dead-row, browser sign-out and human-owner sentences. #838's stamp
sentence now covers agent connections. The decision line adds the
sign-in decision with #846, #847 and #849. `GLOSSARY-MAP.md` carries the
new title. The Auth glossary's *Revocation*, *Device login* and *Your
machines* and Companies' *Deactivation* and *Reactivation* already read
as built, so they're unchanged. `docs/OPERATIONS.md` › Rolling back and
`docs/DEVELOPMENT.md` describe the fourth step. There's no route, CLI,
API or migration change: #853 adds the Disconnect route and #849 the
consent rows.

## Release impact

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

No schema change. One new service method, comments, a test file, the ADR
and the rehearsal.

- **What does a revert leave behind?** Connections disconnected through
the new method keep `revoked_at`. Nothing else is written.
- **Does the release before it still work with that?** Yes. The
rehearsal shows release 16 running on HEAD's data and ending credentials
HEAD then honours.

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:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area area:integrations Company connections and integration implementations 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.

Agent connections: the work credential and its tokens

1 participant