Skip to content

MCP OAuth 2.1 + PKCE flow (fixes Replicate connect) - #134

Merged
FMXExpress merged 2 commits into
mainfrom
claude/mcp-catalog-stdio
Jun 5, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/mcp-catalog-stdio

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Fixes the [warn] mcp[replicate] connect failed: initialize failed failure: mcp.replicate.com is OAuth-only and rejects raw REPLICATE_API_TOKEN with invalid_token / Invalid token format. The catalog entry handed it the wrong shape and never had a chance.

Implements the MCP Authorization spec end-to-end so OAuth-only remote MCP servers actually work.

New units

  • PasClaw.Crypto.Random — cross-platform CSPRNG (/dev/urandom on POSIX, CryptGenRandom on Windows). PKCE verifiers + state nonces need real entropy.
  • PasClaw.MCP.OAuth — full flow: RFC 9728 protected-resource discovery → RFC 8414 authorization-server discovery → RFC 7591 dynamic client registration (public client, token_endpoint_auth_method=none) → PKCE-S256 → loopback callback TIdHTTPServer on 127.0.0.1:0 → token exchange → silent refresh on expiry. Tokens persist to <home>/oauth/<server>.json.

Wiring

  • PasClaw.MCP.HttpClient.RoundTrip — when the configured FAuth is empty, fall back to GetAccessToken(FName). On 401 with stored tokens, force-refresh once and retry.
  • PasClaw.MCP.Catalog — TMCPCatalogEntry gains RequiresOAuth: Boolean; Replicate flipped to RequiresOAuth=True with empty EnvVar/AuthFmt.
  • PasClaw.Cmd.MCP — new pasclaw mcp auth <name> subcommand drives the flow. mcp install for OAuth entries writes an empty Args slot and prints the "run mcp auth" hint.

Usage

pasclaw mcp install replicate     # writes the entry, points at `mcp auth`
pasclaw mcp auth replicate        # opens browser, runs PKCE, persists tokens
pasclaw mcp test replicate        # tokens auto-loaded; refresh on expiry

Test plan

  • make clean && make — clean build (FPC).
  • make smoke — green.
  • pasclaw mcp catalog shows Replicate as (no auth) with the new "OAuth-only — run pasclaw mcp auth replicate" desc.
  • pasclaw mcp auth help renders.
  • End-to-end OAuth flow with a real browser + the live mcp.replicate.com — needs a desktop session, can't be exercised from this sandbox.
  • Refresh-on-401 path with an expired access token.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

mcp.replicate.com is the v1 case: it advertises RFC 9728 protected-
resource metadata, requires OAuth-issued access tokens, and rejects
raw REPLICATE_API_TOKEN with "invalid_token / Invalid token format".
The previous catalog entry handed it the raw token via Bearer and
never had a chance.

Implements the MCP Authorization spec end-to-end:

  1. PasClaw.Crypto.Random — cross-platform CSPRNG (/dev/urandom on
     POSIX, CryptGenRandom on Windows). PKCE verifiers + state nonces
     need real entropy; System.Random would be insufficient.

  2. PasClaw.MCP.OAuth — discovery + dynamic client registration +
     PKCE (S256) + loopback callback server + token exchange + silent
     refresh.

       DiscoverEndpoints     GET /.well-known/oauth-protected-resource
                             then /.well-known/oauth-authorization-server
       RegisterClient        POST registration_endpoint (public client,
                             token_endpoint_auth_method="none")
       TLoopbackServer       TIdHTTPServer on 127.0.0.1:0 with one
                             /cb handler — captures code + validates
                             state, closes the browser tab with a
                             "you can return to the terminal" page
       RunOAuthFlow          orchestrates the above + shells out to
                             xdg-open / open / start to launch the
                             browser; blocks ≤ 3 minutes for callback
       GetAccessToken        silent refresh when within 60s of expiry;
                             called by the HTTP MCP client per request
       ForceRefresh          POST grant_type=refresh_token; called by
                             the HTTP client on a 401

     Tokens persist to <home>/oauth/<server>.json as JSON; refresh
     rotates them in place. Issuer + endpoints are cached alongside
     so refresh doesn't need to re-do discovery.

  3. PasClaw.MCP.HttpClient — ResolveAuth() falls back to
     GetAccessToken(FName) when the configured FAuth header is empty.
     On 401 with an empty FAuth and stored tokens, force one refresh
     and retry; logs and surfaces the failure if refresh fails.

  4. PasClaw.MCP.Catalog — TMCPCatalogEntry gains RequiresOAuth:
     Boolean. Replicate flipped to RequiresOAuth=True with empty
     EnvVar/AuthFmt; the description now points the user at
     `pasclaw mcp auth replicate`.

  5. PasClaw.Cmd.MCP — new `pasclaw mcp auth <name>` subcommand
     drives the flow. `mcp install` for OAuth entries writes an empty
     Args slot and prints the "run mcp auth" hint.

