Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions pkgs/mcpx/internal/pool/oauthwait.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package pool

import (
"crypto/md5"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"strings"

"github.com/dezren39/mcpx/internal/config"
)

// mcp-remote parks an unfinished OAuth sign-in on disk: the per-server
// directory under ~/.mcp-auth/mcp-remote-*/<md5(url)> gains client_info.json
// and code_verifier when the browser flow starts, and tokens.json only when
// it completes. While that state holds, every mcp-remote start blocks opening
// a browser and waiting, so mcpx sees nothing but a discover timeout. Naming
// the state (and the command that finishes it) turns a one-minute mystery
// into a one-line instruction.

// oauthWait describes a detected unfinished mcp-remote sign-in.
type oauthWait struct {
URL string
Dir string
Command string // the command line that finishes the sign-in
}

// pendingOAuth reports whether cfg is an mcp-remote stdio server whose OAuth
// sign-in was started but never finished.
func pendingOAuth(cfg *config.Resolved) (oauthWait, bool) {
home, err := os.UserHomeDir()
if err != nil {
return oauthWait{}, false
}
return pendingOAuthIn(cfg, filepath.Join(home, ".mcp-auth"))
}

// pendingOAuthIn is pendingOAuth with the mcp-auth root made explicit, for tests.
func pendingOAuthIn(cfg *config.Resolved, authRoot string) (oauthWait, bool) {
if cfg == nil || !cfg.Stdio() {
return oauthWait{}, false
}
if filepath.Base(cfg.Command) != "mcp-remote" {
return oauthWait{}, false
}
url := ""
for _, a := range cfg.Args {
if strings.HasPrefix(a, "https://") || strings.HasPrefix(a, "http://") {
url = a
break
}
}
if url == "" {
return oauthWait{}, false
}
sum := md5.Sum([]byte(url))
key := hex.EncodeToString(sum[:])
dirs, _ := filepath.Glob(filepath.Join(authRoot, "mcp-remote-*", key))
for _, dir := range dirs {
if !exists(filepath.Join(dir, "client_info.json")) || !exists(filepath.Join(dir, "code_verifier")) {
continue // sign-in never got as far as the browser step
}
if exists(filepath.Join(dir, "tokens.json")) {
continue // sign-in finished; the failure is something else
}
return oauthWait{
URL: url,
Dir: dir,
Command: cfg.Command + " " + url,
}, true
}
return oauthWait{}, false
}

func exists(path string) bool {
_, err := os.Stat(path)
return err == nil
}

// oauthWaitError wraps a start failure with the sign-in explanation when the
// server is parked on an unfinished OAuth flow; otherwise it returns err.
func (p *Pool) oauthWaitError(err error) error {
w, ok := pendingOAuth(p.cfg)
if !ok {
return err
}
return fmt.Errorf("server %q is waiting for OAuth sign-in: an mcp-remote sign-in for %s was started but never finished (no tokens in %s); run `%s` in a terminal and complete the browser sign-in, then retry (start failed with: %v)",
p.cfg.Name, w.URL, w.Dir, w.Command, err)
}
104 changes: 104 additions & 0 deletions pkgs/mcpx/internal/pool/oauthwait_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package pool

import (
"crypto/md5"
"encoding/hex"
"errors"
"os"
"path/filepath"
"strings"
"testing"

"github.com/dezren39/mcpx/internal/config"
)

const oauthTestURL = "https://mcp.example.com/v1/mcp?toolsets=core"

func oauthCfg(command string, args ...string) *config.Resolved {
return &config.Resolved{Server: &config.Server{Name: "datadog", Command: command, Args: args}}
}

// authDir builds <root>/mcp-remote-v1/<md5(url)> populated with files.
func authDir(t *testing.T, url string, files ...string) string {
t.Helper()
root := t.TempDir()
sum := md5.Sum([]byte(url))
dir := filepath.Join(root, "mcp-remote-v1", hex.EncodeToString(sum[:]))
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
for _, f := range files {
if err := os.WriteFile(filepath.Join(dir, f), []byte("{}"), 0o644); err != nil {
t.Fatal(err)
}
}
return root
}

