Repository navigation
mcp-apps-cli helper: signin for MCP servers behind OAuth - #13
agentiknet wants to merge 21 commits into
Conversation
VOUCHAVOUCHA is currently in early access and is not enabled for this repository yet. To request access, contact @idosal. VOUCHA has not added a comprehension check to this PR. |
|
Hi @idosal I've put the PR as "Ready for review", happy to discuss it further. |
Thanks for the contribution! Originally, I didn't add this capability because it'd be a different token lifecycle, storage, and governance in comparison to the hosts' native MCP connections. I did specify the changes hosts would need to do to enable it natively. What are your thoughts on adding OAuth support as opt-in with appropriate warnings? |
The helper's connection to a server can't use Claude Code's sign-in, which the helper never reads. For a server the person chooses, the helper can sign in itself, as its own second grant, and only then: - A new setting, "Own sign-in (OAuth)", works like "Structured results from text": empty by default, MCP server names separated by commas. The mod says with each request that names a server whether it is listed; the helper's connection carries its token only for a listed server, and taking a name off the list stops the use at once. - `mcp-apps-cli-helper signin <server>` says what the sign-in is (a second grant with its own client registration, tokens in one file only the person can read, not encrypted, how to end it) and asks to continue, no by default. Without a terminal it refuses unless `--yes` is given. Then: protected resource metadata, dynamic client registration, authorization code with PKCE on a loopback address, and refresh, as rmcp's `auth` feature does them. - `mcp-apps-cli-helper signout <server>` asks the server to revoke the tokens where it publishes a revocation endpoint (RFC 7009), says honestly when it doesn't, and deletes the file. - A session that uses the helper's own sign-in for a server says so once, in the debug log and in the /discover answer. - A 401 from a server that isn't listed no longer points to `signin`; it says the helper doesn't share Claude Code's sign-in. One for a listed server says to sign in again. - One folder for the tokens (~/.cache/mcp-apps-cli/oauth, or MCP_APPS_CLI_OAUTH_DIR), and only https or loopback addresses. Only streamable HTTP, and not a server whose config sets its own Authorization header. Tests: the stand-in server that needs sign-in, in both forms of the connection, now also checks the opt-in, the refusal without a terminal, revocation, and a server without a revocation endpoint.
The README's "Limits" keeps its original sentence about servers that need sign-in as the default behaviour, and adds what the opt-in means before someone turns it on: a second grant, tokens in a file on this machine, not seen by an organisation's MCP sign-in controls, and how to end it. The host's own sign-in stays the recommended way. SECURITY.md describes the mechanism; the compliance table says "no by default" and names the opt-in.
…ncies Generated: cargo for the lockfile, node package/third-party.mjs for the licenses.
1d50ec2 to
3f5b011
Compare
…ase-encrypted tokens (macOS) signin shows a short consent page on a loopback address of its own (random port, token against forged requests, Host and Origin checks, closed after the answer or five minutes): what it means, where to keep the login, Accept or Refuse. Accept goes on to the server's own sign-in in the same tab. The y/N question stays for --no-browser; --yes and the environment variable skip both. The tokens go to the macOS Keychain (Security.framework, called directly), or to a file encrypted with a passphrase (AES-256-GCM, PBKDF2-HMAC-SHA256); a plain file is an explicit option only. No silent fall back. macOS only for now.
|
Human note : yes, I've made a few proposals around it, putting back the PR in draft to fully discuss it. It can be refined, and allow CLI/Browser process to accept/refuse. The best option is probably the browser webview, so that informations can be displayed properly, eventually branded. Terminal y/N is fine but a bitsy unreadable. Can be a flag --no-browser to use one or the other. On storage: the PR currently offers either the macOS Keychain or a file encrypted with a passphrase. My preference would be one encrypted file per access (the OAuth payload), with a single Keychain private key to decrypt them. Happy to switch to that if it works for you. Side note : is there a DESIGN.md or similar for the project ? |
… (serverInfo, RFC 9728 metadata)
…; where logins are kept becomes one global setting The page no longer asks where to keep the login: that is MCP_APPS_CLI_TOKEN_STORE (or --token-store), keychain by default, the same for every server. The page says what is set. The terminal question loses its store choice the same way.
Rewritten as short interface text: who asks, what for, what it will be able to do (permissions in plain words, the server's own names in small print), where the login is kept, and buttons that say what happens. The technical details stay behind the "?".
A login made before MCP_APPS_CLI_TOKEN_STORE changed is still found (the store that is set is tried first, then the others; "file" no longer hides the rest). `signout` revokes and deletes the login in every store that holds it, and a new sign-in revokes and removes the same server's login kept in another store (one that can't be opened, an encrypted file without its passphrase, is left and said).
`signin --no-browser` (and the summary `--yes` prints) draws the same structure as the page, by hand with ANSI colours (off with NO_COLOR, TERM=dumb or no terminal): who asks, the permissions with a check and the server's word in grey, where the login is kept, then "Continue to <server> [y/N/?]"; "?" shows the details. No is the default.
The storage line goes: a quiet lock by the buttons says where the login is kept (closed for the Keychain or a passphrase-locked file, open and amber for a plain file, with a short tooltip), and a gear opens the details (where it is kept and how to change it, separate from Claude Code's own login, signout, the server's links). The terminal gets the same lock line.
…s its own line The server's word, in grey, with the same check as the others.
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical flaws can expose stored credentials and allow authenticated access to persist after opt-out or sign-out.
22 open issues
Restrict metadata and icon requests to trusted network destinations · New Keep the store passphrase out of child process environments · New Cancel stale authenticated connections before waiting on the lock · New Report when credentials load from a different store · New Coordinate refresh-token use across helper processes · New Bound Content-Length and check arithmetic before slicing · New Validate environment-provided passphrases · New Pass sign-in configuration directly instead of mutating the environment · New Retain unreadable credentials when revocation cannot be attempted · New Invalidate cached grants before deleting stored logins · New Revoke replaced credentials after successful sign-in · New Keep Keychain as the default when unavailable · New Apply sign-in opt-in changes to existing app connections · New Label advertised scopes separately from granted permissions · New Invalidate cached discovery when sign-in settings change · New Validate and process callbacks before reporting success · New Validate server transport and URL before consent · New Honor --no-browser when opening the authorization URL · New Allow signout when current server configuration blocks access · New Propagate Keychain access errors instead of treating them as missing · New
And 2 more that still need to be addressed.
What changed in this PR
This draft adds a separate, per-server OAuth login to the Claude Code MCP Apps helper, allowing it to discover apps on protected servers without reading Claude Code’s stored credentials. The design decision in #12 remains open.
Changes:
- Add
signinandsignout, OAuth authorization and refresh, and three token-storage options. - Add browser and terminal consent, server identity metadata, and a per-server opt-in setting.
- Extend tests, dependencies, and documentation for the new authentication flow.
| File | Description |
|---|---|
polyfills/apps/claude-code/SECURITY.md |
Describe grant isolation and token storage. |
polyfills/apps/claude-code/README.md |
Document setup, consent, and limitations. |
polyfills/apps/claude-code/mod/tests/mcp-apps.test.tsx |
Test per-server opt-in propagation. |
polyfills/apps/claude-code/mod/hooks/state.ts |
Add OAuth setting state. |
polyfills/apps/claude-code/mod/hooks/settings.ts |
Parse opted-in server names. |
polyfills/apps/claude-code/mod/hooks/helper.ts |
Forward opt-in and log authenticated discovery. |
polyfills/apps/claude-code/mod/.claude-plugin/plugin.json |
Expose Own sign-in configuration. |
polyfills/apps/claude-code/helper-rs/tests/pty-run.py |
Support terminal consent tests. |
polyfills/apps/claude-code/helper-rs/tests/oauth-server.mjs |
Provide a local OAuth/MCP stand-in. |
polyfills/apps/claude-code/helper-rs/tests/gate.rs |
Exercise consent, storage, and sign-out. |
polyfills/apps/claude-code/helper-rs/src/vault.rs |
Implement Keychain, encrypted, and plaintext stores. |
polyfills/apps/claude-code/helper-rs/src/store.rs |
Extract atomic JSON persistence. |
polyfills/apps/claude-code/helper-rs/src/server.rs |
Apply opt-in and report authentication use. |
polyfills/apps/claude-code/helper-rs/src/oauth.rs |
Implement OAuth flows and CLI commands. |
polyfills/apps/claude-code/helper-rs/src/mcp.rs |
Integrate authenticated connections and error hints. |
polyfills/apps/claude-code/helper-rs/src/main.rs |
Dispatch sign-in and sign-out commands. |
polyfills/apps/claude-code/helper-rs/src/consent.rs |
Render browser consent pages. |
polyfills/apps/claude-code/helper-rs/src/ask.rs |
Render terminal summaries and prompts. |
polyfills/apps/claude-code/helper-rs/src/about.rs |
Fetch server identity and advertised permissions. |
polyfills/apps/claude-code/helper-rs/Cargo.toml |
Enable OAuth and encryption dependencies. |
polyfills/apps/claude-code/helper-rs/Cargo.lock |
Record the updated dependency graph. |
polyfills/apps/claude-code/docs/COMPLIANCE.md |
Describe optional OAuth support and verification limits. |
Review effort: Max
| if !crate::oauth::allowed(address) { | ||
| return None; | ||
| } | ||
| let response = http.get(address).header("accept", "application/json").send().await.ok()?; |
There was a problem hiding this comment.
Fixed in a826651. Before consent, the helper now fetches only from the configured server's own origin (resource metadata, including the address a 401 names, and the icon). The one request that may leave it is the authorization server's metadata: https only, and only if every address the name resolves to is public (loopback, private, link-local, CGNAT and the other reserved ranges are refused, IPv4-in-IPv6 forms included); that request is pinned to the addresses that were checked. No redirect is followed, as before. After consent, discovery goes through rmcp's AuthorizationManager::new, which applies its own private-address filter. Test: what_a_server_names_is_fetched_only_from_its_origin_or_a_public_https_address.
| /// passphrase-locked file is as safe as the Keychain (the same strong encryption), so it is | ||
| /// green too; only the plain file is a warning. |
There was a problem hiding this comment.
Fixed in df04b5a. The helper takes MCP_APPS_CLI_PASSPHRASE out of its own environment first thing in main, before any thread or process is started, and keeps it in memory, so stdio MCP servers, Chrome and the browser launcher are no longer handed it (test: the_passphrase_is_not_handed_to_the_processes_the_helper_starts). The "same strong encryption / as safe as the Keychain" wording is gone from the code and the page, and SECURITY.md and the README now say the helper keeps the passphrase while it runs and that any other program started from the same environment (Claude Code's own MCP servers included) can still read it there.
| if let Some((client, _)) = self.open.lock().await.remove(server) { | ||
| client.cancellation_token().cancel(); |
There was a problem hiding this comment.
Fixed in fd88e75. A change of the setting bumps a per-server counter while the list is held; a connection being made subscribes to it and is dropped in a select! as soon as it changes, so the setter no longer waits behind a slow attempt and a connection made under the old choice is never kept. Test: a_connection_being_made_is_dropped_when_the_sign_in_setting_changes (a server that never answers).
| if !allowed(url) { | ||
| return Ok(None); | ||
| } | ||
| let Some(place) = vault::kept(name, url) else { return Ok(None) }; |
There was a problem hiding this comment.
Addressed in fd88e75, by reporting rather than migrating. Still reading a login made before the setting changed is deliberate (a3c4808: otherwise changing the setting silently signs the person out), but it is no longer silent: /discover returns the store the login was actually read from when it differs from the one that is set, and the mod shows it in a toast with the command that moves it (signin <server> again, which revokes and removes the old copy). Covered in changing_the_store_setting_keeps_one_login_and_signout_removes_every_copy. I did not migrate automatically: moving tokens between stores without the person asking seemed worse than saying it.
| let mut manager = AuthorizationManager::new(url).await.map_err(|e| anyhow!("{e}"))?; | ||
| manager.set_credential_store(TokenStore { place }); | ||
| if !manager.initialize_from_store().await.map_err(|e| anyhow!("{e}"))? { |
There was a problem hiding this comment.
Fixed in b7baf37. The credential store now implements rmcp's acquire_refresh_guard with a cross-process lock (a lock file beside the logins, one per server and address), held from before the kept tokens are read until the refreshed ones are saved. A second helper waits, then reads what the first one wrote instead of spending the same refresh token. signout holds the same lock. Not covered by an automated test (it needs two helpers racing a refresh); the lock itself is std::fs::File::lock.
| } | ||
| signin(name, &url, kind, |address| { | ||
| println!("Open this address to sign in to {name}:\n{address}"); | ||
| if std::env::var_os("MCP_APPS_CLI_NO_BROWSER").is_none() { |
There was a problem hiding this comment.
Fixed in 1b8b705. --no-browser (like MCP_APPS_CLI_NO_BROWSER) now also keeps the browser closed for the authorization URL, which is printed. No automated test: it would have to assert that no browser was launched.
| let (name, url) = target(&args, words)?; | ||
| // Wherever it is kept: a login made before the store setting changed counts too. | ||
| let places = vault::all_kept(&name, &url); |
There was a problem hiding this comment.
Partly fixed in b7baf37, and here is why only partly. signout <server> --url <address> now reaches a login whose server was removed, disabled, moved to another URL or put behind a policy: it does not consult the configuration and sends nothing (local deletion only, and it says the grant must be removed in the server's connected apps), and the error for an unresolvable server names that flag. What I did not do is locate logins from saved identity metadata: entries are keyed by a hash of name and URL, and Keychain items aren't enumerated, so finding them without the address would mean adding an index of servers and URLs on disk, which felt like more stored state than this opt-in feature should carry. Nothing is sent with --url on purpose: the address is no longer one the configuration vouches for. Test: same as the replaced-login one.
| pub fn exists(&self) -> bool { | ||
| match self { | ||
| Place::File(path) | Place::Encrypted(path, _) => path.is_file(), | ||
| Place::Keychain(_) => matches!(self.read(), Ok(Some(_))), |
There was a problem hiding this comment.
Fixed in a1dce5c. exists() returns a Result: not-found is false, any other Keychain status is an error, and all_kept()/kept() pass it on. signout then fails with the Keychain's error instead of "nothing to delete", and a session's connection fails instead of quietly using an older file-backed login. No automated test (it needs a Keychain that refuses access).
| unsafe { std::env::remove_var("MCP_APPS_CLI_TOKEN_STORE") }; | ||
| assert_eq!(asked(&words("h signin demo")).unwrap(), None); |
There was a problem hiding this comment.
Fixed in a1dce5c. The parsing is now a pure function that takes the environment's value as an argument, and the test no longer touches the process environment. The sign-in test in mcp.rs still sets the variable (it needs the file store for the whole flow) and is now the only test that does.
| try: | ||
| os.waitpid(pid, 0) | ||
| except ChildProcessError: | ||
| pass | ||
| sys.stdout.buffer.write(out) |
There was a problem hiding this comment.
Fixed in e63ee67. The runner polls the child while reading, and at the deadline kills the command's process group, reaps it and exits with 124; otherwise it exits with the command's own status, which the test now checks. Checked by hand with a command that sleeps past a shortened deadline.
…nly from its own origin What a server publishes about itself is read before the person has agreed to anything, from addresses the server names. Those requests now go to the server's own origin (its resource metadata, its icon), and, for the authorization server's metadata alone, to another origin over https whose name gives only public addresses: never this machine, a private network, a link-local or other reserved address. That request connects to the addresses that were checked, so a second answer from the name service changes nothing. No redirect is followed, as before.
…hat the helper starts The helper takes MCP_APPS_CLI_PASSPHRASE out of its own environment first thing, before it starts anything, and keeps it in memory: a stdio MCP server, Chrome or the person's browser is no longer handed it. `signin` passes the passphrase to where the tokens are kept directly, instead of writing it back to the environment of a process that already has threads. A passphrase from the environment is held to the same minimum length as one typed at the prompt. The page, the README and SECURITY.md no longer set the encrypted file beside the Keychain: they say the helper keeps the passphrase while it runs, and that any other program started from the same environment can read it there.
…ain file is chosen for the person A Keychain that refuses to be looked in was taken for "no login there": `signout` could say there was nothing to delete, and a session could pick up an older login from a file instead. The error is now passed on. Without a store setting the Keychain is the choice everywhere; where there is none, `signin` refuses and says how to ask for another store, where it used to pick the plain file on Linux and Windows without being asked. The test of the store setting reads the environment's value as an argument, so it no longer changes a variable another test reads.
…says why `signout` deleted the tokens whatever came of the revocation: a login it could not read (an encrypted file without its passphrase) was reported as "no way to revoke" and deleted, leaving the grant alive at the server with nothing left to end it with. Now a login that can't be read, or that the server didn't revoke, is left in place and said, and `signout` fails; `--local` deletes without asking the server. `signout <server> --url <address>` reaches the login of a server that is no longer configured or allowed (nothing is sent to it). Signing in again into the store that already holds a login revokes the one it replaces, which used to stay alive at the server. A refresh and `signout` hold the same lock, on a file beside the logins: a helper that is refreshing can't write a token back after `signout` deleted it, and two sessions' helpers no longer spend the same rotating refresh token (the second waits, then reads what the first wrote). A running helper reads the kept login for each request, so it stops with the deletion: a test now holds that.
…elper with any request The mod said whether a server was listed only with the requests that name one (/discover, /prewarm, /open): an app that was already open kept its signed-in connection for its replies after the server was taken off the list. The mod now sends the list with every request, and the helper applies it before the route. In the helper, a change no longer waits for a connection that is being made under the old choice (it held the lock): that attempt hears of the change and is dropped. What the server listed under the old choice is forgotten, in the helper and in the mod, since a signed-in server may list other apps. A login still read from a store other than the one that is set (a plain file kept from before the setting moved to the Keychain, say) is used as before, and now said, in a toast, with the command that moves it.
…turn, and small requests The return from the server's sign-in page is heard only with the `state` this sign-in sent. Any GET to /callback used to be answered "You're connected", a denial included, before anything was checked, and a request from elsewhere on the machine could use up the wait and end the sign-in. Now such a request gets a 400 and the wait goes on; the tab is told it worked after the code was exchanged and the tokens kept, and otherwise what went wrong. A declared Content-Length is bounded (64 KB) and added with a check: a huge one made an inverted slice range and, with panic=abort, ended `signin`. `signin` refuses a server whose sign-in the helper's connection would never use (sse, an Authorization header of the person's own, plain http elsewhere) before it asks or sends anything; the terminal path used to contact the server first. `--no-browser` now also keeps the browser closed for the server's own page, whose address is printed.
…he server can allow
The list under "It will be able to:" is the server's published `scopes_supported`
(the authorization server's when the resource names none): what it can allow, not
what this sign-in asks for or is given. The heading now says so ("<server> can
allow it to:"), and a line under the list says the server's own page, next, is
where what it gets is decided. Same words in the terminal's summary.
…hangs pty-run.py stopped reading after 30 seconds and then waited for the command with no limit, so a prompt that hung held the test for ever. It now kills the command and its process group at the deadline and exits with 124; otherwise it exits with the command's own status, which the test checks.
|
Hi Ido, I pushed fixes for the Copilot review: all 22 comments are addressed and the 3 security issues fixed. One is only partly addressed, I explain why in its thread. Thanks, |






Closes #12. Draft: the design question in #12 is still open; please don't merge before it is answered.
The helper can sign in to an OAuth-protected MCP server itself, as an opt-in per server, after a short consent page (or the same summary in the terminal) that shows who asks, what it can do and where the login is kept. macOS only for now.
What it looks like now
How to test
THIRD_PARTY_LICENSES.txtis most of the diff; it is regenerated in its own commit.🤖 @agentproto-bot — PR · session
sess_0df2bb5e(agentpolyfill-consent-metadata-27-11) · claude-code / subscription · auth-profileClaude Subs Agentik· modelclaude-sonnet-5-5· supervisorsess_790c58fe· 382 in / 184.5k out · $7.5804 (daemon) · hostmac.home· cwddefault/AgentPolyfill