From 32dc263baf56f70e622eb6fd829f562bcb1ca403 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Fri, 30 Oct 2026 08:48:13 -0400 Subject: [PATCH] Sign in to HTTP MCP servers with OAuth: discovery, registration, PKCE, refresh and step-up --- cli/internal/daemon/credentials.go | 20 +- cli/internal/daemon/protocol/api.gen.go | 29 +- cli/internal/daemon/settings.go | 27 +- cli/internal/tui/app.go | 1 + cli/internal/tui/capability_pages.go | 22 + cli/internal/tui/mcp_sign_in.go | 188 ++++++ cli/internal/tui/shot_caps_test.go | 20 + docs/openapi.yaml | 70 ++- robot-docs/auth.md | 4 +- robot-docs/mcp.md | 14 +- src/albedo/daemon/albedo_settings_http.erl | 31 +- src/albedo/daemon/http_auth.gleam | 28 +- src/albedo/harness/albedo_oauth.erl | 103 +++- src/albedo/harness/extension.gleam | 24 + src/albedo/harness/extension/selection.gleam | 1 + .../extensions/antigravity/extension.gleam | 1 + .../harness/extensions/claude/extension.gleam | 1 + .../harness/extensions/codex/extension.gleam | 1 + .../harness/extensions/colab/extension.gleam | 1 + .../harness/extensions/mcp/albedo_mcp.erl | 78 ++- .../extensions/mcp/albedo_mcp_oauth.erl | 572 ++++++++++++++++++ .../harness/extensions/mcp/client.gleam | 192 ++++-- .../harness/extensions/mcp/extension.gleam | 22 +- src/albedo/harness/extensions/mcp/http.gleam | 76 ++- .../harness/extensions/mcp/sign_in.gleam | 64 ++ .../extensions/mistral/extension.gleam | 2 +- .../extensions/opencode_go/extension.gleam | 2 +- src/albedo/harness/oauth.gleam | 8 +- src/albedo/harness/settings/projection.gleam | 63 ++ test/e2e/fake_mcp_http_server.py | 61 +- test/e2e/fake_oauth_server.py | 207 +++++++ test/e2e/mcp_oauth_test.py | 233 +++++++ test/harness/oauth_test.gleam | 14 +- web/src/lib/api.gen.d.ts | 21 + 34 files changed, 2075 insertions(+), 126 deletions(-) create mode 100644 cli/internal/tui/mcp_sign_in.go create mode 100644 src/albedo/harness/extensions/mcp/albedo_mcp_oauth.erl create mode 100644 src/albedo/harness/extensions/mcp/sign_in.gleam create mode 100644 test/e2e/fake_oauth_server.py create mode 100644 test/e2e/mcp_oauth_test.py diff --git a/cli/internal/daemon/credentials.go b/cli/internal/daemon/credentials.go index ff642c15f..1070b3c71 100644 --- a/cli/internal/daemon/credentials.go +++ b/cli/internal/daemon/credentials.go @@ -3,6 +3,7 @@ package daemon import ( "encoding/json" "errors" + "time" ) // The daemon alone reads and writes creds.json. A client changes a profile's @@ -16,11 +17,28 @@ type Credentials struct { Providers []string `json:"providers"` } -// MCPSecretNames is what an MCP server has saved, by name only. +// MCPSecretNames is what an MCP server has saved, by name only, and where +// its OAuth sign-in stands. type MCPSecretNames struct { Headers []string `json:"headers"` Env []string `json:"env"` BearerToken bool `json:"bearerToken"` + Auth MCPAuth `json:"auth"` +} + +// MCPAuth is an HTTP server's OAuth sign-in as the daemon reports it. State +// is "none" until the server asks for a sign-in, then "needs_sign_in", +// "signed_in" or "signed_out"; StepUp names a wider scope a signed-in +// server asked for. Tokens never reach the client. +type MCPAuth struct { + State, Account, Scope, StepUp, Reason, Client string + ExpiresAt time.Time +} + +// SignInNeeded reports whether the server asks the user to sign in, or to +// sign in again for more access. +func (a MCPAuth) SignInNeeded() bool { + return a.State == "needs_sign_in" || a.State == "signed_out" || a.StepUp != "" } // Any reports whether the server has any secret saved. diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index 70d57d43b..c099cba68 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -1668,9 +1668,27 @@ type LoginRequest struct { Values map[string]json.RawMessage `json:"values"` } +// MCPAuth A server's OAuth sign-in. none until the server asks for one; needs_sign_in when it asked and albedo has no usable token, signed_in, or signed_out after the user signed out. Start a sign-in with PUT /auth/logins/{login_id} and provider mcp:. Tokens and client secrets never appear. +type MCPAuth struct { + Account *string `json:"account" nullable:"true"` + + // Client configured when the user set a client id, registered when albedo registered itself. + Client *string `json:"client" nullable:"true"` + ExpiresAt *string `json:"expires_at" nullable:"true"` + Reason *string `json:"reason" nullable:"true"` + Scope *string `json:"scope" nullable:"true"` + State string `json:"state"` + + // StepUp The wider scope a signed-in server asked for; signing in again grants it. + StepUp *string `json:"step_up" nullable:"true"` +} + // MCPDefinition defines model for MCPDefinition. type MCPDefinition struct { - Arguments []string `json:"arguments"` + Arguments []string `json:"arguments"` + + // Auth A server's OAuth sign-in. none until the server asks for one; needs_sign_in when it asked and albedo has no usable token, signed_in, or signed_out after the user signed out. Start a sign-in with PUT /auth/logins/{login_id} and provider mcp:. Tokens and client secrets never appear. + Auth MCPAuth `json:"auth"` BearerTokenEnvVar *string `json:"bearer_token_env_var" nullable:"true"` CallTimeoutMs int64 `json:"call_timeout_ms"` Command *string `json:"command" nullable:"true"` @@ -1709,6 +1727,15 @@ type MCPSecretsPatch struct { BearerToken *string `json:"bearer_token,omitempty" nullable:"true"` Environment map[string]*string `json:"environment,omitempty"` Headers map[string]*string `json:"headers,omitempty"` + + // Oauth Null signs the server out of its OAuth sign-in. + Oauth any `json:"oauth,omitempty" nullable:"true"` + + // OauthClient A client the user registered with the server's authorization server, used instead of registering albedo; null forgets it. + OauthClient *struct { + ClientID string `json:"client_id"` + ClientSecret *string `json:"client_secret,omitempty" nullable:"true"` + } `json:"oauth_client,omitempty" nullable:"true"` } // MCPSettings defines model for MCPSettings. diff --git a/cli/internal/daemon/settings.go b/cli/internal/daemon/settings.go index 8e759a9f0..2a0e4b2ff 100644 --- a/cli/internal/daemon/settings.go +++ b/cli/internal/daemon/settings.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "strconv" + "time" "albedo/cli/internal/config" "albedo/cli/internal/daemon/protocol" @@ -59,7 +60,7 @@ func GetSettings(ctx context.Context, conn *Connection) (Settings, error) { for name, server := range wire.MCP.Definitions { enabled := server.Enabled result.MCP[name] = config.MCPServer{Enabled: &enabled, Type: server.Transport, URL: value(server.URL), Command: value(server.Command), Args: server.Arguments, CWD: value(server.Cwd), BearerTokenEnvVar: value(server.BearerTokenEnvVar), Env: sourceValues(server.Environment), Headers: sourceValues(server.Headers), EnabledTools: server.EnabledTools, DisabledTools: server.DisabledTools, StartupTimeoutMs: int(server.StartupTimeoutMs), CallTimeoutMs: int(server.CallTimeoutMs)} - result.Credentials.MCP[name] = MCPSecretNames{BearerToken: server.SecretPresence.BearerToken, Headers: server.SecretPresence.Headers, Env: server.SecretPresence.Environment} + result.Credentials.MCP[name] = MCPSecretNames{BearerToken: server.SecretPresence.BearerToken, Headers: server.SecretPresence.Headers, Env: server.SecretPresence.Environment, Auth: mcpAuth(server.Auth)} } result.Capabilities = config.CapabilityPrefs{Global: map[string]map[string]bool{"mcp": {}}, Sessions: map[string]map[string]map[string]bool{}} for name := range result.MCP { @@ -248,6 +249,30 @@ func SaveMCP(ctx context.Context, conn *Connection, session string, request MCPU }, &change) return applicationResult(change.Application), err } + +// SignOutMCP drops an MCP server's OAuth tokens; the server stays saved and +// asks for a sign-in on its next request. +func SignOutMCP(ctx context.Context, conn *Connection, name, etag string) error { + var change protocol.MCPSettingsChange + return patchSettingsGroup(ctx, conn, "mcp", etag, map[string]any{ + "definitions": map[string]any{name: map[string]any{"secrets": map[string]any{"oauth": nil}}}, + "validate_connection": false, + }, &change) +} + +// StartMCPSignIn starts the daemon's browser sign-in for one MCP server. +func StartMCPSignIn(ctx context.Context, conn *Connection, name string) (StartedSignIn, error) { + return StartProviderLogin(ctx, conn, "mcp:"+name, "browser", nil) +} + +func mcpAuth(wire protocol.MCPAuth) MCPAuth { + auth := MCPAuth{State: wire.State, Account: value(wire.Account), Scope: value(wire.Scope), StepUp: value(wire.StepUp), Reason: value(wire.Reason), Client: value(wire.Client)} + if at := value(wire.ExpiresAt); at != "" { + auth.ExpiresAt, _ = time.Parse(time.RFC3339, at) + } + return auth +} + func nonNil[T any](s []T) []T { if s == nil { return []T{} diff --git a/cli/internal/tui/app.go b/cli/internal/tui/app.go index bcda93b66..daab6f20f 100644 --- a/cli/internal/tui/app.go +++ b/cli/internal/tui/app.go @@ -447,6 +447,7 @@ func (m *AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case ChatOpenCapabilityPageMsg: if m.ActiveSession != nil { m.CapabilityPage = NewCapabilityPageModel(m.Conn, m.ActiveSession.ID, msg.Kind) + m.CapabilityPage.openBrowser = m.openBrowser return m, m.openScreen(AppStateCapabilityPage, &m.CapabilityPage) } diff --git a/cli/internal/tui/capability_pages.go b/cli/internal/tui/capability_pages.go index 3848a2b70..0b1991295 100644 --- a/cli/internal/tui/capability_pages.go +++ b/cli/internal/tui/capability_pages.go @@ -23,6 +23,8 @@ type CapabilityPageModel struct { Prefs config.CapabilityPrefs Conn *daemon.Connection Form *mcpForm + SignIn *mcpSignIn + openBrowser func(string) SessionID, Kind string Items []capabilityItem Revision string @@ -267,6 +269,12 @@ func (m CapabilityPageModel) Update(msg tea.Msg) (CapabilityPageModel, tea.Cmd) m.Loading, m.Generation = true, nextPageGeneration() return m, tea.Batch(m.loadCmd(m.Generation), func() tea.Msg { return CapabilityPageChangedMsg{} }) + case mcpSignInStartedMsg: + return m.signInStarted(msg) + + case mcpSignInPolledMsg: + return m.signInPolled(msg) + case tea.PasteMsg: if m.Form == nil || m.Saving { return m, nil @@ -286,6 +294,8 @@ func (m CapabilityPageModel) Update(msg tea.Msg) (CapabilityPageModel, tea.Cmd) return m, nil case m.Form != nil: return m.formKey(msg) + case m.SignIn != nil && msg.String() == "esc": + return m.cancelSignIn() case msg.String() == "esc" || msg.String() == "ctrl+c" || (msg.String() == "ctrl+d" && m.Kind != "mcp"): return m, func() tea.Msg { return CapabilityPageDoneMsg{} } case m.Loading || m.Saving: @@ -348,6 +358,14 @@ func (m CapabilityPageModel) listKey(msg tea.KeyPressMsg) (CapabilityPageModel, if mcp && ok && serverDisabled(item) { return m.enableServer(item) } + case "ctrl+l": + if mcp && ok && m.SignIn == nil && canSignIn(item) { + return m.startSignIn(item) + } + case "ctrl+u": + if mcp && ok && item.Secrets.Auth.State == "signed_in" { + m.confirm.ask(actionSignOut, item.ID, "sign out", fmt.Sprintf("Its tools stop working until you sign in again. Sign out of %s?", item.Title)) + } case "ctrl+t": if !m.ExtensionEnabled { m.confirm.ask(actionEnableExtension, m.Kind, "enable", fmt.Sprintf("Enable the %s extension? This reloads this session to apply it.", m.Kind)) @@ -406,6 +424,8 @@ func (m CapabilityPageModel) confirmed() (CapabilityPageModel, tea.Cmd) { return m.save(m.enableExtensionCmd) case actionDeleteServer: return m.save(func(gen int) tea.Cmd { return m.deleteMCPCmd(target, gen) }) + case actionSignOut: + return m.save(func(gen int) tea.Cmd { return m.signOutCmd(target, gen) }) } item, ok := m.itemNamed(target) if !ok { @@ -582,6 +602,7 @@ func (m CapabilityPageModel) serverDetails(item capabilityItem, asked string, wi } } else { lines = append(lines, factRows("url", server.URL, width)...) + lines = append(lines, m.signInRows(item, width)...) } file := "enabled in extensions.json" if serverDisabled(item) { @@ -650,6 +671,7 @@ func (m CapabilityPageModel) hints(item capabilityItem, ok bool) []hint { if mcp { hints = append(hints, hint{"ctrl+o", "add server"}) if ok { + hints = append(hints, m.signInHints(item)...) hints = append(hints, hint{"ctrl+e", "edit"}, hint{"ctrl+d", "delete"}) } } diff --git a/cli/internal/tui/mcp_sign_in.go b/cli/internal/tui/mcp_sign_in.go new file mode 100644 index 000000000..1b32d871a --- /dev/null +++ b/cli/internal/tui/mcp_sign_in.go @@ -0,0 +1,188 @@ +package tui + +import ( + "albedo/cli/internal/daemon" + "context" + "fmt" + "time" + + tea "charm.land/bubbletea/v2" +) + +// An MCP server that asks for OAuth signs in through the daemon's browser +// sign-in (PUT /auth/logins with provider mcp:); the page opens the +// authorize URL, shows it for a terminal without a browser, and polls until +// the daemon has the tokens. + +const actionSignOut = "sign-out" + +// mcpSignIn is the browser sign-in in flight for one server. +type mcpSignIn struct { + Server, ID, URL, Message string +} + +type mcpSignInStartedMsg struct { + Server string + Started daemon.StartedSignIn + Err error +} + +type mcpSignInPolledMsg struct { + ID string + Status daemon.SignInStatus + Err error +} + +// signInPollEvery is how often the page asks whether the browser finished. +const signInPollEvery = time.Second + +// canSignIn is whether the row is an HTTP server the user may sign in to. +func canSignIn(item capabilityItem) bool { + return item.Server.Type == "http" && item.Server.BearerTokenEnvVar == "" && !item.Secrets.BearerToken +} + +func (m CapabilityPageModel) startSignIn(item capabilityItem) (CapabilityPageModel, tea.Cmd) { + m.Error, m.Notice = "", "" + m.setSignIn(&mcpSignIn{Server: item.ID, Message: "starting the sign-in"}) + conn, name := m.Conn, item.ID + return m, func() tea.Msg { + started, err := daemon.StartMCPSignIn(context.Background(), conn, name) + return mcpSignInStartedMsg{Server: name, Started: started, Err: err} + } +} + +func (m CapabilityPageModel) signInStarted(msg mcpSignInStartedMsg) (CapabilityPageModel, tea.Cmd) { + if m.SignIn == nil || m.SignIn.Server != msg.Server { + return m, nil + } + if msg.Err != nil { + m.setSignIn(nil) + m.Error = msg.Err.Error() + return m, nil + } + m.setSignIn(&mcpSignIn{Server: msg.Server, ID: msg.Started.ID, URL: msg.Started.URL, Message: "waiting for the browser"}) + url, open := msg.Started.URL, m.openBrowser + return m, tea.Batch(func() tea.Msg { + if open != nil { + open(url) + } + return nil + }, m.pollSignIn(msg.Started.ID)) +} + +func (m CapabilityPageModel) pollSignIn(id string) tea.Cmd { + conn := m.Conn + return tea.Tick(signInPollEvery, func(time.Time) tea.Msg { + status, err := daemon.PollSignIn(context.Background(), conn, id) + return mcpSignInPolledMsg{ID: id, Status: status, Err: err} + }) +} + +func (m CapabilityPageModel) signInPolled(msg mcpSignInPolledMsg) (CapabilityPageModel, tea.Cmd) { + if m.SignIn == nil || m.SignIn.ID != msg.ID { + return m, nil + } + if msg.Err != nil { + m.setSignIn(nil) + m.Error = msg.Err.Error() + return m, nil + } + switch msg.Status.State { + case "waiting", "exchanging": + if msg.Status.Message != "" { + m.setSignIn(&mcpSignIn{Server: m.SignIn.Server, ID: msg.ID, URL: m.SignIn.URL, Message: msg.Status.Message}) + } + return m, m.pollSignIn(msg.ID) + case "complete": + m.Notice, m.noticeWarns = fmt.Sprintf("Signed in to %s. Its tools join the session on its next turn.", m.SignIn.Server), false + m.setSignIn(nil) + m.Loading, m.Generation = true, nextPageGeneration() + return m, tea.Batch(m.loadCmd(m.Generation), func() tea.Msg { return CapabilityPageChangedMsg{} }) + default: + m.Error = "Sign-in " + msg.Status.State + ": " + msg.Status.Message + m.setSignIn(nil) + return m, nil + } +} + +// setSignIn replaces the sign-in in flight and redraws the rows whose pane +// shows it. +func (m *CapabilityPageModel) setSignIn(signIn *mcpSignIn) { + m.SignIn = signIn + m.refreshRows() +} + +// cancelSignIn stops waiting for the browser and closes the daemon's listener. +func (m CapabilityPageModel) cancelSignIn() (CapabilityPageModel, tea.Cmd) { + id, conn := m.SignIn.ID, m.Conn + m.setSignIn(nil) + if id == "" { + return m, nil + } + return m, func() tea.Msg { + _ = daemon.CancelSignIn(context.Background(), conn, id) + return nil + } +} + +func (m CapabilityPageModel) signOutCmd(name string, gen int) tea.Cmd { + conn, etag := m.Conn, m.MCPETag + return func() tea.Msg { + err := daemon.SignOutMCP(context.Background(), conn, name, etag) + return capabilitySavedMsg{Gen: gen, Err: err, Notice: "Signed out of " + name + "."} + } +} + +// signInRows are the pane's sign-in facts for an HTTP server: a sign-in in +// flight with the URL to open by hand, or where the saved one stands. +func (m CapabilityPageModel) signInRows(item capabilityItem, width int) []string { + if s := m.SignIn; s != nil && s.Server == item.ID { + lines := factRows("sign-in", "signing in · "+s.Message, width) + if s.URL != "" { + lines = append(lines, factRows("open", s.URL, width)...) + } + return lines + } + auth := item.Secrets.Auth + var text string + switch auth.State { + case "signed_in": + text = "signed in" + if auth.Account != "" { + text += " as " + auth.Account + } + if !auth.ExpiresAt.IsZero() { + text += " · token renews " + auth.ExpiresAt.Local().Format("15:04") + } + case "needs_sign_in": + text = "needs sign-in" + if auth.Reason != "" { + text += " · " + auth.Reason + } + case "signed_out": + text = "signed out" + default: + return nil + } + lines := factRows("sign-in", text, width) + if auth.StepUp != "" { + lines = append(lines, factRows("needs", "wider access: "+auth.StepUp, width)...) + } + return lines +} + +// signInHints are the sign-in keys the highlighted server answers. +func (m CapabilityPageModel) signInHints(item capabilityItem) []hint { + switch { + case m.SignIn != nil: + return []hint{{"esc", "cancel sign-in"}} + case !canSignIn(item): + return nil + case item.Secrets.Auth.State == "signed_in" && item.Secrets.Auth.StepUp == "": + return []hint{{"ctrl+l", "sign in again"}, {"ctrl+u", "sign out"}} + case item.Secrets.Auth.State == "signed_in": + return []hint{{"ctrl+l", "grant access"}, {"ctrl+u", "sign out"}} + default: + return []hint{{"ctrl+l", "sign in"}} + } +} diff --git a/cli/internal/tui/shot_caps_test.go b/cli/internal/tui/shot_caps_test.go index 055d87296..6c8282f87 100644 --- a/cli/internal/tui/shot_caps_test.go +++ b/cli/internal/tui/shot_caps_test.go @@ -5,6 +5,7 @@ import ( "albedo/cli/internal/daemon" "errors" "slices" + "time" tea "charm.land/bubbletea/v2" ) @@ -108,6 +109,16 @@ func init() { return m.View() }}, shotState{"mcp-form-stdio", capsShot("mcp", servers, true, nil, stdio...)}, + shotState{"mcp-needs-sign-in", capsShot("mcp", capsOAuthServers(daemon.MCPAuth{State: "needs_sign_in", Reason: "the server asks you to sign in"}), true, nil)}, + shotState{"mcp-signed-out", capsShot("mcp", capsOAuthServers(daemon.MCPAuth{State: "signed_out"}), true, nil)}, + shotState{"mcp-signing-in", func(w, h int) string { + m := capsModel("mcp", w, h, capsOAuthServers(daemon.MCPAuth{State: "needs_sign_in", Reason: "the server asks you to sign in"}), true, nil, chord('l')) + m, _ = m.Update(mcpSignInStartedMsg{Server: "docs", Started: daemon.StartedSignIn{ID: "login-1", URL: "https://auth.docs.example/authorize?response_type=code&client_id=client-1&resource=https%3A%2F%2Fdocs.example%2Fmcp"}}) + return m.View() + }}, + shotState{"mcp-signed-in", capsShot("mcp", capsOAuthServers(daemon.MCPAuth{State: "signed_in", Account: "ana@example.com", Scope: "read offline_access", Client: "registered", ExpiresAt: capsExpiry}), true, nil)}, + shotState{"mcp-step-up", capsShot("mcp", capsOAuthServers(daemon.MCPAuth{State: "signed_in", Account: "ana@example.com", StepUp: "read offline_access admin", ExpiresAt: capsExpiry}), true, nil)}, + shotState{"mcp-confirm-sign-out", capsShot("mcp", capsOAuthServers(daemon.MCPAuth{State: "signed_in", Account: "ana@example.com", ExpiresAt: capsExpiry}), true, nil, chord('u'))}, ) } @@ -151,6 +162,15 @@ func capsInstructions() []capabilityItem { } } +var capsExpiry = time.Date(2026, 10, 14, 15, 42, 0, 0, time.Local) + +// capsOAuthServers are the servers with docs signing in through OAuth. +func capsOAuthServers(auth daemon.MCPAuth) []capabilityItem { + items := capsServers() + items[0].Secrets = daemon.MCPSecretNames{Auth: auth} + return items +} + func capsServers() []capabilityItem { on, off := true, false return []capabilityItem{ diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 6da5d1c4e..45ce1eb9b 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -5967,6 +5967,50 @@ components: maxItems: 200 required: [bearer_token, environment, headers] additionalProperties: false + MCPAuth: + type: object + description: A server's OAuth sign-in. none until the server asks for one; needs_sign_in when it + asked and albedo has no usable token, signed_in, or signed_out after the user signed out. Start + a sign-in with PUT /auth/logins/{login_id} and provider mcp:. Tokens and client + secrets never appear. + properties: + state: + type: string + enum: [none, needs_sign_in, signed_in, signed_out] + account: + anyOf: + - type: string + maxLength: 256 + - type: 'null' + expires_at: + anyOf: + - type: string + format: date-time + - type: 'null' + scope: + anyOf: + - type: string + maxLength: 4096 + - type: 'null' + step_up: + anyOf: + - type: string + maxLength: 4096 + - type: 'null' + description: The wider scope a signed-in server asked for; signing in again grants it. + reason: + anyOf: + - type: string + maxLength: 4096 + - type: 'null' + client: + anyOf: + - type: string + enum: [configured, registered] + - type: 'null' + description: configured when the user set a client id, registered when albedo registered itself. + required: [state, account, expires_at, scope, step_up, reason, client] + additionalProperties: false MCPDefinition: type: object properties: @@ -6033,8 +6077,10 @@ components: maximum: 3600000 secret_presence: $ref: '#/components/schemas/SecretPresence' + auth: + $ref: '#/components/schemas/MCPAuth' required: [enabled, transport, command, arguments, cwd, url, environment, headers, bearer_token_env_var, - enabled_tools, disabled_tools, startup_timeout_ms, call_timeout_ms, secret_presence] + enabled_tools, disabled_tools, startup_timeout_ms, call_timeout_ms, secret_presence, auth] additionalProperties: false MCPSecretsPatch: type: object @@ -6062,6 +6108,28 @@ components: writeOnly: true maxLength: 16384 - type: 'null' + oauth: + type: 'null' + description: Null signs the server out of its OAuth sign-in. + oauth_client: + anyOf: + - type: object + properties: + client_id: + type: string + minLength: 1 + maxLength: 1024 + client_secret: + anyOf: + - type: string + writeOnly: true + maxLength: 4096 + - type: 'null' + required: [client_id] + additionalProperties: false + - type: 'null' + description: A client the user registered with the server's authorization server, used instead + of registering albedo; null forgets it. writeOnly: true additionalProperties: false MCPDefinitionPatch: diff --git a/robot-docs/auth.md b/robot-docs/auth.md index 75c600885..f119c0280 100644 --- a/robot-docs/auth.md +++ b/robot-docs/auth.md @@ -4,7 +4,7 @@ model authentication is supplied by model-provider extensions rather than the da ## credentials -Every secret albedo keeps lives in `$ALBEDO_HOME/creds.json`, mode `0600`, and only the daemon reads or writes it. `accounts` holds OAuth and key accounts by store key, as one object or an array. Key accounts contain `type: "key"`, `apiKey`, `endpoint`, `label`, and `_albedo_account_id`; generic compatible keys use `accounts.openai`, OpenCode Go uses `accounts.opencode-go`, Perplexity uses `accounts.perplexity`, and Mistral uses `accounts.mistral`. `providers` holds legacy profile keys for other extensions; `mcp` holds each MCP server's `bearerToken`, `headers` and `env`. All credential and settings mutations share one per-home daemon lock. OAuth refreshes re-read under that lock and preserve unrelated sections. A hand-written config `apiKey` wins at runtime: the next start moves it into a key account and pins the profile for `openai`, `opencode-go` and `mistral`, and leaves it in the profile for a provider that reads its own (`bedrock`, `vertex`, `perplexity`). +Every secret albedo keeps lives in `$ALBEDO_HOME/creds.json`, mode `0600`, and only the daemon reads or writes it. `accounts` holds OAuth and key accounts by store key, as one object or an array. Key accounts contain `type: "key"`, `apiKey`, `endpoint`, `label`, and `_albedo_account_id`; generic compatible keys use `accounts.openai`, OpenCode Go uses `accounts.opencode-go`, Perplexity uses `accounts.perplexity`, and Mistral uses `accounts.mistral`. `providers` holds legacy profile keys for other extensions; `mcp` holds each MCP server's `bearerToken`, `headers`, `env`, a configured OAuth client (`oauthClient`) and its OAuth sign-in (`oauth`, see [mcp](mcp.md#sign-in-with-oauth)). All credential and settings mutations share one per-home daemon lock. OAuth refreshes re-read under that lock and preserve unrelated sections. A hand-written config `apiKey` wins at runtime: the next start moves it into a key account and pins the profile for `openai`, `opencode-go` and `mistral`, and leaves it in the profile for a provider that reads its own (`bedrock`, `vertex`, `perplexity`). Account limit marks under `accounts` are recorded per model-family meter for Google Antigravity (`limitedMeters: {"claude": , ...}` with meter keys `gemini`, `claude`, `gpt-oss`, falling back conservatively to legacy `limitedUntil` when `limitedMeters` is absent). Codex and saved API keys use account-wide `limitedUntil`. Environment keys keep transient marks for the daemon's lifetime. @@ -40,7 +40,7 @@ The oauth callback binds only to `127.0.0.1`. Port 1455 is fixed because OpenAI ## sign-in api -Browser sign-ins run in the daemon, so every client shares one OAuth implementation. An extension contributes `extension.LoginPlugin(oauth.Login(...))`: the profile extension it serves, a chooser label and detail, the protocol its profiles use, its `creds.json` accounts key, its loopback callback (host, port, path, and whether the port is fixed), and three functions. `authorize` builds the provider url from a `Grant` (redirect, state, PKCE verifier and challenge). `exchange` trades the code for the credential object to store and may report progress. `account` names a stored credential; equal ids are the same account. `albedo_oauth` owns the rest: the callback listener, the race with a pasted code, a 5-minute timeout, and locked writes. A sign-in replaces the stored account with the same id and appends a new one. One account is stored as an object, two or more as an array. +Browser sign-ins run in the daemon, so every client shares one OAuth implementation. An extension contributes `extension.LoginPlugin(oauth.Login(...))`, or a `LoginResolverPlugin` that names sign-ins at request time (one per MCP server, provider `mcp:`): the profile extension it serves, a chooser label and detail, the protocol its profiles use, its `creds.json` accounts key, its loopback callback (host, port, path, and whether the port is fixed), and three functions. `authorize` builds the provider url from a `Grant` (redirect, state, PKCE verifier and challenge), or says why the sign-in cannot start. `oauth.callback_issuer()` gives `exchange` the response's `iss` (RFC 9207). `exchange` trades the code for the credential object to store and may report progress. `account` names a stored credential; equal ids are the same account. `albedo_oauth` owns the rest: the callback listener, the race with a pasted code, a 5-minute timeout, and locked writes. A sign-in replaces the stored account with the same id and appends a new one. One account is stored as an object, two or more as an array. Clients use these resources with the daemon bearer token: diff --git a/robot-docs/mcp.md b/robot-docs/mcp.md index 4b29e6e2e..479a7752e 100644 --- a/robot-docs/mcp.md +++ b/robot-docs/mcp.md @@ -28,10 +28,22 @@ Albedo owns configuration, credential scope, naming, and lifecycle in `albedo_mc - **transport**: `http` (default) or `stdio`, switched with ← →. - **url** for HTTP, or **command** for stdio, written as you would type it in a shell (`npx -y @modelcontextprotocol/server-filesystem "/srv/my docs"`); quotes are honoured but no shell runs. - **name**, suggested from the URL host or the command's package until you edit it. -- **bearer token** and one custom **header** for HTTP, or `KEY=value` **env** entries for stdio. These are optional, masked while typed, and stored by the daemon in `creds.json` (mode 0600), never in `extensions.json`. +- **bearer token** and one custom **header** for HTTP (a server that asks for OAuth needs neither; see below), or `KEY=value` **env** entries for stdio. These are optional, masked while typed, and stored by the daemon in `creds.json` (mode 0600), never in `extensions.json`. Nothing is written until the form is saved with ctrl+s (or enter on its last field). The server and its credentials are saved together and the session reloads once; if the server cannot connect, both are restored and the form stays open with the error. `enter` edits a server in the same form (a blank secret keeps the stored one, `-` removes it), `d` deletes a server and its credentials, and `e` re-enables a server switched off with `"enabled": false`. +## Sign in with OAuth + +An HTTP server that answers `401` asks albedo to sign in, as the MCP authorization spec describes (2025-11-25 and 2026-07-28 `basic/authorization`). `mcp/albedo_mcp_oauth.erl` holds the protocol, `mcp/sign_in.gleam` names one sign-in per server (`mcp:`) through the `LoginResolverPlugin`, and the daemon's shared sign-in flow (`albedo_oauth`, see [auth](auth.md#sign-in-api)) runs the loopback callback, the state check and the race with a pasted callback URL. + +- **Discovery.** The `resource_metadata` of the `WWW-Authenticate` challenge, else the well-known Protected Resource Metadata (RFC 9728) under the endpoint's path and then at the root, in the spec's order. The metadata's `resource` must be the server URL or a prefix of it; it becomes the `resource` parameter (RFC 8707) of the authorize, token and refresh requests. The first `authorization_servers` entry is asked for RFC 8414 metadata, then OpenID Connect discovery, in the spec's order for an issuer with or without a path; a document whose `issuer` differs is not used. An authorization server that does not list `S256` in `code_challenge_methods_supported` is refused. Its endpoints must be https, unless the MCP server itself is plain http. +- **Scope.** A pending step-up, else the challenge's `scope`, else the resource's `scopes_supported`, plus `offline_access` when the authorization server lists it. +- **Client.** A client id (and secret) the user configured for the server (`secrets.oauth_client` in the settings patch), else Dynamic Client Registration (RFC 7591, `application_type: native`, public client). The registration is kept per issuer and redirect, and reused while both match. Client ID Metadata Documents come between the two in the spec's order, but need an https URL albedo can host its metadata document at; a local daemon has none, so albedo does not use them. +- **Authorization.** Authorization code with PKCE S256 and `state`; the callback listens on `127.0.0.1:33418/callback`, or an ephemeral port when that is busy (which registers again). A configured client should register that redirect. An `iss` in the response must be the issuer (RFC 9207); one the server promised and left out is refused. +- **Tokens.** Kept in `creds.json` under `mcp..oauth` with the server URL they belong to, never in `extensions.json` or a log; a record for another URL is never sent. Every request carries the access token; one within a minute of expiry is refreshed first, and one the server refuses with `401` is refreshed once and the request posted again. Refreshes of one server are single-flight. A refresh the authorization server refuses marks the server `needs_sign_in` instead of trying again. A `403` with `insufficient_scope` keeps the token and records the union of the requested and challenged scopes as a step-up; the next sign-in asks for it. + +A server that needs a sign-in is left out of the session with a warning and a line in the MCP context, and its calls fail with "needs the user to sign in", which says the request did not run. It joins once signed in, the way a server that comes back does. Saving a server that answers `401` keeps it, needing a sign-in, instead of refusing it. The settings group reports each server's `auth` (`state` none, needs_sign_in, signed_in or signed_out, `account`, `expires_at`, `scope`, `step_up`, `reason`, `client`), never a token. A client signs in with `PUT /auth/logins/` and provider `mcp:`, and signs out with `secrets: {oauth: null}`. In `/mcp`, `ctrl+l` signs in (it opens the browser unless `ALBEDO_NO_BROWSER` is set, and shows the URL either way), `ctrl+u` signs out, and `esc` cancels a sign-in in flight. + ## Configure servers Servers live in the `mcp` section of `$ALBEDO_HOME/extensions.json` (default `~/.albedo/extensions.json`), never in `config.json` with provider credentials. diff --git a/src/albedo/daemon/albedo_settings_http.erl b/src/albedo/daemon/albedo_settings_http.erl index 77471c4d5..ceccbfdb7 100644 --- a/src/albedo/daemon/albedo_settings_http.erl +++ b/src/albedo/daemon/albedo_settings_http.erl @@ -63,7 +63,8 @@ match_group(Group, Match, Prior, Revisions) -> checked_candidates(Patch, Docs) -> Definitions = object(<<"servers">>, object(<<"mcp">>, maps:get(<<"extensions.json">>, Docs))), Secrets = object(<<"mcp">>, maps:get(<<"creds.json">>, Docs)), - [{Name, maps:get(Name, Definitions), maps:get(Name, Secrets, #{})} + %% A probe may record that a server asks for a sign-in; that is not a change. + [{Name, maps:get(Name, Definitions), maps:remove(<<"oauth">>, maps:get(Name, Secrets, #{}))} || {Name, Change} <- lists:sort(maps:to_list(object(<<"definitions">>, Patch))), Change =/= null]. publish(Home, Group, Docs, Next, Validation, Revisions, Declared) -> @@ -233,7 +234,7 @@ translate(Map, Names) -> maps:from_list([{Stored, maps:get(Wire, Map)} || {Wire, mcp_candidate(Patch, Prior, Secrets0) -> fields(Patch, [Wire || {Wire, _} <- 'albedo@harness@settings@projection':mcp_fields()] ++ [<<"environment">>, <<"headers">>, <<"secrets">>]), Public0 = maps:merge(Prior, translate(Patch, 'albedo@harness@settings@projection':mcp_fields())), - SecretPatch = object(<<"secrets">>, Patch), fields(SecretPatch, [<<"bearer_token">>, <<"environment">>, <<"headers">>]), + SecretPatch = object(<<"secrets">>, Patch), fields(SecretPatch, [<<"bearer_token">>, <<"environment">>, <<"headers">>, <<"oauth">>, <<"oauth_client">>]), {Public1, Secrets1} = lists:foldl(fun({Wire, Stored}, {Public, Secrets}) -> PublicChanges = maps:get(Wire, Patch, #{}), SecretChanges = maps:get(Wire, SecretPatch, #{}), Sources = source_choices(object(Stored, Public), PublicChanges), @@ -248,10 +249,11 @@ mcp_candidate(Patch, Prior, Secrets0) -> {ok, null} -> {Public1, maps:remove(<<"bearerToken">>, Secrets1)}; {ok, Token} -> text(Token, 1, 16384), {maps:remove(<<"bearerTokenEnvVar">>, Public1), Secrets1#{<<"bearerToken">> => Token}} end, - Secrets2 = case maps:find(<<"bearer_token_env_var">>, Patch) of + Secrets3 = case maps:find(<<"bearer_token_env_var">>, Patch) of {ok, Name} when is_binary(Name) -> true = not maps:is_key(<<"bearer_token">>, SecretPatch) orelse maps:get(<<"bearer_token">>, SecretPatch) =:= null, maps:remove(<<"bearerToken">>, Secrets); _ -> Secrets end, + Secrets2 = oauth_choices(Secrets3, SecretPatch), Type = maps:get(<<"type">>, Public), case Type of <<"http">> -> true = maps:get(<<"command">>, Public, null) =:= null, true = maps:get(<<"cwd">>, Public, null) =:= null, true = maps:get(<<"args">>, Public, []) =:= [], true = map_size(object(<<"env">>, Public)) =:= 0; @@ -260,6 +262,29 @@ mcp_candidate(Patch, Prior, Secrets0) -> case maps:find(<<"startupTimeoutMs">>, Public) of {ok, Millis} -> counter(Millis, 1, 300000); error -> ok end, {Public, Secrets2}. +%% `oauth: null` signs the server out, keeping what it asked for; a sign-in +%% itself only ever comes from the daemon's sign-in flow. `oauth_client` is a +%% client id (and secret) the user registered with the server's +%% authorization server, or null to forget it. +oauth_choices(Secrets, SecretPatch) -> + Signed = case maps:find(<<"oauth">>, SecretPatch) of + error -> Secrets; + {ok, null} -> + case maps:find(<<"oauth">>, Secrets) of + {ok, Record} -> Secrets#{<<"oauth">> => albedo_mcp_oauth:signed_out(Record)}; + error -> Secrets + end + end, + case maps:find(<<"oauth_client">>, SecretPatch) of + error -> Signed; + {ok, null} -> maps:remove(<<"oauthClient">>, Signed); + {ok, Client} -> + fields(Client, [<<"client_id">>, <<"client_secret">>]), + Id = maps:get(<<"client_id">>, Client), text(Id, 1, 1024), + Secret = maps:get(<<"client_secret">>, Client, null), nullable_text(Secret, 4096), + Signed#{<<"oauthClient">> => #{<<"clientId">> => Id, <<"clientSecret">> => Secret}} + end. + source_choices(_, null) -> #{}; source_choices(Prior, Changes) -> maps:fold(fun (K, null, Acc) -> maps:remove(K, Acc); diff --git a/src/albedo/daemon/http_auth.gleam b/src/albedo/daemon/http_auth.gleam index 0c4e4d538..1a990fa23 100644 --- a/src/albedo/daemon/http_auth.gleam +++ b/src/albedo/daemon/http_auth.gleam @@ -328,10 +328,12 @@ pub fn login( #("values", json.object([])), ]) |> json.to_string - let login = - list.find(logins, fn(login) { login.provider == provider }) - |> result.map(Some) - |> result.unwrap(None) + use login <- result.try( + case list.find(logins, fn(login) { login.provider == provider }) { + Ok(login) -> Ok(Some(login)) + Error(Nil) -> resolved_login(config, registry, provider) + }, + ) use created <- result.try( oauth.start_identified(config.home, id, provider, login, intent) |> result.map_error(http_api.native_failure), @@ -411,6 +413,24 @@ pub fn login( http_api.answer(outcome) } +/// A sign-in an extension names at request time, such as an MCP server's. +/// One it names but cannot start yet is refused with its reason. +fn resolved_login( + config: Config, + registry: Subject(Message), + provider: String, +) -> Result(Option(oauth.Login), http_api.Failure) { + use host <- result.try( + registry.host(registry) |> result.map_error(http_api.failure), + ) + case extension.resolve_login(runtime.installed(host), config.home, provider) { + None -> Ok(None) + Some(Ok(login)) -> Ok(Some(login)) + Some(Error(reason)) -> + Error(http_api.Failure(409, "sign_in_unavailable", reason)) + } +} + pub fn account( config: Config, registry: Subject(Message), diff --git a/src/albedo/harness/albedo_oauth.erl b/src/albedo/harness/albedo_oauth.erl index d5369a303..fc5f3a949 100644 --- a/src/albedo/harness/albedo_oauth.erl +++ b/src/albedo/harness/albedo_oauth.erl @@ -4,13 +4,14 @@ %% tracks the flows; each flow owns its loopback callback listener and ends by %% storing the credential in creds.json's accounts under the provider's key. --export([put_key/6, rename_account/4, accounts/2, +-export([put_key/6, rename_account/4, accounts/2, callback_issuer/0, parse_input/1, start_identified/5, get_identified/3, input_identified/5, cancel_identified/3, auth_snapshot/2, account_overview/2, remove_account/3]). -define(OWNER, albedo_oauth). -define(FLOW_TIMEOUT_MS, 300000). -define(CALL_MS, 60000). +-define(ISSUER, albedo_oauth_issuer). %% Login is the Gleam oauth.Login record: %% {login, Provider, Label, Detail, Kind, Store, {callback, Host, Port, Path, Fixed}, Authorize, Exchange, Account} @@ -188,29 +189,36 @@ run_flow(Owner, Id, {login, Provider, _, _, _, Store, {callback, Host, Port, Pat Challenge = base64url(crypto:hash(sha256, Verifier)), Redirect = iolist_to_binary(["http://", Host, ":", integer_to_binary(Bound), Path]), Grant = {grant, Redirect, State, Verifier, Challenge}, - Self = self(), - spawn_link(fun() -> accept(Socket, Path, Self) end), - Owner ! {Id, ready, Authorize(Grant)}, - albedo_clock:send_after(?FLOW_TIMEOUT_MS, self(), timeout), - Settle = settle_fn(Owner, Id), - Outcome = wait(State), - gen_tcp:close(Socket), - case Outcome of - {ok, Code} -> - Settle({exchanging, <<"exchanging authorization code">>}), - Progress = fun(Text) -> Settle({exchanging, Text}), nil end, - try Exchange(Grant, Code, Progress) of - {ok, Credential} -> - case Save(Store, Credential, Account) of - {ok, Label} -> Settle({done, Label}); - {error, Reason} -> Settle({failed, Reason}) - end; + case Authorize(Grant) of + {ok, Url} -> callback_flow(Owner, Id, Socket, Path, Grant, Url, Exchange, Store, Account, Save); + {error, Reason} -> gen_tcp:close(Socket), Owner ! {Id, refused, Reason} + end + end. + +%% Waits for the browser's callback or a pasted code, then trades the code. +callback_flow(Owner, Id, Socket, Path, {grant, _, State, _, _} = Grant, Url, Exchange, Store, Account, Save) -> + Self = self(), + spawn_link(fun() -> accept(Socket, Path, Self) end), + Owner ! {Id, ready, Url}, + albedo_clock:send_after(?FLOW_TIMEOUT_MS, self(), timeout), + Settle = settle_fn(Owner, Id), + Outcome = wait(State), + gen_tcp:close(Socket), + case Outcome of + {ok, Code} -> + Settle({exchanging, <<"exchanging authorization code">>}), + Progress = fun(Text) -> Settle({exchanging, Text}), nil end, + try Exchange(Grant, Code, Progress) of + {ok, Credential} -> + case Save(Store, Credential, Account) of + {ok, Label} -> Settle({done, Label}); {error, Reason} -> Settle({failed, Reason}) - catch Class:Reason -> - Settle({failed, iolist_to_binary(io_lib:format("sign-in failed: ~p:~p", [Class, Reason]))}) end; {error, Reason} -> Settle({failed, Reason}) - end + catch Class:Reason -> + Settle({failed, iolist_to_binary(io_lib:format("sign-in failed: ~p:~p", [Class, Reason]))}) + end; + {error, Reason} -> Settle({failed, Reason}) end. listen(Port, Fixed) -> @@ -236,9 +244,12 @@ wait(State) -> (maps:get(<<"error_description">>, Query, Error))/binary>>}; _ -> wait(State) end; - {callback, #{<<"code">> := <<_, _/binary>> = Code, <<"state">> := State}} -> {ok, Code}; + {callback, #{<<"code">> := <<_, _/binary>> = Code, <<"state">> := State} = Query} -> + put(?ISSUER, maps:get(<<"iss">>, Query, none)), + {ok, Code}; {callback, _} -> wait(State); {input, Text} -> + put(?ISSUER, input_issuer(Text)), case parse_input(Text) of {<<>>, _} -> {error, <<"missing authorization code">>}; {Code, <<>>} -> {ok, Code}; @@ -312,6 +323,26 @@ query_pair(Q) -> Query = maps:from_list(uri_string:dissect_query(Q)), {maps:get(<<"code">>, Query, <<>>), maps:get(<<"state">>, Query, <<>>)}. +%% The `iss` a pasted callback url or query string carries (RFC 9207), or none. +input_issuer(Text0) -> + Text = string:trim(unicode:characters_to_binary(Text0)), + Query = case uri_string:parse(Text) of + #{scheme := _, host := _, query := Q} -> Q; + _ -> string:trim(Text, leading, "?#") + end, + try maps:get(<<"iss">>, maps:from_list(uri_string:dissect_query(Query)), none) + catch _:_ -> none + end. + +%% The `iss` the authorization response carried, for an `exchange` that +%% checks it (RFC 9207); none when it carried none. Exchange runs in the flow +%% process that received the response. +callback_issuer() -> + case get(?ISSUER) of + Issuer when is_binary(Issuer) -> {some, Issuer}; + _ -> none + end. + %% ---- creds.json accounts ------------------------------------------------ id(Account, Credential) -> element(2, Account(Credential)). @@ -460,6 +491,8 @@ create_identified(Home, Id, Provider, Login0, Intent, Flows) -> true -> Flow#{<<"url">> => Url}; false -> exit(Pid, kill), failed_record(Flow, <<"Provider authorization URL is invalid.">>) end; + {Id, refused, Reason} -> + finish(Flow#{<<"state">> => <<"failed">>, <<"failure">> => bounded(Reason, 4096)}); {Id, failed, Reason} -> Failure = case element(7, Login) of {device, _} when is_binary(Reason), Reason =/= <<>> -> bounded(Reason, 4096); @@ -520,19 +553,27 @@ store_identified(Id, Home, Store, Credential0, Account, Flows) -> true = is_map(Credential0), RawId = id(Account, Credential0), true = is_binary(RawId) andalso byte_size(RawId) > 0, Creds = albedo_settings_store:read(Home, <<"creds.json">>), - Accounts = albedo_settings_store:object(<<"accounts">>, Creds), Values = albedo_credentials:values(Accounts, Store), - Previous = [V || V <- Values, id(Account, V) =:= RawId], - PublicId = case Previous of [P | _] -> maps:get(<<"_albedo_account_id">>, P, token(16)); [] -> token(16) end, - {account, _, Label, Detail, _} = Account(Credential0), - Credential = Credential0#{<<"_albedo_account_id">> => PublicId, - <<"_albedo_account_meta">> => #{<<"provider">> => maps:get(<<"provider">>, Flow), <<"label">> => bounded(Label, 256), <<"detail">> => bounded(Detail, 4096)}}, - NewValues = case Previous of [] -> Values ++ [Credential]; _ -> [case id(Account, V) =:= RawId of true -> Credential; false -> V end || V <- Values] end, + {PublicId, NextCreds} = stored_credential(Creds, Store, Credential0, Account, RawId, maps:get(<<"provider">>, Flow)), Next = finish(Flow#{<<"state">> => <<"complete">>, <<"progress">> => <<>>, <<"failure">> => null, <<"account_ids">> => [PublicId]}), - albedo_settings_store:commit_group(Home, #{<<"creds.json">> => Creds#{<<"accounts">> => albedo_credentials:put_values(Accounts, Store, NewValues)}, - <<"oauth-logins.json">> => Records#{Id => Next}}), Next + albedo_settings_store:commit_group(Home, #{<<"creds.json">> => NextCreds, <<"oauth-logins.json">> => Records#{Id => Next}}), Next end), {{ok, hd(maps:get(<<"account_ids">>, Completed))}, Flows#{Id := Active#{record => Completed}}}. +%% Creds with a signed-in credential in place, and the id it is known by. An +%% MCP server's sign-in replaces that server's tokens; any other replaces the +%% account with the same identity or joins the store's accounts. +stored_credential(Creds, <<"mcp:", Server/binary>> = Store, Credential, _, _, _) -> + {Store, albedo_mcp_oauth:signed_in(Creds, Server, Credential)}; +stored_credential(Creds, Store, Credential0, Account, RawId, Provider) -> + Accounts = albedo_settings_store:object(<<"accounts">>, Creds), Values = albedo_credentials:values(Accounts, Store), + Previous = [V || V <- Values, id(Account, V) =:= RawId], + PublicId = case Previous of [P | _] -> maps:get(<<"_albedo_account_id">>, P, token(16)); [] -> token(16) end, + {account, _, Label, Detail, _} = Account(Credential0), + Credential = Credential0#{<<"_albedo_account_id">> => PublicId, + <<"_albedo_account_meta">> => #{<<"provider">> => Provider, <<"label">> => bounded(Label, 256), <<"detail">> => bounded(Detail, 4096)}}, + NewValues = case Previous of [] -> Values ++ [Credential]; _ -> [case id(Account, V) =:= RawId of true -> Credential; false -> V end || V <- Values] end, + {PublicId, Creds#{<<"accounts">> => albedo_credentials:put_values(Accounts, Store, NewValues)}}. + stopped(Flows, Pid) -> maps:map(fun (Id, #{pid := P, home := Home, record := Record} = F) when P =:= Pid -> case terminal(Record) of diff --git a/src/albedo/harness/extension.gleam b/src/albedo/harness/extension.gleam index 6641ee2c5..56deb104f 100644 --- a/src/albedo/harness/extension.gleam +++ b/src/albedo/harness/extension.gleam @@ -305,6 +305,12 @@ pub type Plugin { ModelProviderPlugin(provider: ModelProvider) /// A browser sign-in the daemon runs on behalf of clients. LoginPlugin(login: oauth.Login) + /// Sign-ins named at request time, such as one per configured MCP server. + /// `resolve(home, provider)` is None for a provider it does not serve, and + /// may reach the network to describe one it does. + LoginResolverPlugin( + resolve: fn(String, String) -> Option(Result(oauth.Login, String)), + ) /// HTTP routes the daemon serves under `/extensions//` while the extension /// is enabled globally. ServicePlugin(service: Service) @@ -1012,6 +1018,24 @@ pub fn logins(installed: List(Extension)) -> List(oauth.Login) { }) } +/// The sign-in a resolver names for `provider`, when no static one does. +pub fn resolve_login( + installed: List(Extension), + home: String, + provider: String, +) -> Option(Result(oauth.Login, String)) { + plugin_values(installed, fn(_, plugin) { + case plugin { + LoginResolverPlugin(resolve) -> Ok(resolve) + _ -> Error(Nil) + } + }) + |> list.find_map(fn(resolve) { + resolve(home, provider) |> option.to_result(Nil) + }) + |> option.from_result +} + pub fn upstream( installed: List(Extension), context: ModelContext, diff --git a/src/albedo/harness/extension/selection.gleam b/src/albedo/harness/extension/selection.gleam index e3bf0a902..46af27edd 100644 --- a/src/albedo/harness/extension/selection.gleam +++ b/src/albedo/harness/extension/selection.gleam @@ -567,6 +567,7 @@ pub fn summaries( extension.ModelsPlugin(_) -> "models" extension.ModelProviderPlugin(_) -> "model_provider" extension.LoginPlugin(_) -> "login" + extension.LoginResolverPlugin(_) -> "login" extension.ServicePlugin(_) -> "service" extension.StartupPlugin(_) -> "startup" extension.GlancePlugin(..) -> "glance" diff --git a/src/albedo/harness/extensions/antigravity/extension.gleam b/src/albedo/harness/extensions/antigravity/extension.gleam index bf32621eb..94f09d1db 100644 --- a/src/albedo/harness/extensions/antigravity/extension.gleam +++ b/src/albedo/harness/extensions/antigravity/extension.gleam @@ -84,6 +84,7 @@ pub fn login(endpoints: Endpoints) -> oauth.Login { #("access_type", "offline"), #("prompt", "consent"), ]) + |> Ok }, fn(grant, code, progress) { native_exchange(code, grant.redirect, progress, endpoints) diff --git a/src/albedo/harness/extensions/claude/extension.gleam b/src/albedo/harness/extensions/claude/extension.gleam index d7ce2f29b..5b7367ff0 100644 --- a/src/albedo/harness/extensions/claude/extension.gleam +++ b/src/albedo/harness/extensions/claude/extension.gleam @@ -75,6 +75,7 @@ fn login() -> oauth.Login { #("code_challenge_method", "S256"), #("state", grant.state), ]) + |> Ok }, fn(grant, code, _progress) { native_exchange(code, grant.state, grant.verifier, grant.redirect) diff --git a/src/albedo/harness/extensions/codex/extension.gleam b/src/albedo/harness/extensions/codex/extension.gleam index 817568c10..df823eae2 100644 --- a/src/albedo/harness/extensions/codex/extension.gleam +++ b/src/albedo/harness/extensions/codex/extension.gleam @@ -136,6 +136,7 @@ fn login() -> oauth.Login { #("codex_cli_simplified_flow", "true"), #("originator", "albedo"), ]) + |> Ok }, fn(grant, code, _progress) { native_exchange(code, grant.verifier, grant.redirect) diff --git a/src/albedo/harness/extensions/colab/extension.gleam b/src/albedo/harness/extensions/colab/extension.gleam index db56efa4f..fb3d536fe 100644 --- a/src/albedo/harness/extensions/colab/extension.gleam +++ b/src/albedo/harness/extensions/colab/extension.gleam @@ -86,6 +86,7 @@ pub fn login() -> oauth.Login { #("access_type", "offline"), #("prompt", "consent"), ]) + |> Ok }, fn(grant, code, progress) { native_exchange(code, grant.redirect, progress) diff --git a/src/albedo/harness/extensions/mcp/albedo_mcp.erl b/src/albedo/harness/extensions/mcp/albedo_mcp.erl index 62f664f51..cd952ce94 100644 --- a/src/albedo/harness/extensions/mcp/albedo_mcp.erl +++ b/src/albedo/harness/extensions/mcp/albedo_mcp.erl @@ -1,7 +1,7 @@ -module(albedo_mcp). -export([check_candidate/3]). --export([prepare/5, definitions/1, context/1, offline/1, observe/3, only/2, observer/1, closer/1, +-export([prepare/5, definitions/1, context/1, offline/1, sign_in/1, observe/3, only/2, observer/1, closer/1, call/3, close/1, url_allowed/1, validate_settings/3]). -define(CLIENT, 'albedo@harness@extensions@mcp@client'). @@ -37,8 +37,9 @@ prepare(ConfigJson, Ledger, Session, Lookup, Save) -> open_servers(Candidates, Preferences, Retry, Cache) -> open_servers(Candidates, [], [], Preferences, Retry, Cache). -%% A server that cannot start is left out and named; one that is badly -%% configured still fails the whole preparation. +%% A server that cannot start, or that needs the user to sign in, is left +%% out and named; one that is badly configured still fails the whole +%% preparation. open_servers([], Joined, Offline, _, Retry, _) -> finish(lists:reverse(Joined), lists:reverse(Offline), Retry); open_servers([{Name, Config} | Rest], Joined, Offline, Preferences, Retry, Cache) -> @@ -47,7 +48,9 @@ open_servers([{Name, Config} | Rest], Joined, Offline, Preferences, Retry, Cache {true, {ok, true}} -> case join(Name, Config, Cache) of {ok, Server} -> open_servers(Rest, [Server | Joined], Offline, Preferences, Retry, Cache); - {unavailable, _} -> open_servers(Rest, Joined, [{Name, Config} | Offline], Preferences, Retry, Cache); + {unavailable, _} -> open_servers(Rest, Joined, [{Name, Config, unavailable} | Offline], Preferences, Retry, Cache); + {needs_sign_in, _, Reason} -> + open_servers(Rest, Joined, [{Name, Config, {needs_sign_in, Reason}} | Offline], Preferences, Retry, Cache); {error, Reason} -> close_joined(Joined), {error, Reason} end; {false, _} -> open_servers(Rest, Joined, Offline, Preferences, Retry, Cache); @@ -85,18 +88,23 @@ join(_, _, _) -> {error, <<"MCP server configuration is invalid">>}. close_joined(Joined) -> close_servers([Server || {_, _, _, _, {connected, Server, _, _}} <- Joined]). -finish(Joined, Offline0, Retry) -> - Offline = lists:keysort(1, Offline0), +finish(Joined, Offline1, Retry) -> + Offline0 = lists:keysort(1, Offline1), + Offline = [{Name, Config} || {Name, Config, _} <- Offline0], + SignIn = [{Name, Reason} || {Name, _, {needs_sign_in, Reason}} <- Offline0], Operations = lists:append([Ops || {_, _, _, {Ops, _}, _} <- Joined]), - Context = [Text || {_, _, _, {_, Text}, _} <- Joined], + Context = [Text || {_, _, _, {_, Text}, _} <- Joined] + ++ [<<"MCP server '", Name/binary, "' needs the user to sign in (", Reason/binary, + "); its tools join once they sign in from the MCP settings.">> || {Name, Reason} <- SignIn], Names = [maps:get(advertised, O) || O <- Operations], case length(Operations) =< 512 andalso length(Names) =:= length(lists:usort(Names)) of true -> Watcher = watch(Offline, Retry), Servers = [link(Name, Config, Secrets, Catalogue, Start, Watcher) || {Name, Config, Secrets, Catalogue, Start} <- Joined], - {ok, #{servers => Servers, operations => Operations, offline => [N || {N, _} <- Offline], - watcher => Watcher, + {ok, #{servers => Servers, operations => Operations, + offline => [N || {N, _} <- Offline, not lists:keymember(N, 1, SignIn)], + sign_in => [N || {N, _} <- SignIn], watcher => Watcher, context => iolist_to_binary(lists:join("\n", Context))}}; false -> close_joined(Joined), @@ -118,10 +126,11 @@ open_server_with_secrets(Name, Config, Secrets) -> try Startup = positive_ms(maps:get(<<"startupTimeoutMs">>, Config, ?DEFAULT_STARTUP_MS)), Call = positive_ms(maps:get(<<"callTimeoutMs">>, Config, ?DEFAULT_CALL_MS)), - case ?CLIENT:start(transport(Config, Secrets), Startup) of + case ?CLIENT:start(transport(Name, Config, Secrets), Startup) of {ok, Client} -> {ok, #{name => Name, client => Client, pid => ?CLIENT:pid(Client), call_timeout => Call, config => Config}}; + {error, {needs_sign_in, Reason}} -> {needs_sign_in, Name, Reason}; {error, _} -> {unavailable, Name} end catch @@ -141,8 +150,10 @@ connect(Name, Config, Secrets) -> %% Names one server's configuration and credentials, so a saved catalogue %% is only trusted for the setup that produced it. +%% A sign-in's tokens change on every refresh, so they are left out. fingerprint(Config, Secrets) -> - binary:encode_hex(crypto:hash(sha256, term_to_binary({Config, Secrets}, [deterministic])), lowercase). + Stable = maps:remove(<<"oauth">>, Secrets), + binary:encode_hex(crypto:hash(sha256, term_to_binary({Config, Stable}, [deterministic])), lowercase). encode_catalogue({Ops, Text}) -> term_to_binary({?CATALOGUE_VERSION, Ops, Text}). @@ -155,18 +166,31 @@ saved({some, Encoded}) when is_binary(Encoded) -> saved(_) -> none. %% The client's transport: an https server is reached through the provider -%% transport, verified against albedo_trust's roots. -transport(#{<<"type">> := <<"http">>, <<"url">> := Url} = Config, Secrets) +%% transport, verified against albedo_trust's roots. An HTTP server without +%% an authorization header of its own may sign in with OAuth. +transport(Name, #{<<"type">> := <<"http">>, <<"url">> := Url} = Config, Secrets) when is_binary(Url), byte_size(Url) > 0 -> case url_allowed(Url) of true -> ok; false -> erlang:error(unsafe_url) end, - {http, Url, http_headers(Config, Secrets)}; -transport(#{<<"type">> := <<"stdio">>, <<"command">> := Command} = Config, Secrets) + Headers = http_headers(Config, Secrets), + Auth = case lists:keymember(<<"authorization">>, 1, [{string:lowercase(K), V} || {K, V} <- Headers]) of + true -> none; + false -> {some, oauth(Name, Url)} + end, + {http, Url, Headers, Auth}; +transport(_, #{<<"type">> := <<"stdio">>, <<"command">> := Command} = Config, Secrets) when is_binary(Command), byte_size(Command) > 0 -> Args = string_list(maps:get(<<"args">>, Config, [])), Cwd = optional_binary(maps:get(<<"cwd">>, Config, null)), {stdio, executable(<<"python3">>), [launcher(), Cwd, executable(Command) | Args], scoped_env(maps:get(<<"env">>, Config, #{}), maps:get(<<"env">>, Secrets, #{}))}; -transport(_, _) -> erlang:error(invalid_transport). +transport(_, _, _) -> erlang:error(invalid_transport). + +%% The client.Auth for one server's OAuth sign-in in this daemon's home. +oauth(Name, Url) -> + Home = albedo_extension_settings:home(), + {auth, + fun(Refused) -> albedo_mcp_oauth:access(Home, Name, Url, Refused) end, + fun(Status, Challenge) -> albedo_mcp_oauth:challenged(Home, Name, Url, Status, Challenge) end}. url_allowed(Url) -> try @@ -475,8 +499,10 @@ call(#{servers := Servers, operations := Operations}, Advertised, ArgumentsJson) case timed_dispatch(Operation, Server, Arguments) of {ok, Value} -> encode_result(Value); {error, timeout} -> {error, <<"MCP request timed out; outcome unknown. Inspect effects before any retry.">>}; + {error, {unauthorized, Reason}} -> {error, needs_sign_in(maps:get(name, Link), Reason)}; {error, _} -> {error, <<"MCP request failed; outcome unknown. Inspect effects before any retry.">>} end; + {needs_sign_in, Reason} -> {error, needs_sign_in(maps:get(name, Link), Reason)}; unavailable -> {error, unavailable(maps:get(name, Link))} end catch @@ -644,8 +670,12 @@ connector(#{client := Client, waiters := Waiters, dialler := Dialler} = State) - again -> connector(refresh(Next#{refresh := idle})); _ -> connector(Next#{refresh := idle}) end; - {dialled, Dialler, _} -> - [Alias ! {Alias, unavailable} || Alias <- Waiters], + {dialled, Dialler, Failed} -> + Answer = case Failed of + {needs_sign_in, _, Reason} -> {needs_sign_in, Reason}; + _ -> unavailable + end, + [Alias ! {Alias, Answer} || Alias <- Waiters], connector(State#{waiters => [], dialler => none}); {'DOWN', Monitor, process, _, _} -> connector(State#{client => none}); @@ -693,20 +723,30 @@ optional_binary(_) -> erlang:error(invalid_value). unavailable(Name) -> <<"MCP server '", Name/binary, "' is unavailable">>. +%% A request the server refused before running it, for want of a sign-in. +needs_sign_in(Name, Reason) -> + <<"MCP server '", Name/binary, "' needs the user to sign in: ", Reason/binary, + ". The request did not run; ask the user to sign in from the MCP settings.">>. + %% The servers that were configured and enabled but could not be reached. offline(#{offline := Offline}) -> Offline. +%% The servers left out because they need the user to sign in. +sign_in(#{sign_in := Names}) -> Names. + probe(Name, Config) -> case open_server(Name, Config) of {ok, Server} -> close_servers([Server]), true; _ -> false end. +%% A server that asks for a sign-in is saved, so the user can sign in to it. check_candidate(Name, Config, Secrets) -> case maps:get(<<"enabled">>, Config, true) of false -> {ok, nil}; true -> case open_server_with_secrets(Name, Config, Secrets) of {ok, Server} -> close_servers([Server]), {ok, nil}; + {needs_sign_in, _, _} -> {ok, nil}; _ -> {error, unavailable(Name)} end end. @@ -803,6 +843,8 @@ validate_settings(Name, Server, Secret) -> true = is_map(Secret), maps:foreach(fun (<<"bearerToken">>, null) -> ok; + (<<"oauth">>, Record) -> true = is_map(Record); + (<<"oauthClient">>, #{<<"clientId">> := Id}) -> true = is_binary(Id); (<<"bearerToken">>, Token) when is_binary(Token) -> false = contains_newline(Token); (Field, null) when Field =:= <<"headers">>; Field =:= <<"env">> -> ok; (Field, Changes) when Field =:= <<"headers">>; Field =:= <<"env">> -> diff --git a/src/albedo/harness/extensions/mcp/albedo_mcp_oauth.erl b/src/albedo/harness/extensions/mcp/albedo_mcp_oauth.erl new file mode 100644 index 000000000..974fbc5fe --- /dev/null +++ b/src/albedo/harness/extensions/mcp/albedo_mcp_oauth.erl @@ -0,0 +1,572 @@ +-module(albedo_mcp_oauth). +%% OAuth for streamable HTTP MCP servers, as the MCP authorization spec asks +%% (2025-11-25 and 2026-07-28 basic/authorization): Protected Resource +%% Metadata discovery (RFC 9728), authorization server metadata (RFC 8414 and +%% OpenID Connect discovery, in the spec's order), a configured client or +%% Dynamic Client Registration (RFC 7591), the authorization code flow with +%% PKCE S256 and the resource parameter (RFC 8707), refresh, and step-up on +%% insufficient_scope. albedo_oauth runs the browser half: its loopback +%% listener, state check and paste race. +%% +%% Each server's sign-in lives in creds.json under mcp..oauth, never +%% in extension settings. Its `state` is needs_sign_in, signed_in or +%% signed_out; `resource` is the server URL it belongs to, so a record left +%% by a server of the same name at another URL is never sent anywhere. + +-export([access/4, challenged/5, discover/2, authorize/2, exchange/4, account/2, + signed_in/3, signed_out/1, parse_challenge/1]). + +-define(SKEW_MS, 60000). +-define(REFRESH_WAIT_MS, 30000). +-define(FETCH_MS, 15000). +-define(MAX_BODY, 1048576). + +%% ---- tokens for requests ------------------------------------------------ + +%% The bearer token for the next request to `Url`: {ok, none} when the server +%% has no sign-in, {ok, {some, Token}}, or {error, Reason} when it needs one. +%% `Rejected` is the token the server just refused with 401, which is +%% refreshed once unless another request already replaced it. Refreshes of +%% one server are single-flight; a refresh the authorization server refuses +%% marks the server as needing sign-in instead of trying again. +access(Home, Name, Url, Rejected) -> + case record(Home, Name, Url) of + none -> {ok, none}; + Record -> + case usable(Record, Rejected) of + {ok, Token} -> {ok, {some, Token}}; + stale -> refreshed(Home, Name, Url, Rejected); + {error, Reason} -> {error, Reason} + end + end. + +usable(#{<<"state">> := <<"signed_in">>, <<"access">> := Token} = Record, Rejected) when is_binary(Token) -> + Fresh = case maps:get(<<"expires">>, Record, null) of + Expires when is_integer(Expires) -> Expires - now_ms() > ?SKEW_MS; + _ -> true + end, + case {Fresh, Rejected} of + {true, none} -> {ok, Token}; + {true, {some, Other}} when Other =/= Token -> {ok, Token}; + _ -> stale + end; +usable(Record, _) -> {error, reason(Record)}. + +refreshed(Home, Name, Url, Rejected) -> + Run = fun() -> + case record(Home, Name, Url) of + none -> {ok, none}; + Record -> + case usable(Record, Rejected) of + {ok, Token} -> {ok, {some, Token}}; + {error, Reason} -> {error, Reason}; + stale -> refresh(Home, Name, Url, Record, Rejected) + end + end + end, + case albedo_lock:trans({?MODULE, Home, Name}, Run, ?REFRESH_WAIT_MS) of + {ok, Result} -> Result; + busy -> {error, <<"the sign-in is still refreshing">>} + end. + +refresh(Home, Name, Url, #{<<"refresh">> := Refresh} = Record, Rejected) when is_binary(Refresh) -> + Form = [{<<"grant_type">>, <<"refresh_token">>}, {<<"refresh_token">>, Refresh}, + {<<"resource">>, maps:get(<<"resourceParameter">>, Record, Url)}], + case token_request(Record, Form) of + {ok, Tokens} -> + Next = with_tokens(Record, Tokens, maps:get(<<"scope">>, Record, null)), + update(Home, Name, Url, fun(_) -> Next end), + {ok, {some, maps:get(<<"access">>, Next)}}; + {refused, _} -> + Reason = <<"the saved sign-in expired; sign in again">>, + update(Home, Name, Url, fun(Current) -> needs_sign_in(Current, Reason) end), + {error, Reason}; + {error, Reason} -> + %% The authorization server could not be asked: a token that has + %% not been refused yet is still worth sending. + case {Rejected, maps:get(<<"access">>, Record, null)} of + {none, Token} when is_binary(Token) -> {ok, {some, Token}}; + _ -> {error, <<"could not refresh the sign-in: ", Reason/binary>>} + end + end; +refresh(Home, Name, Url, _, _) -> + Reason = <<"the sign-in expired; sign in again">>, + update(Home, Name, Url, fun(Current) -> needs_sign_in(Current, Reason) end), + {error, Reason}. + +%% Records what a 401 or 403 from the server says and returns the reason the +%% request cannot go on. A 401 to a server without a sign-in, or one whose +%% token was refused even after a refresh, needs sign-in; a 403 +%% insufficient_scope keeps the token and asks for the wider scope, the +%% union of what was asked before and what the challenge names (2026-07-28 +%% basic/authorization, "Step-Up Authorization Flow"). +challenged(Home, Name, Url, Status, Header) -> + Challenge = parse_challenge(Header), + Metadata = maps:get(<<"resource_metadata">>, Challenge, null), + Scope = maps:get(<<"scope">>, Challenge, null), + case {Status, maps:get(<<"error">>, Challenge, null)} of + {403, <<"insufficient_scope">>} -> + Wider = union(requested(record(Home, Name, Url)), Scope), + Reason = <<"the server needs wider access (", Wider/binary, "); sign in again to grant it">>, + update(Home, Name, Url, fun(Current) -> + with_challenge(Current#{<<"stepUp">> => Wider, <<"reason">> => Reason}, Metadata, null) + end), + Reason; + _ -> + Reason = case record(Home, Name, Url) of + #{<<"state">> := <<"signed_in">>} -> <<"the server refused the saved sign-in; sign in again">>; + #{<<"state">> := <<"signed_out">>} -> <<"signed out">>; + _ -> <<"the server asks you to sign in">> + end, + update(Home, Name, Url, fun(Current) -> + with_challenge(needs_sign_in(Current, Reason), Metadata, Scope) + end), + Reason + end. + +with_challenge(Record, Metadata, Scope) -> + Keep = fun(_, null, R) -> R; (Key, Value, R) when is_binary(Value) -> R#{Key => Value}; (_, _, R) -> R end, + Keep(<<"challengeScope">>, Scope, Keep(<<"resourceMetadata">>, Metadata, Record)). + +needs_sign_in(Record, Reason) -> + (maps:without([<<"access">>, <<"refresh">>, <<"expires">>], Record))#{ + <<"state">> => <<"needs_sign_in">>, <<"reason">> => Reason}. + +%% A record whose tokens are dropped by the user; what the server asked for +%% and the client it registered stay for the next sign-in. +signed_out(Record) when is_map(Record) -> + (maps:without([<<"access">>, <<"refresh">>, <<"expires">>, <<"reason">>, <<"label">>], Record))#{ + <<"state">> => <<"signed_out">>}; +signed_out(_) -> #{<<"state">> => <<"signed_out">>}. + +reason(#{<<"state">> := <<"signed_out">>}) -> <<"signed out">>; +reason(#{<<"reason">> := Reason}) when is_binary(Reason) -> Reason; +reason(_) -> <<"the server asks you to sign in">>. + +requested(#{<<"stepUp">> := Scope}) when is_binary(Scope) -> Scope; +requested(#{<<"scope">> := Scope}) when is_binary(Scope) -> Scope; +requested(#{<<"challengeScope">> := Scope}) when is_binary(Scope) -> Scope; +requested(_) -> null. + +union(null, null) -> <<>>; +union(A, null) -> A; +union(null, B) -> B; +union(A, B) -> + Words = string:lexemes(A, " ") ++ [W || W <- string:lexemes(B, " "), not lists:member(W, string:lexemes(A, " "))], + iolist_to_binary(lists:join(<<" ">>, Words)). + +%% The `Bearer` parameters of a WWW-Authenticate value (RFC 6750 section 3, +%% RFC 9728 section 5.1), lower-cased names to unquoted values. +parse_challenge(Header) when is_binary(Header) -> + Bearer = case re:run(Header, <<"(?i)\\bbearer\\b(.*)">>, [{capture, [1], binary}]) of + {match, [Rest]} -> Rest; + nomatch -> <<>> + end, + case re:run(Bearer, <<"([A-Za-z_]+)\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|([^,\\s]*))">>, + [global, {capture, all_but_first, binary}]) of + {match, Pairs} -> + maps:from_list([{string:lowercase(Key), unquote(Quoted, Token)} || [Key, Quoted, Token | _] <- [P ++ [<<>>] || P <- Pairs]]); + nomatch -> #{} + end; +parse_challenge(_) -> #{}. + +unquote(<<>>, Token) -> Token; +unquote(Quoted, _) -> re:replace(Quoted, <<"\\\\(.)">>, <<"\\1">>, [global, {return, binary}]). + +%% ---- sign-in ------------------------------------------------------------ + +%% Everything a sign-in needs before the browser opens: the server's +%% protected resource metadata, its authorization server's metadata, the +%% scope to ask for and how albedo is known to that server. +discover(Home, Name) -> + try + Url = server_url(Home, Name), + Record = case record(Home, Name, Url) of none -> #{}; R -> R end, + Resource = protected_resource(Url, maps:get(<<"resourceMetadata">>, Record, null)), + Parameter = resource_parameter(Url, maps:get(<<"resource">>, Resource, null)), + Issuer = case maps:get(<<"authorization_servers">>, Resource, []) of + [First | _] when is_binary(First) -> First; + _ -> fail(<<"the server names no authorization server">>) + end, + allowed_endpoint(Url, Issuer), + Metadata = authorization_server(Url, Issuer), + Methods = maps:get(<<"code_challenge_methods_supported">>, Metadata, []), + case is_list(Methods) andalso lists:member(<<"S256">>, Methods) of + true -> ok; + false -> fail(<<"the authorization server does not support PKCE with S256">>) + end, + Client = client(Home, Name, Metadata), + {ok, #{home => Home, name => Name, url => Url, resource => Parameter, + metadata_url => maps:get(<<"resourceMetadata">>, Record, null), + issuer => Issuer, metadata => Metadata, client => Client, + scope => scope(Record, Resource, Metadata)}} + catch + throw:{mcp_oauth, Reason} -> {error, Reason}; + _:_ -> {error, <<"could not prepare the sign-in">>} + end. + +server_url(Home, Name) -> + Extensions = albedo_settings_store:read(Home, <<"extensions.json">>), + Servers = albedo_settings_store:object(<<"servers">>, albedo_settings_store:object(<<"mcp">>, Extensions)), + case maps:get(Name, Servers, null) of + #{<<"type">> := <<"http">>, <<"url">> := Url} when is_binary(Url) -> Url; + null -> fail(<<"no MCP server is named ", Name/binary>>); + _ -> fail(<<"only HTTP MCP servers sign in">>) + end. + +%% The resource metadata the 401 named, else the well-known locations in the +%% spec's order: under the endpoint's path, then at the root. +protected_resource(Url, Named) -> + #{scheme := Scheme, host := Host} = Parsed = uri_string:parse(Url), + Origin = origin(Scheme, Host, maps:get(port, Parsed, undefined)), + Path = string:trim(maps:get(path, Parsed, <<>>), trailing, "/"), + WellKnown = [<> || Path =/= <<>>] + ++ [<>], + Candidates = case Named of + Value when is_binary(Value) -> allowed_endpoint(Url, Value), [Value]; + _ -> WellKnown + end, + first_document(Candidates, fun(Document) -> is_list(maps:get(<<"authorization_servers">>, Document, null)) end, + <<"the server publishes no protected resource metadata">>). + +%% The resource parameter: the metadata's `resource` when the server URL is +%% it or lies under it (RFC 9728 section 3.3), else the server URL. +resource_parameter(Url, null) -> canonical(Url); +resource_parameter(Url, Resource) when is_binary(Resource) -> + Canonical = canonical(Resource), + Server = canonical(Url), + case Server =:= Canonical orelse string:prefix(Server, <>) =/= nomatch of + true -> Canonical; + false -> fail(<<"the server's metadata names another resource">>) + end; +resource_parameter(_, _) -> fail(<<"the server's metadata names no valid resource">>). + +canonical(Url) -> + #{scheme := Scheme, host := Host} = Parsed = uri_string:parse(Url), + Path = string:trim(maps:get(path, Parsed, <<>>), trailing, "/"), + Query = case maps:get(query, Parsed, undefined) of undefined -> <<>>; Q -> <<"?", Q/binary>> end, + <<(origin(string:lowercase(Scheme), string:lowercase(Host), maps:get(port, Parsed, undefined)))/binary, Path/binary, Query/binary>>. + +origin(Scheme, Host, Port) -> + Bracketed = case binary:match(Host, <<":">>) of nomatch -> Host; _ -> <<"[", Host/binary, "]">> end, + case Port of + undefined -> <>; + _ -> <> + end. + +%% RFC 8414 metadata, then OpenID Connect discovery, as the spec orders them +%% for an issuer with and without a path; a document whose `issuer` is not +%% the one asked for is not used. +authorization_server(Url, Issuer) -> + #{scheme := Scheme, host := Host} = Parsed = uri_string:parse(Issuer), + Origin = origin(Scheme, Host, maps:get(port, Parsed, undefined)), + Path = string:trim(maps:get(path, Parsed, <<>>), trailing, "/"), + Candidates = case Path of + <<>> -> [<>, + <>]; + _ -> [<>, + <>, + <>] + end, + Metadata = first_document(Candidates, fun(Document) -> maps:get(<<"issuer">>, Document, null) =:= Issuer end, + <<"the authorization server publishes no metadata for its issuer">>), + lists:foreach(fun(Key) -> + case maps:get(Key, Metadata, null) of + Endpoint when is_binary(Endpoint) -> allowed_endpoint(Url, Endpoint); + null when Key =:= <<"registration_endpoint">> -> ok; + _ -> fail(<<"the authorization server metadata has no ", Key/binary>>) + end + end, [<<"authorization_endpoint">>, <<"token_endpoint">>, <<"registration_endpoint">>]), + Metadata. + +first_document([], _, Reason) -> fail(Reason); +first_document([Candidate | Rest], Valid, Reason) -> + case fetch_json(get, Candidate, [], none) of + {ok, 200, Document} when is_map(Document) -> + case Valid(Document) of + true -> Document; + false -> first_document(Rest, Valid, Reason) + end; + _ -> first_document(Rest, Valid, Reason) + end. + +%% Authorization server endpoints must use https (2025-11-25 +%% basic/authorization, "Communication Security"); a server the user reaches +%% over plain http on a network they trust may name plain http ones too. +allowed_endpoint(Url, Endpoint) -> + Http = string:prefix(Url, <<"http://">>) =/= nomatch, + case albedo_mcp:url_allowed(Endpoint) of + true -> + case string:prefix(Endpoint, <<"https://">>) =/= nomatch orelse Http of + true -> ok; + false -> fail(<<"the authorization server must use https">>) + end; + false -> fail(<<"the authorization server named an invalid URL">>) + end. + +%% The scope to ask for: a pending step-up, else the 401's scope, else the +%% resource's scopes_supported (2026-07-28 basic/authorization, "Scope +%% Selection Strategy"), with offline_access when the authorization server +%% lists it, so a refresh token may come back. +scope(Record, Resource, Metadata) -> + Base = case requested(Record) of + null -> + case maps:get(<<"scopes_supported">>, Resource, null) of + Scopes when is_list(Scopes), Scopes =/= [] -> iolist_to_binary(lists:join(<<" ">>, Scopes)); + _ -> null + end; + Scope -> Scope + end, + Offline = lists:member(<<"offline_access">>, case maps:get(<<"scopes_supported">>, Metadata, []) of L when is_list(L) -> L; _ -> [] end), + case {Base, Offline} of + {null, true} -> <<"offline_access">>; + {null, false} -> null; + {_, true} -> union(Base, <<"offline_access">>); + {_, false} -> Base + end. + +%% How albedo is known to the authorization server, in the spec's order +%% (2026-07-28 basic/authorization/client-registration): a client the user +%% configured for this server, then Dynamic Client Registration. Client ID +%% Metadata Documents come between them in the spec, but they need an https +%% URL albedo can host the document at, and a local daemon has none. +client(Home, Name, Metadata) -> + case configured_client(Home, Name) of + {ok, Client} -> Client; + none -> + case maps:get(<<"registration_endpoint">>, Metadata, null) of + Endpoint when is_binary(Endpoint) -> {register, Endpoint}; + _ -> fail(<<"the authorization server offers no client registration; configure a client id for this server">>) + end + end. + +configured_client(Home, Name) -> + case albedo_credentials:mcp(Home) of + {ok, #{Name := #{<<"oauthClient">> := #{<<"clientId">> := Id} = Client}}} when is_binary(Id), Id =/= <<>> -> + {ok, {configured, Id, maps:get(<<"clientSecret">>, Client, null)}}; + _ -> none + end. + +%% The authorize URL for one grant, registering albedo first when the +%% authorization server has no client for this redirect yet. +authorize(#{metadata := Metadata, resource := Resource, scope := Scope} = Plan, {grant, Redirect, State, _, Challenge}) -> + try + {Id, _, _} = registered(Plan, Redirect), + Query = [{<<"response_type">>, <<"code">>}, {<<"client_id">>, Id}, {<<"redirect_uri">>, Redirect}, + {<<"code_challenge">>, Challenge}, {<<"code_challenge_method">>, <<"S256">>}, + {<<"state">>, State}, {<<"resource">>, Resource}] + ++ [{<<"scope">>, Scope} || is_binary(Scope)], + Endpoint = maps:get(<<"authorization_endpoint">>, Metadata), + Separator = case binary:match(Endpoint, <<"?">>) of nomatch -> <<"?">>; _ -> <<"&">> end, + {ok, <>} + catch + throw:{mcp_oauth, Reason} -> {error, Reason}; + _:_ -> {error, <<"could not start the sign-in">>} + end. + +%% {ClientId, Secret, AuthMethod}: the configured client, a registration this +%% authorization server issued for `Redirect`, or a new one (RFC 7591), kept +%% per issuer so another authorization server never sees it. +registered(#{client := {configured, Id, Secret}}, _) -> + {Id, Secret, case Secret of null -> <<"none">>; _ -> <<"client_secret_basic">> end}; +registered(#{client := {register, Endpoint}, home := Home, name := Name, url := Url, issuer := Issuer} = Plan, Redirect) -> + Saved = case record(Home, Name, Url) of + #{<<"registration">> := #{<<"issuer">> := Issuer, <<"redirectUri">> := Redirect} = R} -> R; + _ -> none + end, + case Saved of + #{<<"clientId">> := Id} = R2 -> + {Id, maps:get(<<"clientSecret">>, R2, null), maps:get(<<"authMethod">>, R2, <<"none">>)}; + none -> + Request = #{<<"client_name">> => <<"albedo">>, <<"redirect_uris">> => [Redirect], + <<"grant_types">> => [<<"authorization_code">>, <<"refresh_token">>], + <<"response_types">> => [<<"code">>], <<"token_endpoint_auth_method">> => <<"none">>, + <<"application_type">> => <<"native">>}, + Body = iolist_to_binary(json:encode(case maps:get(scope, Plan) of + Scope when is_binary(Scope) -> Request#{<<"scope">> => Scope}; + _ -> Request + end)), + case fetch_json(post, Endpoint, [], {<<"application/json">>, Body}) of + {ok, Status, #{<<"client_id">> := Id} = Answer} when Status =:= 200; Status =:= 201 -> + Secret = case maps:get(<<"client_secret">>, Answer, null) of S when is_binary(S) -> S; _ -> null end, + Method = case maps:get(<<"token_endpoint_auth_method">>, Answer, null) of + M when is_binary(M) -> M; + _ when Secret =:= null -> <<"none">>; + _ -> <<"client_secret_basic">> + end, + Registration = #{<<"issuer">> => Issuer, <<"redirectUri">> => Redirect, <<"clientId">> => Id, + <<"clientSecret">> => Secret, <<"authMethod">> => Method}, + update(Home, Name, Url, fun(Current) -> Current#{<<"registration">> => Registration} end), + {Id, Secret, Method}; + {ok, Status, Answer} -> fail(described(<<"client registration">>, Status, Answer)); + {error, Reason} -> fail(Reason) + end + end. + +%% Trades the authorization code for tokens and returns the credential the +%% sign-in stores. An `iss` in the response must be the issuer albedo asked +%% (RFC 9207 section 2.4), and one the server promised must be there. +exchange(#{metadata := Metadata, issuer := Issuer, resource := Resource, scope := Scope} = Plan, {grant, Redirect, _, Verifier, _}, Code, Iss) -> + try + Promised = maps:get(<<"authorization_response_iss_parameter_supported">>, Metadata, false) =:= true, + case {Iss, Promised} of + {{some, Issuer}, _} -> ok; + {{some, _}, _} -> fail(<<"the authorization response came from another issuer">>); + {none, true} -> fail(<<"the authorization response did not name its issuer">>); + {none, false} -> ok + end, + {Id, Secret, Method} = registered(Plan, Redirect), + Client = #{<<"tokenEndpoint">> => maps:get(<<"token_endpoint">>, Metadata), + <<"clientId">> => Id, <<"clientSecret">> => Secret, <<"authMethod">> => Method}, + Form = [{<<"grant_type">>, <<"authorization_code">>}, {<<"code">>, Code}, + {<<"redirect_uri">>, Redirect}, {<<"code_verifier">>, Verifier}, + {<<"resource">>, Resource}], + case token_request(Client, Form) of + {ok, Tokens} -> + Base = Client#{<<"issuer">> => Issuer, <<"resource">> => maps:get(url, Plan), + <<"resourceParameter">> => Resource, <<"resourceMetadata">> => maps:get(metadata_url, Plan)}, + {ok, with_tokens(Base, Tokens, Scope)}; + {refused, Reason} -> fail(Reason); + {error, Reason} -> fail(Reason) + end + catch + throw:{mcp_oauth, Failure} -> {error, Failure}; + _:_ -> {error, <<"could not finish the sign-in">>} + end. + +%% A credential with the token response folded in: the access token, a new +%% refresh token or the old one, when it expires, the granted scope, and the +%% account a token names, for "signed in as". +with_tokens(Record, Tokens, Requested) -> + Expires = case maps:get(<<"expires_in">>, Tokens, null) of + Seconds when is_integer(Seconds), Seconds > 0 -> now_ms() + Seconds * 1000; + _ -> null + end, + Refresh = case maps:get(<<"refresh_token">>, Tokens, null) of + R when is_binary(R) -> R; + _ -> maps:get(<<"refresh">>, Record, null) + end, + Granted = case maps:get(<<"scope">>, Tokens, null) of S when is_binary(S) -> S; _ -> Requested end, + Label = account_label(Tokens, maps:get(<<"label">>, Record, null), maps:get(<<"issuer">>, Record, <<>>)), + maps:without([<<"reason">>, <<"stepUp">>], Record#{ + <<"state">> => <<"signed_in">>, <<"access">> => maps:get(<<"access_token">>, Tokens), + <<"refresh">> => Refresh, <<"expires">> => Expires, <<"scope">> => Granted, <<"label">> => Label}). + +account_label(Tokens, Previous, Issuer) -> + Claims = [C || Key <- [<<"id_token">>, <<"access_token">>], Token <- [maps:get(Key, Tokens, null)], + C <- [jwt_claims(Token)], is_map(C)], + Named = [V || C <- Claims, Key <- [<<"email">>, <<"preferred_username">>, <<"name">>, <<"sub">>], + V <- [maps:get(Key, C, null)], is_binary(V), V =/= <<>>], + case {Named, Previous} of + {[Name | _], _} -> bounded(Name, 256); + {[], P} when is_binary(P) -> P; + _ -> case uri_string:parse(Issuer) of #{host := Host} -> Host; _ -> Issuer end + end. + +jwt_claims(Token) when is_binary(Token) -> + case binary:split(Token, <<".">>, [global]) of + [_, Payload, _] -> + try json:decode(base64:decode(Payload, #{mode => urlsafe, padding => false})) catch _:_ -> none end; + _ -> none + end; +jwt_claims(_) -> none. + +%% The account a stored credential names: one per server, so a new sign-in +%% replaces the last. +account(Name, Credential) -> + Label = case maps:get(<<"label">>, Credential, null) of L when is_binary(L) -> L; _ -> Name end, + {account, <<"mcp:", Name/binary>>, Label, <<"MCP server ", Name/binary>>, false}. + +%% Creds with this server's signed-in credential in place, keeping the +%% registration an earlier sign-in made; albedo_oauth calls it under the lock. +signed_in(Creds, Name, Credential) -> + Servers = albedo_settings_store:object(<<"mcp">>, Creds), + Secrets = maps:get(Name, Servers, #{}), + Previous = case maps:get(<<"oauth">>, Secrets, #{}) of P when is_map(P) -> P; _ -> #{} end, + Kept = maps:with([<<"registration">>, <<"challengeScope">>], Previous), + Creds#{<<"mcp">> => Servers#{Name => Secrets#{<<"oauth">> => maps:merge(Kept, Credential)}}}. + +%% ---- token endpoint ----------------------------------------------------- + +%% {ok, Tokens}, {refused, Reason} when the authorization server answered +%% with an OAuth error, or {error, Reason} when it could not be asked. +token_request(#{<<"tokenEndpoint">> := Endpoint, <<"clientId">> := Id} = Client, Form0) -> + Secret = maps:get(<<"clientSecret">>, Client, null), + {Form, Headers} = case {maps:get(<<"authMethod">>, Client, <<"none">>), Secret} of + {<<"client_secret_basic">>, S} when is_binary(S) -> + Basic = base64:encode(<<(form_encode(Id))/binary, ":", (form_encode(S))/binary>>), + {Form0, [{<<"authorization">>, <<"Basic ", Basic/binary>>}]}; + {<<"client_secret_post">>, S} when is_binary(S) -> + {Form0 ++ [{<<"client_id">>, Id}, {<<"client_secret">>, S}], []}; + _ -> {Form0 ++ [{<<"client_id">>, Id}], []} + end, + Body = uri_string:compose_query(Form), + case fetch_json(post, Endpoint, Headers, {<<"application/x-www-form-urlencoded">>, Body}) of + {ok, 200, #{<<"access_token">> := Access} = Tokens} when is_binary(Access) -> + case string:lowercase(maps:get(<<"token_type">>, Tokens, <<"bearer">>)) of + <<"bearer">> -> {ok, Tokens}; + _ -> {refused, <<"the authorization server issued a token albedo cannot send">>} + end; + {ok, Status, Answer} when Status >= 400, Status < 500 -> {refused, described(<<"the token request">>, Status, Answer)}; + {ok, Status, Answer} -> {error, described(<<"the token request">>, Status, Answer)}; + {error, Reason} -> {error, Reason} + end. + +%% A client id or secret as application/x-www-form-urlencoded, which HTTP +%% Basic carries for OAuth (RFC 6749 section 2.3.1). +form_encode(Value) -> iolist_to_binary(uri_string:compose_query([{Value, true}])). + + +described(What, _, #{<<"error">> := Error} = Answer) when is_binary(Error) -> + Detail = case maps:get(<<"error_description">>, Answer, null) of D when is_binary(D) -> <<": ", (bounded(D, 512))/binary>>; _ -> <<>> end, + <>; +described(What, Status, _) -> + <>. + +fetch_json(Method, Url, Headers, Body) -> + case albedo_http:request(Method, Url, [{<<"accept">>, <<"application/json">>} | Headers], Body, ?FETCH_MS, ?FETCH_MS) of + {ok, {Status, _, Response}} when byte_size(Response) =< ?MAX_BODY -> + Decoded = try json:decode(Response) catch _:_ -> none end, + {ok, Status, Decoded}; + {ok, _} -> {error, <<"the answer was too large">>}; + _ -> + Host = case uri_string:parse(Url) of #{host := H} -> H; _ -> Url end, + {error, <<"could not reach ", Host/binary>>} + end. + +%% ---- creds.json --------------------------------------------------------- + +%% This server's sign-in record when it belongs to `Url`, else none. +record(Home, Name, Url) -> + case albedo_credentials:mcp(Home) of + {ok, #{Name := #{<<"oauth">> := #{<<"resource">> := Url} = Record}}} -> Record; + _ -> none + end. + +%% Replaces this server's record with `Change(Current)` under the settings +%% lock; a record for another URL is started afresh. +update(Home, Name, Url, Change) -> + albedo_settings_store:with_lock(Home, fun() -> + albedo_settings_store:guarded(fun() -> + Creds = albedo_settings_store:read(Home, <<"creds.json">>), + Servers = albedo_settings_store:object(<<"mcp">>, Creds), + Secrets = maps:get(Name, Servers, #{}), + Current = case maps:get(<<"oauth">>, Secrets, null) of + #{<<"resource">> := Url} = R -> R; + _ -> #{<<"resource">> => Url, <<"state">> => <<"needs_sign_in">>} + end, + Next = Change(Current), + case Next =:= Current of + true -> ok; + false -> albedo_settings_store:commit_group(Home, + #{<<"creds.json">> => Creds#{<<"mcp">> => Servers#{Name => Secrets#{<<"oauth">> => Next}}}}) + end, + {ok, nil} + end) + end). + +fail(Reason) -> throw({mcp_oauth, Reason}). + +bounded(Text, Max) -> unicode:characters_to_binary(lists:sublist(unicode:characters_to_list(Text), Max)). + +now_ms() -> erlang:system_time(millisecond). diff --git a/src/albedo/harness/extensions/mcp/client.gleam b/src/albedo/harness/extensions/mcp/client.gleam index 1023e4f60..89d97aa49 100644 --- a/src/albedo/harness/extensions/mcp/client.gleam +++ b/src/albedo/harness/extensions/mcp/client.gleam @@ -55,8 +55,29 @@ const max_listen_wait_ms = 60_000 pub type Transport { /// A server run as `executable arguments` with exactly `environment`. Stdio(executable: String, arguments: List(String), environment: Environment) - /// A streamable HTTP endpoint and the headers every request carries. - Http(url: String, headers: List(#(String, String))) + /// A streamable HTTP endpoint, the headers every request carries, and + /// its OAuth sign-in when it may have one. + Http(url: String, headers: List(#(String, String)), auth: Option(Auth)) +} + +/// An HTTP server's OAuth sign-in (MCP basic/authorization). `token(None)` +/// is the bearer token for the next request, None when the server has no +/// sign-in; `token(Some(refused))` replaces a token the server refused with +/// 401, refreshing it once. Error means the server needs the user to sign +/// in, and why. `challenged(status, www_authenticate)` records a 401 or 403 +/// the token could not get past and returns that reason. +pub type Auth { + Auth( + token: fn(Option(String)) -> Result(Option(String), String), + challenged: fn(Int, String) -> String, + ) +} + +/// Why a client did not start. +pub type StartError { + Unreachable(reason: String) + /// The server wants an OAuth sign-in albedo does not have. + NeedsSignIn(reason: String) } /// An Erlang port environment: names to values, or to `false` to unset. @@ -72,6 +93,9 @@ pub type Failure { Lost(reason: String) /// The answer did not have the shape the method promises. Invalid(reason: String) + /// The server refused the request for want of a sign-in, or of a wider + /// one, before running it. + Unauthorized(reason: String) } pub opaque type Client { @@ -111,6 +135,8 @@ type Message { Received(messages: List(Incoming)) /// A worker finished its POST; `id` is the request it carried, if any. Posted(id: Option(Int), outcome: http.Outcome) + /// A worker's POST was refused for want of a sign-in. + Denied(id: Option(Int), reason: String) /// The server's own stream ended. Listened(end: http.StreamEnd) Relisten @@ -131,6 +157,7 @@ type Link { Web( url: String, headers: List(#(String, String)), + auth: Option(Auth), session: Option(String), workers: Dict(Int, Pid), ) @@ -139,7 +166,7 @@ type Link { /// Where opening the connection is. type Opening { Opening( - started: Subject(Result(#(Subject(Message), Dynamic), String)), + started: Subject(Result(#(Subject(Message), Dynamic), StartError)), /// The `server/discover` probe, while it waits. probe: Option(Int), handshake: Handshake, @@ -185,7 +212,10 @@ type State { /// Connects and opens the connection within `startup_ms`. The client process /// is not linked to the caller; `close` ends it. -pub fn start(transport: Transport, startup_ms: Int) -> Result(Client, String) { +pub fn start( + transport: Transport, + startup_ms: Int, +) -> Result(Client, StartError) { let started = process.new_subject() let pid = process.spawn_unlinked(fn() { run(transport, startup_ms, started) }) let monitor = process.monitor(pid) @@ -193,7 +223,7 @@ pub fn start(transport: Transport, startup_ms: Int) -> Result(Client, String) { process.new_selector() |> process.select(started) |> process.select_specific_monitor(monitor, fn(_) { - Error("the MCP client exited") + Error(Unreachable("the MCP client exited")) }) |> process.selector_receive(clock.delay_ms(startup_ms) + 250) case outcome { @@ -207,7 +237,7 @@ pub fn start(transport: Transport, startup_ms: Int) -> Result(Client, String) { } Error(Nil) -> { stop(pid, monitor, started) - Error("the MCP server did not initialize in time") + Error(Unreachable("the MCP server did not initialize in time")) } } } @@ -217,7 +247,7 @@ pub fn start(transport: Transport, startup_ms: Int) -> Result(Client, String) { fn stop( pid: Pid, monitor: process.Monitor, - started: Subject(Result(#(Subject(Message), Dynamic), String)), + started: Subject(Result(#(Subject(Message), Dynamic), StartError)), ) -> Nil { process.kill(pid) let _ = @@ -332,17 +362,17 @@ pub fn close(client: Client) -> Nil { fn run( transport: Transport, startup_ms: Int, - started: Subject(Result(#(Subject(Message), Dynamic), String)), + started: Subject(Result(#(Subject(Message), Dynamic), StartError)), ) -> Nil { let subject = process.new_subject() let link = case transport { Stdio(executable, arguments, environment) -> open(executable, arguments, environment) |> result.map(fn(port) { Pipe(port, bytes_tree.new(), 0) }) - Http(url, headers) -> Ok(Web(url, headers, None, dict.new())) + Http(url, headers, auth) -> Ok(Web(url, headers, auth, None, dict.new())) } case link { - Error(reason) -> process.send(started, Error(reason)) + Error(reason) -> process.send(started, Error(Unreachable(reason))) Ok(link) -> { let state = State( @@ -361,7 +391,10 @@ fn run( case probe(state) { Ok(state) -> loop(state) Error(_) -> - process.send(started, Error("the MCP server could not be reached")) + process.send( + started, + Error(Unreachable("the MCP server could not be reached")), + ) } } } @@ -404,9 +437,39 @@ fn loop(state: State) -> Nil { }) Web(..) -> selector } - case handle(state, process.selector_receive_forever(selector)) { - Ok(state) -> loop(state) - Error(reason) -> shut(state, reason) + case process.selector_receive_forever(selector) { + Denied(id, reason) -> + case denied(state, id, reason) { + Ok(state) -> loop(state) + Error(Nil) -> shut(state, NeedsSignIn(reason)) + } + message -> + case handle(state, message) { + Ok(state) -> loop(state) + Error(reason) -> shut(state, Unreachable(reason)) + } + } +} + +/// A request refused for want of a sign-in fails as unauthorized; while the +/// connection is opening, the connection cannot open (Error). +fn denied(state: State, id: Option(Int), reason: String) -> Result(State, Nil) { + let state = case id, state.link { + Some(id), Web(workers:, ..) as web -> + State(..state, link: Web(..web, workers: dict.delete(workers, id))) + _, _ -> state + } + case state.opening, id { + Some(_), _ -> Error(Nil) + None, Some(id) -> + case dict.get(state.pending, id) { + Ok(Pending(Caller(reply), _)) -> { + process.send(reply, Error(Unauthorized(reason))) + Ok(forget(state, id)) + } + _ -> Ok(state) + } + None, None -> Ok(state) } } @@ -441,6 +504,8 @@ fn handle(state: State, message: Message) -> Result(State, String) { } Received(messages) -> list.try_fold(messages, state, receive) Posted(id, outcome) -> posted(state, id, outcome) + // `loop` answers these itself, since one can end the connection. + Denied(..) -> Ok(state) Listened(end) -> listened(state, end) Relisten -> case state.listener { @@ -562,7 +627,7 @@ fn send( Ok(Nil) -> Ok(state) Error(Nil) -> Error("the MCP server stopped reading") } - Web(url, base, session, workers) as web -> { + Web(url, base, auth, session, workers) as web -> { let owner = state.subject let headers = post_headers(base, session, state.era, headers) let resumable = case state.era { @@ -573,18 +638,23 @@ fn send( let sink = sink(owner) let worker = process.spawn(fn() { - let outcome = - http.post( - url, - headers, - frame, - id, - in_session, - resumable, - timeout, - sink, - ) - process.send(owner, Posted(id, outcome)) + let posted = + authorized(auth, headers, fn(headers) { + http.post( + url, + headers, + frame, + id, + in_session, + resumable, + timeout, + sink, + ) + }) + process.send(owner, case posted { + Ok(outcome) -> Posted(id, outcome) + Error(reason) -> Denied(id, reason) + }) }) case id { Some(id) -> @@ -600,6 +670,58 @@ fn send( } } +/// Runs `post` with the sign-in's bearer token. A 401 refreshes the token +/// once and posts again (2026-07-28 basic/authorization, "Token +/// Handling"); a challenge that remains, or a 403 for a wider scope, is the +/// sign-in's to record (Error). The server refused before running anything, +/// so posting again is safe. Without a sign-in a challenge is a refusal. +fn authorized( + auth: Option(Auth), + headers: List(#(String, String)), + post: fn(List(#(String, String))) -> http.Outcome, +) -> Result(http.Outcome, String) { + case auth { + None -> + case post(headers) { + http.Challenged(status, _) -> Ok(http.Refused(status)) + outcome -> Ok(outcome) + } + Some(auth) -> { + use token <- result.try(auth.token(None)) + case post(bearer(headers, token)), token { + http.Challenged(401, _), Some(refused) -> { + use fresh <- result.try(auth.token(Some(refused))) + case post(bearer(headers, fresh)) { + http.Challenged(status, challenge) -> + Error(auth.challenged(status, challenge)) + outcome -> Ok(outcome) + } + } + http.Challenged(status, challenge), _ -> + Error(auth.challenged(status, challenge)) + outcome, _ -> Ok(outcome) + } + } + } +} + +fn bearer( + headers: List(#(String, String)), + token: Option(String), +) -> List(#(String, String)) { + case token { + Some(token) -> [#("authorization", "Bearer " <> token), ..headers] + None -> headers + } +} + +/// The bearer token a request without a refusal to answer may carry. +fn current_token(auth: Option(Auth)) -> Option(String) { + option.then(auth, fn(auth) { + auth.token(None) |> option.from_result |> option.flatten + }) +} + fn sink(owner: Subject(Message)) -> http.Sink { http.Sink( received: fn(messages) { process.send(owner, Received(messages)) }, @@ -1037,7 +1159,7 @@ fn subscription( /// stream of a 2025-11-25 session (basic/transports, "Listening for Messages /// from the Server") or a modern server's `subscriptions/listen`. fn listen(state: State, failures: Int) -> State { - let assert Web(url, base, session, _) = state.link + let assert Web(url, base, auth, session, _) = state.link let #(how, headers, state) = case state.era { Some(Modern(_)) -> { let id = state.next_id @@ -1053,6 +1175,7 @@ fn listen(state: State, failures: Int) -> State { let sink = sink(owner) let worker = process.spawn(fn() { + let headers = bearer(headers, current_token(auth)) process.send( owner, Listened(http.listen(url, headers, how, in_session, sink)), @@ -1123,7 +1246,7 @@ fn posted( |> handshake http.Finished, Some(id) -> fail(state, id, "the MCP server answered without a response") - http.Refused(status), Some(id) -> + http.Refused(status), Some(id) | http.Challenged(status, _), Some(id) -> fail(state, id, "the MCP server answered HTTP " <> int.to_string(status)) http.Failed(reason), Some(id) -> fail(state, id, reason) } @@ -1159,15 +1282,15 @@ fn fail(state: State, id: Int, reason: String) -> Result(State, String) { } /// Answers every waiting request and closes the transport. -fn shut(state: State, reason: String) -> Nil { +fn shut(state: State, failure: StartError) -> Nil { dict.each(state.pending, fn(_, pending) { case pending.waiter { - Caller(reply) -> process.send(reply, Error(Lost(reason))) + Caller(reply) -> process.send(reply, Error(Lost(failure.reason))) Opener -> Nil } }) case state.opening { - Some(opening) -> process.send(opening.started, Error(reason)) + Some(opening) -> process.send(opening.started, Error(failure)) None -> Nil } case state.listener { @@ -1179,12 +1302,13 @@ fn shut(state: State, reason: String) -> Nil { } case state.link, state.era { Pipe(port, ..), _ -> close_port(port) - Web(url, headers, Some(session), _), era -> { + Web(url, headers, auth, Some(session), _), era -> { let _ = http_request( atom.create("delete"), url, - post_headers(headers, Some(session), era, []), + post_headers(headers, Some(session), era, []) + |> bearer(current_token(auth)), atom.create("none"), delete_ms, delete_ms, diff --git a/src/albedo/harness/extensions/mcp/extension.gleam b/src/albedo/harness/extensions/mcp/extension.gleam index 50e1fd9e3..18febcc90 100644 --- a/src/albedo/harness/extensions/mcp/extension.gleam +++ b/src/albedo/harness/extensions/mcp/extension.gleam @@ -2,6 +2,7 @@ import albedo/daemon/store import albedo/harness/extension +import albedo/harness/extensions/mcp/sign_in import albedo/harness/rpc import albedo/harness/settings import albedo/openai_api/types @@ -161,6 +162,7 @@ pub fn configured_extension() -> extension.Extension { ["python"], [ extension.SettingsPlugin(settings.declaration(config_section())), + extension.LoginResolverPlugin(sign_in.resolve), extension.ManagedPlugin(fn(ledger, session, workspace) { use config <- result.try(settings.load_section(config_section())) prepare(config, ledger, session, workspace) @@ -269,11 +271,18 @@ fn prepare( fn(_) { None }, ) }), - warnings: list.map(native_offline(handle), fn(name) { - "MCP server '" - <> name - <> "' is unavailable; its tools join the session once it connects" - }), + warnings: list.append( + list.map(native_offline(handle), fn(name) { + "MCP server '" + <> name + <> "' is unavailable; its tools join the session once it connects" + }), + list.map(native_sign_in(handle), fn(name) { + "MCP server '" + <> name + <> "' needs you to sign in; sign in from /mcp and its tools join the session" + }), + ), observe: fn(session: extension.Session, event) { case event { extension.Stirred -> @@ -463,6 +472,9 @@ fn native_context(handle: Handle) -> String @external(erlang, "albedo_mcp", "offline") fn native_offline(handle: Handle) -> List(String) +@external(erlang, "albedo_mcp", "sign_in") +fn native_sign_in(handle: Handle) -> List(String) + @external(erlang, "albedo_mcp", "observe") fn native_observe( handle: Handle, diff --git a/src/albedo/harness/extensions/mcp/http.gleam b/src/albedo/harness/extensions/mcp/http.gleam index 15adf3f5d..e888e2f1a 100644 --- a/src/albedo/harness/extensions/mcp/http.gleam +++ b/src/albedo/harness/extensions/mcp/http.gleam @@ -51,6 +51,9 @@ pub type Outcome { Refused(status: Int) /// The server no longer knows the session (404 to a request carrying it). SessionGone + /// The server wants authorization: a 401, or a 403 whose + /// `WWW-Authenticate` says `insufficient_scope`, with that header's value. + Challenged(status: Int, challenge: String) Failed(reason: String) } @@ -174,15 +177,18 @@ fn resumed( id: Option(Int), progress: Progress, ) -> Read { - use status, _, final <- headers(exchange, connection) + use status, _, final, challenge <- headers(exchange, connection) case status, final { 404, _ if exchange.in_session -> Stopped(SessionGone) _, _ if status < 200 || status >= 300 -> - Stopped(Failed( - "the MCP server would not resume the stream (HTTP " - <> int.to_string(status) - <> ")", - )) + challenged(exchange, connection, status, final, challenge) + |> option.lazy_unwrap(fn() { + Stopped(Failed( + "the MCP server would not resume the stream (HTTP " + <> int.to_string(status) + <> ")", + )) + }) // The server took the resumption but sent nothing: try again. _, True -> Ended(Progress(..progress, events: 0)) _, False -> @@ -239,11 +245,11 @@ fn listened( last_event: String, ) -> StreamEnd { let read = { - use status, content, final <- headers(exchange, connection) + use status, content, final, challenge <- headers(exchange, connection) case status, final, is_stream(content) { 404, _, _ if exchange.in_session -> Stopped(SessionGone) _, _, _ if status < 200 || status >= 300 -> - refused(exchange, connection, status, final) + refused(exchange, connection, status, final, challenge) _, True, _ -> Ended(Progress(last_event, None, 0)) _, False, True -> events(exchange, connection, id, sse.new(max_message_bytes), 0) @@ -262,6 +268,7 @@ fn listened( Answered -> Closed Stopped(SessionGone) -> StreamSessionGone Stopped(Refused(_)) -> Unsupported + // Tried again later, with whatever token the connection has by then. Stopped(_) -> Dropped(last_event, None, False) Ended(progress) -> Dropped( @@ -280,11 +287,11 @@ fn respond( connection: transport.Connection, id: Option(Int), ) -> Read { - use status, content, final <- headers(exchange, connection) + use status, content, final, challenge <- headers(exchange, connection) case status { 404 if exchange.in_session -> Stopped(SessionGone) _ if status < 200 || status >= 300 -> - refused(exchange, connection, status, final) + refused(exchange, connection, status, final, challenge) _ if final -> Answered _ -> case is_stream(content) { @@ -298,11 +305,12 @@ fn respond( } /// Reads the response head, reporting a session id it carries, and hands -/// the status, content type, and whether a body follows to `next`. +/// the status, content type, whether a body follows, and the +/// `WWW-Authenticate` value ("" when none) to `next`. fn headers( exchange: Exchange, connection: transport.Connection, - next: fn(Int, String, Bool) -> Read, + next: fn(Int, String, Bool, String) -> Read, ) -> Read { case receive(exchange, connection) { Error(reason) -> Stopped(Failed(reason)) @@ -314,7 +322,9 @@ fn headers( Error(Nil) -> Nil } let content = list.key_find(headers, "content-type") |> result.unwrap("") - next(status, string.lowercase(content), final) + let challenge = + list.key_find(headers, "www-authenticate") |> result.unwrap("") + next(status, string.lowercase(content), final, challenge) } } } @@ -324,13 +334,22 @@ fn is_stream(content: String) -> Bool { } /// Passes on a JSON-RPC error in a refusal's body, so a 2026-07-28 server's -/// error reaches its request; any other body is dropped. +/// error reaches its request; any other body is dropped. An authorization +/// challenge is not an answer, so its body is drained unread. fn refused( exchange: Exchange, connection: transport.Connection, status: Int, final: Bool, + challenge: String, ) -> Read { + use <- option.lazy_unwrap(challenged( + exchange, + connection, + status, + final, + challenge, + )) case final { True -> Nil False -> { @@ -341,6 +360,35 @@ fn refused( Stopped(Refused(status)) } +/// A 401, or a 403 for `insufficient_scope` (RFC 6750 section 3.1), as the +/// challenge it carries; None for any other refusal. +fn challenged( + exchange: Exchange, + connection: transport.Connection, + status: Int, + final: Bool, + challenge: String, +) -> Option(Read) { + let scope = string.contains(string.lowercase(challenge), "insufficient_scope") + case status == 401 || { status == 403 && scope } { + False -> None + True -> { + case final { + True -> Nil + False -> drain(exchange, connection) + } + Some(Stopped(Challenged(status, challenge))) + } + } +} + +fn drain(exchange: Exchange, connection: transport.Connection) -> Nil { + case receive(exchange, connection) { + Ok(transport.Data(_, False)) -> drain(exchange, connection) + _ -> Nil + } +} + fn result_read(outcome: Result(Nil, String), next: fn(Nil) -> Read) -> Read { case outcome { Ok(Nil) -> next(Nil) diff --git a/src/albedo/harness/extensions/mcp/sign_in.gleam b/src/albedo/harness/extensions/mcp/sign_in.gleam new file mode 100644 index 000000000..b01ab772d --- /dev/null +++ b/src/albedo/harness/extensions/mcp/sign_in.gleam @@ -0,0 +1,64 @@ +//// Sign-ins for HTTP MCP servers that ask for OAuth. The daemon's sign-in +//// flow (`oauth`) runs the browser half; `albedo_mcp_oauth` discovers the +//// server's authorization server, registers albedo with it, and trades the +//// code for tokens it keeps in creds.json. + +import albedo/harness/oauth +import gleam/dict.{type Dict} +import gleam/dynamic.{type Dynamic} +import gleam/option.{type Option, None, Some} +import gleam/result + +/// The loopback port sign-ins listen on first, so a registration made for +/// its redirect keeps working; a busy port moves to an ephemeral one, which +/// registers again. A client id configured by hand should be registered for +/// `http://127.0.0.1:33418/callback`. +const callback_port = 33_418 + +/// What discovery found for one server: opaque to Gleam. +type Plan + +/// The sign-in for `provider` when it names an MCP server as `mcp:`. +pub fn resolve( + home: String, + provider: String, +) -> Option(Result(oauth.Login, String)) { + case provider { + "mcp:" <> name -> Some(login(home, name)) + _ -> None + } +} + +fn login(home: String, name: String) -> Result(oauth.Login, String) { + use plan <- result.map(native_discover(home, name)) + oauth.Login( + "mcp:" <> name, + "sign in to " <> name, + "oauth · mcp server", + oauth.Service, + "mcp:" <> name, + oauth.Callback("127.0.0.1", callback_port, "/callback", False), + fn(grant) { native_authorize(plan, grant) }, + fn(grant, code, _progress) { + native_exchange(plan, grant, code, oauth.callback_issuer()) + }, + fn(credential) { native_account(name, credential) }, + ) +} + +@external(erlang, "albedo_mcp_oauth", "discover") +fn native_discover(home: String, name: String) -> Result(Plan, String) + +@external(erlang, "albedo_mcp_oauth", "authorize") +fn native_authorize(plan: Plan, grant: oauth.Grant) -> Result(String, String) + +@external(erlang, "albedo_mcp_oauth", "exchange") +fn native_exchange( + plan: Plan, + grant: oauth.Grant, + code: String, + issuer: Option(String), +) -> Result(Dict(String, Dynamic), String) + +@external(erlang, "albedo_mcp_oauth", "account") +fn native_account(name: String, credential: Dynamic) -> oauth.Account diff --git a/src/albedo/harness/extensions/mistral/extension.gleam b/src/albedo/harness/extensions/mistral/extension.gleam index e4bf4c286..18f1cf0ea 100644 --- a/src/albedo/harness/extensions/mistral/extension.gleam +++ b/src/albedo/harness/extensions/mistral/extension.gleam @@ -53,7 +53,7 @@ pub fn login() -> oauth.Login { oauth.Model, provider_name, oauth.Device(native_device_start), - fn(_) { "" }, + fn(_) { Ok("") }, fn(_, _, _) { Error("Mistral uses browser sign-in") }, native_account, ) diff --git a/src/albedo/harness/extensions/opencode_go/extension.gleam b/src/albedo/harness/extensions/opencode_go/extension.gleam index 61436b32a..cdad839d4 100644 --- a/src/albedo/harness/extensions/opencode_go/extension.gleam +++ b/src/albedo/harness/extensions/opencode_go/extension.gleam @@ -44,7 +44,7 @@ pub fn login() -> oauth.Login { oauth.Model, provider_name, oauth.Device(native_device_start), - fn(_) { "" }, + fn(_) { Ok("") }, fn(_, _, _) { Error("OpenCode Go uses device authorization") }, native_account, ) diff --git a/src/albedo/harness/oauth.gleam b/src/albedo/harness/oauth.gleam index 820d775dd..a051f499f 100644 --- a/src/albedo/harness/oauth.gleam +++ b/src/albedo/harness/oauth.gleam @@ -23,7 +23,8 @@ pub type Login { /// The creds.json accounts key holding one account object or an array of them. store: String, callback: Callback, - authorize: fn(Grant) -> String, + /// The authorize url for a grant, or why this sign-in cannot start. + authorize: fn(Grant) -> Result(String, String), /// Trades the code for the credential object to store. `progress` /// reports slow follow-up steps such as account provisioning. exchange: fn(Grant, String, fn(String) -> Nil) -> @@ -136,6 +137,11 @@ pub fn remove_account( @external(erlang, "albedo_oauth", "accounts") pub fn accounts(home: String, login: Login) -> List(Account) +/// The `iss` the authorization response carried (RFC 9207), for an +/// `exchange` that checks it. +@external(erlang, "albedo_oauth", "callback_issuer") +pub fn callback_issuer() -> Option(String) + pub fn authorize_url(base: String, query: List(#(String, String))) -> String { base <> "?" <> uri.query_to_string(query) } diff --git a/src/albedo/harness/settings/projection.gleam b/src/albedo/harness/settings/projection.gleam index 194b418a4..a36aa31ca 100644 --- a/src/albedo/harness/settings/projection.gleam +++ b/src/albedo/harness/settings/projection.gleam @@ -360,6 +360,7 @@ fn mcp_view(raw: Dynamic, secret: Dynamic) -> Result(Dynamic, Error) { list.append(dict.to_list(public), [ #("environment", environment), #("headers", headers), + #("auth", auth_view(secret_fields)), #( "secret_presence", object([ @@ -376,6 +377,68 @@ fn mcp_view(raw: Dynamic, secret: Dynamic) -> Result(Dynamic, Error) { ) } +/// A server's OAuth sign-in as clients show it: `none` until the server asks +/// for one, then `needs_sign_in`, `signed_in` or `signed_out`. A signed-in +/// server that asked for a wider scope also names it in `step_up`. Tokens +/// and client secrets never appear. +fn auth_view(secret: Dict(String, Dynamic)) -> Dynamic { + let text = fn(record, key) { + decode.run(record, decode.at([key], decode.string)) + |> result.map(dynamic.string) + |> result.unwrap(null()) + } + let registered = + dict.get(secret, "oauth") + |> result.try(fn(record) { + decode.run(record, decode.at(["registration", "clientId"], decode.string)) + |> result.replace_error(Nil) + }) + let client = case dict.has_key(secret, "oauthClient"), registered { + True, _ -> dynamic.string("configured") + False, Ok(_) -> dynamic.string("registered") + False, Error(_) -> null() + } + case dict.get(secret, "oauth") { + Error(_) -> + object([ + #("state", dynamic.string("none")), + #("account", null()), + #("expires_at", null()), + #("scope", null()), + #("step_up", null()), + #("reason", null()), + #("client", client), + ]) + Ok(record) -> { + let state = + decode.run(record, decode.at(["state"], decode.string)) + |> result.unwrap("needs_sign_in") + let expires = case + state, + decode.run(record, decode.at(["expires"], decode.int)) + { + "signed_in", Ok(ms) -> dynamic.string(native_timestamp(ms)) + _, _ -> null() + } + object([ + #("state", dynamic.string(state)), + #("account", case state { + "signed_in" -> text(record, "label") + _ -> null() + }), + #("expires_at", expires), + #("scope", text(record, "scope")), + #("step_up", text(record, "stepUp")), + #("reason", text(record, "reason")), + #("client", client), + ]) + } + } +} + +@external(erlang, "albedo_http_api", "timestamp") +fn native_timestamp(ms: Int) -> String + fn source_view( definition: Dict(String, Dynamic), key: String, diff --git a/test/e2e/fake_mcp_http_server.py b/test/e2e/fake_mcp_http_server.py index 05fef2774..c4ad0db35 100644 --- a/test/e2e/fake_mcp_http_server.py +++ b/test/e2e/fake_mcp_http_server.py @@ -9,6 +9,10 @@ finishes it on the GET that resumes with Last-Event-ID. ``get=False`` answers GET with 405. ``modern=True`` is a 2026-07-28 server instead: no session, no initialize, server/discover, the request headers and ``_meta`` checked on every request, and change notifications on a ``subscriptions/listen`` stream. +``oauth=AuthServer`` makes it a protected resource (RFC 9728): it publishes +its metadata at the well-known path, answers a request without a live token +from that server with 401 and a ``WWW-Authenticate`` challenge, and a call to +the ``admin`` tool without the ``admin`` scope with 403 insufficient_scope. Every request it receives is kept in ``seen`` for the test to inspect. """ @@ -32,8 +36,9 @@ TOOLS = [ class Server(ThreadingHTTPServer): daemon_threads = True - def __init__(self, modern=False, get=True, tools=None): + def __init__(self, modern=False, get=True, tools=None, oauth=None): super().__init__(("127.0.0.1", 0), Handler) + self.oauth = oauth self.modern = modern self.get = get self.tools = TOOLS if tools is None else tools @@ -96,18 +101,70 @@ class Handler(BaseHTTPRequestHandler): "name": self.headers.get("mcp-name"), "param": self.headers.get("mcp-param-message"), "last_event": self.headers.get("last-event-id"), + "authorization": self.headers.get("authorization"), "message": message, } ) + def metadata_url(self): + return f"{self.server.url.rsplit('/mcp', 1)[0]}/.well-known/oauth-protected-resource/mcp" + + def refused(self, message=None): + """Answers 401 or 403 when OAuth is on and the token cannot do + this; False when the request may go on.""" + oauth = self.server.oauth + if oauth is None: + return False + header = self.headers.get("authorization") or "" + scopes = oauth.scopes(header.removeprefix("Bearer ")) if header else None + if scopes is None: + challenge = ( + f'Bearer resource_metadata="{self.metadata_url()}", scope="read"' + ) + self.challenge(401, challenge) + return True + params = (message or {}).get("params") or {} + if params.get("name") == "admin" and "admin" not in scopes: + challenge = ( + 'Bearer error="insufficient_scope", scope="admin", ' + f'resource_metadata="{self.metadata_url()}"' + ) + self.challenge(403, challenge) + return True + return False + + def challenge(self, status, value): + self.send_response(status) + self.send_header("www-authenticate", value) + self.send_header("content-length", "0") + self.end_headers() + def do_DELETE(self): self.record(None) + if self.refused(): + return if self.server.modern: return self.empty(405) self.empty(200 if self.headers.get("mcp-session-id") else 400) def do_GET(self): + oauth = self.server.oauth + if oauth and self.path == "/.well-known/oauth-protected-resource/mcp": + body = json.dumps( + { + "resource": self.server.url, + "authorization_servers": [oauth.issuer], + "scopes_supported": ["read"], + } + ).encode() + self.send_response(200) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(body))) + self.end_headers() + return self.wfile.write(body) self.record(None) + if self.refused(): + return if self.server.modern or not self.server.get: return self.empty(405) if self.headers.get("mcp-session-id") != SESSION: @@ -156,6 +213,8 @@ class Handler(BaseHTTPRequestHandler): length = int(self.headers.get("content-length") or 0) message = json.loads(self.rfile.read(length)) self.record(message) + if self.refused(message): + return if self.server.modern: return self.modern(message) method, id = message.get("method"), message.get("id") diff --git a/test/e2e/fake_oauth_server.py b/test/e2e/fake_oauth_server.py new file mode 100644 index 000000000..b5369b216 --- /dev/null +++ b/test/e2e/fake_oauth_server.py @@ -0,0 +1,207 @@ +"""Authorization server for an MCP server that asks for OAuth, used by +mcp_oauth_test.py with fake_mcp_http_server.Server(oauth=...). + +It publishes RFC 8414 metadata, registers clients (RFC 7591), answers the +authorize request with a 302 to the client's loopback redirect (so a test +follows it instead of a browser), and checks PKCE S256, the redirect and the +resource parameter (RFC 8707) when it trades a code. Access tokens expire +after ``expires_in`` seconds; ``revoke_access`` and ``revoke_refresh`` make +the tokens it issued stop working. Every request is kept in ``seen``. +""" + +import base64 +import hashlib +import json +import secrets +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlencode, urlparse + + +class AuthServer(ThreadingHTTPServer): + daemon_threads = True + + def __init__(self, expires_in=3600): + super().__init__(("127.0.0.1", 0), Handler) + self.expires_in = expires_in + self.clients = {} + self.codes = {} + self.access = {} + self.refresh = {} + self.seen = [] + self.lock = threading.Lock() + + @property + def issuer(self): + return f"http://127.0.0.1:{self.server_address[1]}" + + def start(self): + threading.Thread(target=self.serve_forever, daemon=True).start() + return self + + def stop(self): + self.shutdown() + self.server_close() + + def scopes(self, token): + """The scopes a live access token grants, or None.""" + with self.lock: + grant = self.access.get(token) + if grant is None or grant["expires"] < time.time(): + return None + return set(grant["scope"].split()) + + def revoke_access(self): + with self.lock: + self.access.clear() + + def revoke_refresh(self): + with self.lock: + self.access.clear() + self.refresh.clear() + + def requests(self, path): + return [entry for entry in self.seen if entry["path"] == path] + + def issue(self, client, scope, resource): + access, refresh = secrets.token_hex(8), secrets.token_hex(8) + with self.lock: + self.access[access] = { + "scope": scope, + "expires": time.time() + self.expires_in, + } + self.refresh[refresh] = { + "client": client, + "scope": scope, + "resource": resource, + } + return { + "access_token": access, + "token_type": "Bearer", + "expires_in": self.expires_in, + "refresh_token": refresh, + "scope": scope, + "id_token": jwt({"sub": "u1", "email": "ana@example.com"}), + } + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + server: AuthServer + + def log_message(self, format, *args): + pass + + def do_GET(self): + url = urlparse(self.path) + query = {key: values[0] for key, values in parse_qs(url.query).items()} + self.server.seen.append({"path": url.path, "query": query}) + if url.path == "/.well-known/oauth-authorization-server": + issuer = self.server.issuer + return self.json( + 200, + { + "issuer": issuer, + "authorization_endpoint": f"{issuer}/authorize", + "token_endpoint": f"{issuer}/token", + "registration_endpoint": f"{issuer}/register", + "code_challenge_methods_supported": ["S256"], + "scopes_supported": ["read", "admin", "offline_access"], + "authorization_response_iss_parameter_supported": True, + }, + ) + if url.path == "/authorize": + return self.authorize(query) + self.json(404, {"error": "not_found"}) + + def authorize(self, query): + client = self.server.clients.get(query.get("client_id")) + if ( + client is None + or query.get("redirect_uri") not in client["redirect_uris"] + or query.get("code_challenge_method") != "S256" + or not query.get("code_challenge") + or not query.get("resource") + ): + return self.json(400, {"error": "invalid_request"}) + code = secrets.token_hex(8) + self.server.codes[code] = query + location = ( + query["redirect_uri"] + + "?" + + urlencode( + {"code": code, "state": query["state"], "iss": self.server.issuer} + ) + ) + self.send_response(302) + self.send_header("location", location) + self.send_header("content-length", "0") + self.end_headers() + + def do_POST(self): + url = urlparse(self.path) + body = self.rfile.read(int(self.headers.get("content-length") or 0)) + if url.path == "/register": + request = json.loads(body) + self.server.seen.append({"path": url.path, "body": request}) + client = f"client-{len(self.server.clients) + 1}" + self.server.clients[client] = request + return self.json( + 201, + {"client_id": client, "token_endpoint_auth_method": "none", **request}, + ) + if url.path == "/token": + form = {key: values[0] for key, values in parse_qs(body.decode()).items()} + self.server.seen.append({"path": url.path, "body": form}) + return self.token(form) + self.json(404, {"error": "not_found"}) + + def token(self, form): + if form.get("grant_type") == "authorization_code": + grant = self.server.codes.pop(form.get("code"), None) + verifier = form.get("code_verifier", "") + challenge = ( + base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()) + .rstrip(b"=") + .decode() + ) + if ( + grant is None + or grant["code_challenge"] != challenge + or grant["redirect_uri"] != form.get("redirect_uri") + or grant["client_id"] != form.get("client_id") + or grant["resource"] != form.get("resource") + ): + return self.json(400, {"error": "invalid_grant"}) + scope = grant.get("scope", "") + return self.json( + 200, self.server.issue(grant["client_id"], scope, grant["resource"]) + ) + if form.get("grant_type") == "refresh_token": + with self.server.lock: + grant = self.server.refresh.pop(form.get("refresh_token"), None) + if grant is None or grant["resource"] != form.get("resource"): + return self.json(400, {"error": "invalid_grant"}) + return self.json( + 200, + self.server.issue(grant["client"], grant["scope"], grant["resource"]), + ) + self.json(400, {"error": "unsupported_grant_type"}) + + def json(self, status, value): + body = json.dumps(value).encode() + self.send_response(status) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +def jwt(claims): + def part(value): + return ( + base64.urlsafe_b64encode(json.dumps(value).encode()).rstrip(b"=").decode() + ) + + return f"{part({'alg': 'none'})}.{part(claims)}.sig" diff --git a/test/e2e/mcp_oauth_test.py b/test/e2e/mcp_oauth_test.py new file mode 100644 index 000000000..7526d8974 --- /dev/null +++ b/test/e2e/mcp_oauth_test.py @@ -0,0 +1,233 @@ +"""OAuth for an HTTP MCP server (MCP basic/authorization): a server that +answers 401 is saved and asks for a sign-in; the sign-in discovers the +authorization server, registers albedo, and trades a PKCE code bound to the +server's resource; tokens refresh before they expire and once after a 401; a +refused refresh asks for a new sign-in; and a 403 insufficient_scope signs in +again with the wider scope. The browser is the test: it follows the +authorization server's redirect to the daemon's loopback callback.""" + +import json +import time +import unittest +import urllib.error +import urllib.request +from urllib.parse import parse_qs, urlparse + +from fake_mcp_http_server import SCHEMA, Server +from fake_oauth_server import AuthServer +from harness import Albedo, Provider, Reply, exclusive, operation_id, text + +TOOLS = [ + {"name": name, "description": f"{name} one message", "inputSchema": SCHEMA} + for name in ("echo", "admin") +] + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +# exclusive: configures global MCP servers and credentials +@exclusive +class McpOAuthTests(unittest.TestCase): + def setUp(self): + self.tool = "echo" + self.auth = AuthServer().start() + self.addCleanup(self.auth.stop) + self.server = Server(tools=TOOLS, oauth=self.auth).start() + self.addCleanup(self.server.stop) + + def script(request): + tools = [tool["name"] for tool in request.get("tools", [])] + called = any( + item.get("type") == "function_call_output" + for item in request["input"][-1:] + ) + wanted = next( + (name for name in tools if name.startswith(f"mcp_web_{self.tool}_")), + None, + ) + if wanted and not called: + return Reply( + "python", tool_name=wanted, tool_arguments={"message": "hi"} + ) + return text("done") + + self.provider = Provider(script) + self.addCleanup(self.provider.close) + + def prepare(app): + app.write_extensions({"mcp": {"retryMs": 100}}) + + self.app = Albedo(self.provider, protocol="responses", prepare=prepare) + self.app.__enter__() + self.addCleanup(self.app.__exit__, None, None, None) + self.session = self.app.session() + + def settings(self): + with self.app.api("/settings?group=mcp") as response: + return json.load(response), response.headers["ETag"] + + def auth_state(self): + return self.settings()[0]["definitions"]["web"]["auth"] + + def patch(self, definitions): + _, etag = self.settings() + with self.app.api( + "/settings?group=mcp", + {"definitions": definitions}, + method="PATCH", + headers={"If-Match": etag}, + ) as response: + return json.load(response) + + def set_mcp(self, enabled): + route = f"/sessions/{self.session}?view=configuration" + with self.app.api(route) as response: + json.load(response) + etag = response.headers["ETag"] + self.app.api( + route, + {"selection": {"extensions": {"mcp": enabled}}}, + method="PATCH", + headers={"If-Match": etag}, + ).close() + with self.app.api( + f"/sessions/{self.session}/reload", {"target": "session"} + ) as response: + return json.load(response) + + def reconnect(self): + self.set_mcp(False) + self.set_mcp(True) + + def turn(self, prompt): + before = len(self.provider.requests) + self.app.prompt(self.session, prompt).close() + self.app.idle(self.session, timeout=60) + return [entry["request"] for entry in self.provider.requests[before:]] + + def output(self, requests): + outputs = [ + item["output"] + for item in requests[-1]["input"] + if item.get("type") == "function_call_output" + ] + return outputs[-1] if outputs else None + + def sign_in(self): + """Starts the sign-in, follows the authorization server's redirect to + the daemon's callback as a browser would, and waits for it to end.""" + login = operation_id() + with self.app.api( + f"/auth/logins/{login}", + {"provider": "mcp:web", "flow": "browser", "values": {}}, + method="PUT", + ) as response: + started = json.load(response) + url = started["url"] + opener = urllib.request.build_opener(NoRedirect) + try: + opener.open(url, timeout=10) + self.fail("the authorization server did not redirect") + except urllib.error.HTTPError as redirect: + self.assertEqual(redirect.code, 302) + callback = redirect.headers["location"] + with urllib.request.urlopen(callback, timeout=10) as page: + self.assertIn(b"Authentication completed", page.read()) + deadline = time.monotonic() + 20 + while True: + with self.app.api(f"/auth/logins/{login}") as response: + state = json.load(response) + if state["state"] not in ("waiting", "exchanging"): + break + self.assertLess(time.monotonic(), deadline, state) + time.sleep(0.05) + self.assertEqual(state["state"], "complete", state) + return {key: values[0] for key, values in parse_qs(urlparse(url).query).items()} + + def bearers(self): + return [entry["authorization"] for entry in self.server.seen] + + def test_sign_in_refresh_and_step_up(self): + # A server that answers 401 is saved anyway, needing a sign-in. + self.patch({"web": {"transport": "http", "url": self.server.url}}) + auth = self.auth_state() + self.assertEqual(auth["state"], "needs_sign_in", auth) + self.set_mcp(True) + requests = self.turn("anything there?") + self.assertFalse( + [t for t in requests[0]["tools"] if t["name"].startswith("mcp_web_")] + ) + self.assertIn("needs the user to sign in", json.dumps(requests[0])) + + query = self.sign_in() + self.assertEqual(query["code_challenge_method"], "S256") + self.assertEqual(query["resource"], self.server.url) + self.assertEqual(query["scope"], "read offline_access") + registration = self.auth.requests("/register")[0]["body"] + self.assertEqual(registration["application_type"], "native") + self.assertEqual(registration["redirect_uris"], [query["redirect_uri"]]) + self.assertTrue(query["redirect_uri"].startswith("http://127.0.0.1:")) + exchange = self.auth.requests("/token")[0]["body"] + self.assertEqual(exchange["resource"], self.server.url) + auth = self.auth_state() + self.assertEqual( + (auth["state"], auth["account"], auth["client"]), + ("signed_in", "ana@example.com", "registered"), + ) + creds = json.loads((self.app.home / "creds.json").read_text()) + token = creds["mcp"]["web"]["oauth"]["access"] + self.assertNotIn(token, json.dumps(self.settings()[0])) + + # Signed in, the server's tools join and calls carry the token. + self.reconnect() + self.assertIn("echoed", self.output(self.turn("echo"))) + self.assertEqual(self.bearers()[-1], f"Bearer {token}") + + # A token about to expire is refreshed before it is sent. + creds["mcp"]["web"]["oauth"]["expires"] = int(time.time() * 1000) + 1000 + (self.app.home / "creds.json").write_text(json.dumps(creds)) + seen = len(self.server.seen) + self.assertIn("echoed", self.output(self.turn("echo again"))) + self.assertEqual(len(self.auth.requests("/token")), 2) + self.assertNotIn(None, self.bearers()[seen:]) + + # A token the server refuses is refreshed once and the call retried. + self.auth.revoke_access() + self.assertIn("echoed", self.output(self.turn("after revocation"))) + refreshes = [ + r + for r in self.auth.requests("/token") + if r["body"]["grant_type"] == "refresh_token" + ] + self.assertEqual(len(refreshes), 2) + self.assertEqual(refreshes[-1]["body"]["resource"], self.server.url) + + # A wider scope is asked for with a new sign-in. + self.tool = "admin" + refused = self.output(self.turn("admin")) + self.assertIn("wider access", refused) + self.assertEqual(self.auth_state()["step_up"], "read offline_access admin") + self.assertEqual(self.sign_in()["scope"], "read offline_access admin") + self.assertIn("echoed", self.output(self.turn("admin again"))) + self.assertIsNone(self.auth_state()["step_up"]) + + # A refused refresh needs a new sign-in instead of trying again. + self.tool = "echo" + self.auth.revoke_refresh() + refused = self.output(self.turn("after the refresh token is gone")) + self.assertIn("needs the user to sign in", refused) + self.assertEqual(self.auth_state()["state"], "needs_sign_in") + tokens = len(self.auth.requests("/token")) + self.output(self.turn("still signed out")) + self.assertEqual(len(self.auth.requests("/token")), tokens) + + # Signing out drops the tokens and keeps the server. + self.sign_in() + self.patch({"web": {"secrets": {"oauth": None}}}) + auth = self.auth_state() + self.assertEqual((auth["state"], auth["account"]), ("signed_out", None)) + creds = json.loads((self.app.home / "creds.json").read_text()) + self.assertNotIn("access", creds["mcp"]["web"]["oauth"]) diff --git a/test/harness/oauth_test.gleam b/test/harness/oauth_test.gleam index 641b48280..f6ad9c1b5 100644 --- a/test/harness/oauth_test.gleam +++ b/test/harness/oauth_test.gleam @@ -21,11 +21,13 @@ fn fake(callback: oauth.Callback) -> oauth.Login { "fake-accounts", callback, fn(grant) { - "https://auth.example/authorize?" - <> uri.query_to_string([ - #("redirect_uri", grant.redirect), - #("state", grant.state), - ]) + Ok( + "https://auth.example/authorize?" + <> uri.query_to_string([ + #("redirect_uri", grant.redirect), + #("state", grant.state), + ]), + ) }, fn(_grant, code, progress) { progress("provisioning " <> code) @@ -175,7 +177,7 @@ fn device_login() -> oauth.Login { ), ) }), - fn(_) { "" }, + fn(_) { Ok("") }, fn(_, _, _) { Error("unused") }, fn(credential) { let email = diff --git a/web/src/lib/api.gen.d.ts b/web/src/lib/api.gen.d.ts index 336c44791..0a8514fd8 100644 --- a/web/src/lib/api.gen.d.ts +++ b/web/src/lib/api.gen.d.ts @@ -1735,6 +1735,19 @@ export interface components { environment: string[]; headers: string[]; }; + /** @description A server's OAuth sign-in. none until the server asks for one; needs_sign_in when it asked and albedo has no usable token, signed_in, or signed_out after the user signed out. Start a sign-in with PUT /auth/logins/{login_id} and provider mcp:. Tokens and client secrets never appear. */ + MCPAuth: { + /** @enum {string} */ + state: "none" | "needs_sign_in" | "signed_in" | "signed_out"; + account: string | null; + expires_at: string | null; + scope: string | null; + /** @description The wider scope a signed-in server asked for; signing in again grants it. */ + step_up: string | null; + reason: string | null; + /** @description configured when the user set a client id, registered when albedo registered itself. */ + client: ("configured" | "registered") | null; + }; MCPDefinition: { enabled: boolean; /** @enum {string} */ @@ -1755,6 +1768,7 @@ export interface components { startup_timeout_ms: number; call_timeout_ms: number; secret_presence: components["schemas"]["SecretPresence"]; + auth: components["schemas"]["MCPAuth"]; }; MCPSecretsPatch: { bearer_token?: string | null; @@ -1764,6 +1778,13 @@ export interface components { headers?: { [key: string]: string | null; }; + /** @description Null signs the server out of its OAuth sign-in. */ + oauth?: null; + /** @description A client the user registered with the server's authorization server, used instead of registering albedo; null forgets it. */ + oauth_client?: { + client_id: string; + client_secret?: string | null; + } | null; }; /** @description Partial merge patch. Public and secret sources cannot overlap. HTTP and stdio fields are validated against transport on the complete candidate. Public environment/header entries accept null removal; a null whole map clears it. Switching credential sources removes the former source in the same patch. */ MCPDefinitionPatch: { -- knotmirror 0.0.1