func TestPendingOAuthDetectsUnfinishedSignIn(t *testing.T) {
root := authDir(t, oauthTestURL, "client_info.json", "code_verifier")
w, ok := pendingOAuthIn(oauthCfg("mcp-remote", oauthTestURL), root)
if !ok {
t.Fatal("unfinished sign-in not detected")
}
if w.URL != oauthTestURL || !strings.Contains(w.Dir, "mcp-remote-v1") {
t.Errorf("wait = %+v", w)
}
if w.Command != "mcp-remote "+oauthTestURL {
t.Errorf("command = %q", w.Command)
}
}

func TestPendingOAuthFinishedSignInIsNotWaiting(t *testing.T) {
root := authDir(t, oauthTestURL, "client_info.json", "code_verifier", "tokens.json")
if _, ok := pendingOAuthIn(oauthCfg("mcp-remote", oauthTestURL), root); ok {
t.Error("finished sign-in reported as waiting")
}
}

func TestPendingOAuthNeverStartedIsNotWaiting(t *testing.T) {
root := authDir(t, oauthTestURL) // directory exists, no files yet
if _, ok := pendingOAuthIn(oauthCfg("mcp-remote", oauthTestURL), root); ok {
t.Error("never-started sign-in reported as waiting")
}
if _, ok := pendingOAuthIn(oauthCfg("mcp-remote", oauthTestURL), t.TempDir()); ok {
t.Error("missing auth dir reported as waiting")
}
}

func TestPendingOAuthIgnoresOtherServers(t *testing.T) {
root := authDir(t, oauthTestURL, "client_info.json", "code_verifier")
if _, ok := pendingOAuthIn(oauthCfg("some-other-server", oauthTestURL), root); ok {
t.Error("non-mcp-remote server reported as waiting")
}
if _, ok := pendingOAuthIn(oauthCfg("mcp-remote", "--help"), root); ok {
t.Error("mcp-remote without a URL arg reported as waiting")
}
http := &config.Resolved{Server: &config.Server{Name: "x", URL: oauthTestURL}}
if _, ok := pendingOAuthIn(http, root); ok {
t.Error("direct-HTTP server reported as waiting")
}
}

func TestOAuthWaitErrorMessage(t *testing.T) {
root := authDir(t, oauthTestURL, "client_info.json", "code_verifier")
// Point HOME at a tree holding the auth root so pendingOAuth finds it.
authParent := t.TempDir()
if err := os.Rename(root, filepath.Join(authParent, ".mcp-auth")); err != nil {
t.Fatal(err)
}
t.Setenv("HOME", authParent)
p := &Pool{cfg: oauthCfg("mcp-remote", oauthTestURL)}
err := p.oauthWaitError(errors.New("server/discover: context deadline exceeded"))
msg := err.Error()
for _, want := range []string{"waiting for OAuth sign-in", oauthTestURL, "mcp-remote " + oauthTestURL, "context deadline exceeded"} {
if !strings.Contains(msg, want) {
t.Errorf("message %q missing %q", msg, want)
}
}
// A server with no pending sign-in keeps its original error untouched.
p2 := &Pool{cfg: oauthCfg("other", oauthTestURL)}
if got := p2.oauthWaitError(errors.New("boom")); got.Error() != "boom" {
t.Errorf("unrelated error rewritten: %v", got)
}
}
2 changes: 1 addition & 1 deletion pkgs/mcpx/internal/pool/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,7 @@ func (p *Pool) startLane(ctx context.Context, legacy bool) (*Instance, error) {
}
if err != nil {
_ = tr.Close()
return nil, fmt.Errorf("server %q: %w", p.cfg.Name, err)
return nil, fmt.Errorf("server %q: %w", p.cfg.Name, p.oauthWaitError(err))
}
if cl.CachedEraWrong {
lifecycle("server.era.stale", map[string]any{
Expand Down
Loading