Smoke + clean build pass on FPC. Full interactive verification
needs a real browser session (xdg-open + listening loopback port)
which doesn't survive this sandbox.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 94e816de75

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/pkg/mcp/PasClaw.MCP.OAuth.pas Outdated
Comment on lines +285 to +287
i := Pos('/', Result);
if i > 0 then Result := Copy(Result, 1, i - 1);
Result := Scheme + Result;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve the resource path during OAuth discovery

For MCP URLs with a path, such as the catalog's https://mcp.replicate.com/mcp, this strips /mcp and makes discovery request the origin-level /.well-known/oauth-protected-resource. RFC 9728 requires inserting /.well-known/oauth-protected-resource between the host and the existing path, so path-scoped servers publish at /.well-known/oauth-protected-resource/mcp; those servers will fail pasclaw mcp auth before the browser flow starts. See RFC 9728 section 3.1: https://www.rfc-editor.org/rfc/rfc9728.html#section-3.1

Useful? React with 👍 / 👎.

Comment thread src/pkg/mcp/PasClaw.MCP.OAuth.pas Outdated
Comment on lines +668 to +670
if LoadTokens(ServerName, ExistingTokens, _Err) and
(ExistingTokens.ClientId <> '') and (ExistingTokens.RegEndpoint = RegEp) then
ClientId := ExistingTokens.ClientId

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Re-register when the loopback redirect URI changes

When a user runs pasclaw mcp auth <name> again, this reuses the previously registered client_id, but the loopback server below chooses a fresh ephemeral port and therefore a different redirect_uri. Dynamic client registration submitted the old exact redirect URI, so OAuth servers that validate registered redirect URIs will reject subsequent authorization attempts; either persist/reuse the same redirect URI or register a new client for the new port.

Useful? React with 👍 / 👎.

…r auth

Two Codex P2s on the OAuth backend:

1. RFC 9728 §3.1 says the well-known URI is constructed by inserting
   /.well-known/oauth-protected-resource between authority and path —
   so a resource at https://host/p1/p2 publishes its metadata at
   https://host/.well-known/oauth-protected-resource/p1/p2. The old
   code stripped the path and only ever requested the origin-level
   URL, which fails discovery for path-scoped servers.

   Build both URLs in ProtectedResourceMetadataURLs and try the
   path-aware one first, falling back to origin-only on 404. Replicate
   serves at origin-only today; the fallback keeps it working.

2. The auth flow reused the previously registered client_id even
   though every run binds a fresh ephemeral loopback port — and
   redirect_uri is part of what the auth server validates against
   the registration. A second `pasclaw mcp auth <name>` would 400
   with redirect_uri_mismatch.

   Always register a fresh public client per auth run. The client_id
   then matches the redirect_uri we're about to use. RFC 7591 public
   clients have no secret and are anonymous identities, so the cost
   is negligible.

Reported by Codex review on PR #134.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants