Skip to content

Fix Mastra auth flow and Better Auth base URL#10

Merged
teallarson merged 2 commits intomainfrom
teallarson/fix-mastra-auth
Mar 4, 2026
Merged

Fix Mastra auth flow and Better Auth base URL#10
teallarson merged 2 commits intomainfrom
teallarson/fix-mastra-auth

Conversation

@teallarson
Copy link
Copy Markdown
Collaborator

Summary

  • Mastra OAuth broken: The connect route was using mcpClient.listTools() (Mastra's MCPClient) to trigger OAuth, but Mastra tries both Streamable HTTP and SSE transports before calling redirectToAuthorization — unreliably saving client registration and PKCE verifier. The callback's auth() call then had no state to work with, so tokens were never stored. Plan route got 401 "Missing Authorization header".
    • Fix: added initiateOAuth() to Mastra's arcade.ts (mirrors ai-sdk template) and rewrote doConnect() / verifyExistingConnection() in the connect route to use it
  • Better Auth sign-in failing without ngrok: betterAuth() had no baseURL, so it couldn't determine the base URL for callbacks/redirects, causing "Network error" on sign-in
    • Fix: set baseURL from NEXT_PUBLIC_APP_URL with http://localhost:<PORT> fallback
  • Plan route error UX: raw MCPClientError message was shown to users on auth failure
    • Fix: detect 401/auth errors in the catch block and show a human-readable message

Test plan

  • Run Mastra template locally (no ngrok): sign in works, no Better Auth warning
  • Run Mastra template, connect Arcade without tokens cached: OAuth flow completes, plan route works after callback
  • Run Mastra template with expired/missing tokens: plan route shows "Not connected to Arcade" instead of raw error

🤖 Generated with Claude Code

- Replace Mastra MCPClient-based OAuth initiation in the connect route
  with the MCP SDK's auth() function (initiateOAuth), matching the
  ai-sdk template. Mastra's transport tried both HTTP and SSE before
  calling redirectToAuthorization, unreliably saving client registration
  and PKCE verifier, causing tokens to never be stored after callback.
- Add initiateOAuth() export to arcade.ts (Mastra template)
- Improve plan route error handling: detect 401/auth errors and show a
  user-friendly message instead of the raw MCPClientError
- Set baseURL on betterAuth() using NEXT_PUBLIC_APP_URL with localhost
  fallback, fixing "Network error" on sign-in when running without ngrok

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@teallarson teallarson marked this pull request as ready for review March 4, 2026 22:07
@teallarson teallarson merged commit 31a8049 into main Mar 4, 2026
@teallarson teallarson deleted the teallarson/fix-mastra-auth branch March 4, 2026 22:07
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.

1 participant