Skip to content

feat(mcp): add direct MCP OAuth dynamic client registration - #1413

Merged
jhrozek merged 21 commits into
mainfrom
impl/direct-mcp-dcr
Sep 15, 2026
Merged

jhrozek merged 21 commits into
mainfrom
impl/direct-mcp-dcr

Conversation

@jhrozek

@jhrozek jhrozek commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a direct (non-broker) MCP OAuth client mode that uses RFC 7591 Dynamic
Client Registration, so a desktop operator can connect to a protected
Streamable HTTP MCP server without a ToolHive broker or manually provisioned
client ID/secret. The profile still requires explicit trusted operator identity,
issuer, credential-store, and network-policy configuration.

  • New client: {mode: dcr, dcr: {}} form for a direct/global MCP OAuth
    profile, separate from the existing broker/preregistered/CIMD forms.
  • Discovers RFC 9728 protected-resource + authorization-server metadata,
    dynamically registers a public client, then runs the existing
    authorization-code/PKCE loopback login flow.
  • v1 is no-refresh by design: only scopes: [openid] and
    request_refresh_token: false are accepted; an unsolicited refresh token
    fails login before persistence. Resource-bound public-client refresh is
    deferred to Support resource-bound public-client OAuth refresh for direct MCP DCR #1355.
  • Durable client registration and the access grant are separate,
    generation-bound, CAS-protected records in the existing encrypted local
    credential store.
  • --retry-dcr-registration retries an identity-matching pending registration;
    --reset-dcr-registration deliberately replaces a valid ready registration.
    Pending identity drift requires restoring the matching configuration before
    retry. Corrupt state remains fail-closed and is preserved for operator/support
    diagnosis; neither recovery flag repairs it or revokes an upstream client.
  • Preserves all existing OAuth controller hardening: DNS-pinned/no-proxy
    egress, exact-issuer-origin validation, redacted errors, and rejection of
    the SDK's Basic-auth probe for the restored public client (only the
    parameter-form fallback with the exact client_id is admitted).
  • See docs/adr/0325-direct-mcp-dcr.md and
    docs/acceptance/direct-mcp-dcr.md for the full decision record and
    acceptance criteria.

Verification

  • Affected DCR package tests passed.
  • task docs, task site:build, task lint, and the offline mecademo passed.
  • Repeat panel review completed; the implementation fixes are at 8ed0a3fb8.
  • Manual live qualification against connector-gateway.stacklok.dev/gw/mcp
    with real browser consent previously verified registration, login, tool
    discovery/call, and credential reuse across a mecatui restart. Post-expiry
    login-required and explicit re-login/registration-reuse verification remains
    a human-run acceptance step and must be confirmed before merge.

Fixes: #1265

🤖 Generated with Claude Code and Mecatl

@jhrozek
jhrozek force-pushed the impl/direct-mcp-dcr branch from ea968bc to dcf2f45 Compare September 14, 2026 11:09

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Panel review

Reviewed dcf2f45926e10fdb9c8badb1a40015730e4822bb against merge base d25313767befc803277e38d658193844d6d150ab across spec, standards, test adequacy, security, architecture, duplication, library reuse, and UX. Disputed security/reuse findings received an independent follow-up. No local tests or linters were run; verification used the existing CI results.

Before approval

  • Reconcile the documented registration-reset procedure with identity-key lookup. Changing issuer/principal/resource makes reset look up a missing record, while ordinary login can bootstrap another registration. The inline comment gives the trace.
  • Fix and regenerate the canonical configuration reference: direct DCR rejects the discovery_url it currently calls required.
  • Complete the acceptance plan's outstanding live expiry/login-required and explicit re-login/registration-reuse qualification. The reported initial login, tool use, and pre-expiry restart evidence is useful; this is not a claim that all live qualification is missing. Please record the remaining safe results before landing.

The runtime exact-issuer gap also deserves correction: preparation checks byte equality, but the SDK's later challenge-time discovery tolerates a trailing-slash variant. It is classified as important rather than a high-severity exploit because the same-origin controls constrain exposure.

Reuse: this is not a second MCP client

The direct-client choice is reasonable. Login still uses mcp.Connect, the existing OAuth controller and callback runtime, and SDK discovery, oauthex.RegisterClient, PKCE, and token exchange. The new code principally owns durable registration, pending evidence, encrypted CAS publication, and generation-bound grants. The installed SDK does not expose the durable registration lifecycle needed here; ToolHive's DCR resolver is not a drop-in replacement for these CAS/recovery semantics. I am not asking for a broker rewrite or a generic OAuth persistence framework.

We checked the apparent duplicates rather than assuming they were removable. The DCR token envelope deliberately excludes refresh_token; reusing the generic envelope changes strict decoding. Raw client_id_issued_at capture preserves omitted versus explicitly supplied epoch-zero semantics that the SDK representation loses. Keep those distinctions.

Scope and configuration

The PR summary says the operator needs only an endpoint URL and closes #1265, but the shipped profile still requires profile, principal, issuer, credential-store/key selection, and network policy. This matches the amended acceptance contract, so it is not a blocker against that contract. It is nevertheless not endpoint-only onboarding. Please narrow the summary/closure claim to 'no manually provisioned client ID or secret', or explicitly leave endpoint-only setup as remaining work. The summary also says recovery flags cover corrupt state, whereas corrupt state deliberately rejects both flags.

For a follow-up desktop flow, a URL-first setup could discover and present the authority for approval, derive stable local identity defaults, reuse host-level credential custody, and persist/pin the approved issuer. Do not silently accept issuer drift or register during startup/reconnect.

UX/UI direction — non-blocking design follow-up

A local TUI should reuse app.LoginMCPWithOptions and oauthlogin.Runtime, not implement OAuth again. Separate Reconnect (existing credentials, no consent), Sign in again (reuse registration), Retry registration… (unknown outcome, possible orphan), and Replace registration… (explicit local invalidation, no upstream revocation). A generic Retry button would conflate materially different operations. Remote TUI support needs an explicit server-side authority boundary; broker enrollment controls are not interchangeable with global direct credentials.

The accepted contract explicitly defers a new mecatui command, so I am not blocking on a button. The immediate usability gap is that the MCP overlay cannot explain sign-in-required state, and its inventory refresh does not reconnect. Show the safe category and exact CLI/restart remedy even if interactive login remains deferred. Also disclose in login help that initial DCR login creates a durable upstream client before consent.

Test adequacy and standards

The encrypted reload, real SDK exchange, MCP invocation, and deterministic CAS fixtures are substantial. The inline comments identify the weaker identity-mismatch oracle and reset/retry CLI seam. Also, TestDirectMCPDCR_Scenario2_RestartRestoresRegistrationGrantAndReadTool in internal/adapter/mcp/oauth_dcr_test.go:1090 uses an in-memory store and only reconstructs the controller; the stronger encrypted-store/app/tool proof exists elsewhere. Please make the AC trace name that stronger proof or make the named test own it.

The nonexistent design citation is noted inline. The introductory OAuth YAML at user-docs/features/mcp-oauth-and-credentials.md:33-48 is also stale, but predates this diff and is not independently a PR blocker. The accepted no-refresh amendment, encrypted credential-store reuse, and conservative pending-before-callback-bind behavior are deliberate contract choices, not additional defects.

CI — separate from review blockers

At this head, root-a/docs fail on duplicate ADR 0328 files outside this diff. Root-b times out in TestSDKServerEnablers_Scenario8_LifetimePipeIsQuietOnCleanShutdown, also outside the DCR changes; flakiness is suspected, not established. The inspected DCR adapter/app/CLI/config/callback packages passed under race. Please reconcile the PR body's 'green' verification claim with current checks. CI failure alone is not the reason for requesting changes.

The two concrete recovery/reference defects and the outstanding required qualification are the approval blockers; the remaining comments distinguish important fixes from optional design follow-up.

Comment thread internal/adapter/mcp/oauth_dcr.go Resolved
Comment thread internal/adapter/permconfig/schema.go Resolved
Comment thread internal/adapter/mcp/oauth.go Resolved
Comment thread cmd/mecated/mcplogin_test.go Resolved
Comment thread cmd/mecated/mcplogin.go Resolved
Comment thread internal/app/mcplogin.go
}
cfg.OAuth = &prepared
return loginMCPAuthorize(cfg, func(authorize oauthlogin.AuthorizeFunc) error {
return runtime.AuthorizeWithCallbackPath(ctx, cfg.OAuth.Issuer, callbackPath, authorize)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Non-blocking UX follow-up — this is the seam a local TUI should reuse.

The shared LoginMCPWithOptions/callback runtime is the right place for registration policy; please do not add another OAuth implementation for mecatui. Today login-required is emitted through composition diagnostics, while the MCP overlay shows source inventory and its refresh action only re-reads that inventory (cmd/mecatui/ui/mcp.go:231-251,673-692). It cannot tell the operator that authentication is why tools are unavailable or reconnect after CLI login.

Even with the accepted new-TUI-command deferral, expose an honest sign-in-required state and the CLI/restart remedy. A later local UI should distinguish Reconnect, Sign in again, Retry registration (possible orphan), and Replace registration (no upstream revocation), with confirmation for the registration mutations. Do not make generic refresh implicitly launch consent or repeat an uncertain registration POST; remote TUI use needs its own server-side authorization boundary.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed this is design follow-up rather than a blocker on this PR, and it isn't addressed by this commit. I'm leaving this thread open rather than resolving it, since the honest sign-in-required overlay state and reconnect action you describe are real gaps worth tracking — let me know if you'd like a follow-up issue filed for it, or if it should just stay open here until the new-mecatui-command work picks it up.

Comment thread docs/design/IMPLEMENTATION-NOTES.md Resolved
@jhrozek
jhrozek force-pushed the impl/direct-mcp-dcr branch from dcf2f45 to 9f054d4 Compare September 14, 2026 19:12
@jhrozek

jhrozek commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. Pushed a rebase onto current main plus the fixes at 7bf4825a7 (rebased content of what was locally 5e47df755) and a follow-up test fix at 9f054d4e6. Replied inline on each thread; summary here:

Blockers — both fixed:

  • Reset/identity-key lookup: the registration record is now keyed by DCR server name alone, not the profile/principal/resource/issuer tuple, so --reset-dcr-registration/--retry-dcr-registration find and act on drifted records instead of missing them. A new OAuthDCRRecoveryResetRequired sentinel distinguishes this from corrupt state.
  • Config schema/reference for discovery_url: doc comments and the generated user-docs/reference/configuration.md now correctly distinguish direct vs. broker DCR, pinned by a new test.

Important findings — all fixed: exact-issuer validation now also covers runtime SDK discovery (not just prep time), the acceptance proof asserts the real diagnostic string instead of relying on an unknown-tool side effect, reset/retry are now exercised through the real app.LoginMCPWithOptions continuation, and the corrupt-state message names a concrete remedy instead of a dead end.

Non-blocking (TUI reuse follow-up): left that thread open — agreed it's real, out of scope for this fix, and better tracked separately; said so inline.

Not addressed by this commit, as you flagged: the outstanding live expiry/login-required and explicit re-login/registration-reuse qualification is a human-run task, not something this diff can satisfy. Recording that as still outstanding before merge, per your note.

One more thing worth surfacing: while verifying this commit I found it had broken TestADR_0325_DCRResetAndRetryCLI in cmd/mecated/mcplogin_test.go — that test still hardcoded the pre-rename identity-tuple key, so it silently mismatched the new lifecycle-key scheme and three subtests failed with "record not found". Fixed in 9f054d4e6. go build ./... and the targeted package tests (internal/adapter/mcp, internal/app, internal/cliconfig, cmd/mecated, internal/adapter/permconfig) are green at the current head.

@jhrozek jhrozek linked an issue Sep 14, 2026 that may be closed by this pull request

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Panel re-review

Reviewed current head 9f054d4e6a5ed77d780943e5bbd22c8ac620b05c against base 0d0cd989c04fb9bc1180603bfa3736990c533116, and separately traced every finding from my review of dcf2f45926e10fdb9c8badb1a40015730e4822bb. CI is green. I did not rerun local tests or linters.

Before approval

  1. Pending identity drift still crosses the retry boundary. PrepareOAuthDCRLogin computes identityMatches, but enforces it only for ordinary reuse. --retry-dcr-registration accepts a pending record for another profile/principal/resource/issuer, CAS-replaces its evidence with the new identity, and may create another upstream client. TestOAuthDCRPendingBindingMismatchRetriesExplicitly currently pins that behavior. This contradicts the accepted rule that retry is valid only for an identity-matching pending record (docs/acceptance/direct-mcp-dcr.md, pending-state step 5 and the CLI contract). Reject mismatched-pending retry without mutation or network/browser side effects, and preserve the old record.

  2. The durable lifecycle record exceeds its exact approved schema. oauthDCRRecord persists optional failure_category, but the acceptance plan's exact lifecycle table does not define that field. Strict unknown-field decoding makes this a durable compatibility commitment. Remove it or obtain an explicit contract amendment defining allowed values, lifecycle, retention, and compatibility.

  3. The required live qualification remains incomplete. The plan and PR body still say post-expiry login-required and explicit re-login/registration reuse are in progress. AC3.1 and Definition of Done require that separate human-run evidence before merge; green CI cannot replace it.

  4. The prior four-field drift regression request is only partially met. The end-to-end reset/upstream-count/read proof changes profile; the focused unit proof changes principal. Resource and issuer do not receive the requested configured-drift → ordinary refusal → reset → upstream-count continuation matrix. Please complete that proof for profile, principal, canonical resource, and exact issuer.

Prior findings

Addressed: direct-vs-broker schema/reference wording, exact challenge-time issuer validation, safe reset-required diagnostic, real LoginMCPWithOptions reset/retry continuation, and the bad implementation-note citation.

Still needs cleanup:

  • The PR summary still claims endpoint-only onboarding and that reset/retry cover corrupt state; neither is true for the shipped configuration/recovery contract.
  • The owning user guide calls corrupt state only “repair-only”; unlike the generated reference and CLI error, it does not give the supported preserve-records/redacted-support procedure.
  • The acceptance trace names TestDirectMCPDCR_Scenario2_RestartRestoresRegistrationGrantAndReadTool under internal/app, but that name exists only in the adapter test with an in-memory store. Point the trace at the real encrypted profile-loader/app/tool proof or add the named proof at the claimed seam.
  • AC1.6 names TestADR_0325_DirectDCRChallengeIssuerBinding, which does not exist. The runtime mismatch behavior is covered under another test name; repair the executable trace.
  • The TUI sign-in-required/reconnect affordance remains an accepted non-blocking follow-up.

Panel

  • Spec: blocker — required live qualification is outstanding.
  • Standards: blocker — exact durable schema drift; important — stale/missing named AC proof.
  • Test adequacy: blockers — cross-identity pending-retry test encodes the opposite contract and the requested four-field matrix remains incomplete; important — encrypted restart trace and configuration-reference oracle remain weaker than claimed.
  • Domain: blockers — cross-identity retry (security + architecture, cross-confirmed) and undeclared durable schema field; advisory — the three identical length-framed SHA-256 key encoders are now a Rule-of-Three cleanup opportunity, not a merge blocker.

PANEL: ship_blockers=6 important=3 advisory=1 reviewer_failures=0

jhrozek and others added 20 commits September 15, 2026 10:58
Add explicit registration reset/retry login flags, redacted operator remedies, and the no-refresh qualification procedure.

Co-Authored-By: mecatl <[email protected]>
Keep the explicit callback lifecycle while satisfying the repository cyclomatic-complexity gate.

Co-Authored-By: mecatl <[email protected]>
Keep the plan in progress until its missing named proofs, resource audit, review, and live qualification are complete.

Co-Authored-By: mecatl <[email protected]>
Validate the current generation grant before registration reset and adopt only a strictly matching ready winner after uncertain registration outcomes. Pin the pending-CAS race matrix with deterministic store and HTTP barriers while retaining the authorization hardening from R01.

Co-Authored-By: mecatl <[email protected]>
Harden persisted DCR validation and explicit expiry reauthorization. Exercise reset and retry through the public CLI boundary, and restore candidate documentation status pending final qualification.

Co-Authored-By: mecatl <[email protected]>
Classify uncertain registration outcomes durably, keep server-advertised registration scopes out of local authority, and make operator recovery remedies match the recorded failure stage.

Co-Authored-By: mecatl <[email protected]>
Co-Authored-By: mecatl <[email protected]>
TestADR_0325_DCRResetAndRetryCLI still hardcoded the pre-rename
identity-tuple key domain and fields. The registration record is now
keyed only by server name under the renamed
mecatl/mcp/oauth-dcr-lifecycle-key/v1 domain, so the test's lookup
never matched what PrepareOAuthDCRLogin actually wrote, and three
subtests failed with "record not found".

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@jhrozek
jhrozek merged commit d34f04e into main Sep 15, 2026
36 checks passed
@jhrozek
jhrozek deleted the impl/direct-mcp-dcr branch September 15, 2026 09:41
This was referenced Sep 15, 2026
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.

Support resource-bound public-client OAuth refresh for direct MCP DCR Direct Streamable HTTP MCP client with discovery and DCR

2 participants