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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 18 additions & 31 deletions core/mcp/clientmanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -600,8 +600,6 @@ func (m *MCPManager) UpdateClient(id string, updatedConfig *schemas.MCPClientCon
return fmt.Errorf("auth_type cannot be updated for client %s", id)
}

oldName := client.ExecutionConfig.Name

oauthConfigID := client.ExecutionConfig.OauthConfigID
if updatedConfig.OauthConfigID != nil {
oauthConfigID = updatedConfig.OauthConfigID
Expand Down Expand Up @@ -638,38 +636,27 @@ func (m *MCPManager) UpdateClient(id string, updatedConfig *schemas.MCPClientCon
// Atomically replace the config pointer
client.ExecutionConfig = newConfig

// If the client name has changed, update all tool name prefixes in the ToolMap
if oldName != updatedConfig.Name {
oldPrefix := oldName + "-"
newPrefix := updatedConfig.Name + "-"

// Create a new ToolMap with updated tool names
newToolMap := make(map[string]schemas.ChatTool, len(client.ToolMap))
for oldToolName, tool := range client.ToolMap {
var newToolName string
if strings.HasPrefix(oldToolName, oldPrefix) {
// Update the tool name by replacing the old prefix with the new prefix
newToolName = newPrefix + strings.TrimPrefix(oldToolName, oldPrefix)
} else {
newToolName = oldToolName
}

// Update the tool's function name if it's a function tool
if tool.Function != nil {
updatedTool := tool
updatedTool.Function.Name = newToolName
newToolMap[newToolName] = updatedTool
} else {
newToolMap[newToolName] = tool
}
// Rebind ToolMap keys (and inner Function.Name) to the current client name.
newPrefix := updatedConfig.Name + "-"
newToolMap := make(map[string]schemas.ChatTool, len(client.ToolMap))
for oldToolName, tool := range client.ToolMap {
newToolName := oldToolName
if _, suffix, ok := strings.Cut(oldToolName, "-"); ok {
newToolName = newPrefix + suffix
}
if tool.Function != nil {
fn := *tool.Function
fn.Name = newToolName
tool.Function = &fn
}
newToolMap[newToolName] = tool
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
Comment thread
Pratham-Mishra04 marked this conversation as resolved.
Resolved

// Replace the old ToolMap with the new one
client.ToolMap = newToolMap
// Replace the old ToolMap with the new one
client.ToolMap = newToolMap

// Also update the client Name field
client.Name = updatedConfig.Name
}
// Also update the client Name field
client.Name = updatedConfig.Name
Comment thread
Pratham-Mishra04 marked this conversation as resolved.
Resolved

return nil
}
Expand Down
8 changes: 6 additions & 2 deletions core/mcp/codemode/starlark/listfiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ func (s *StarlarkCodeMode) createListToolFilesTool() schemas.ChatTool {
"In code, access tools via: server_name.tool_name(param=value). " +
"The server names used in code correspond to the human-readable names shown in this listing. " +
"This tool is generic and works with any set of servers connected at runtime. " +
"Always check this tool whenever you are unsure about what tools you have available or if you want to verify available servers and their tools."
"CALL THIS TOOL FIRST whenever the user references a server, tool, capability, or action that is not visible in your current tool list — connected MCP servers and their tools are NOT included in your top-level tool schema, so the only way to discover them is by calling listToolFiles. " +
"Examples that should trigger this tool: user names a server you don't recognize (e.g. 'localserver', 'mydb'), asks 'who am I on X', 'what can X do', 'does X have a tool for Y', or asks you to perform an action and you are unsure whether a matching tool exists. " +
"Do NOT tell the user a server or capability is unavailable until you have called listToolFiles and confirmed it is absent."
} else {
description = "Returns a tree structure listing all virtual .pyi stub files available for connected MCP servers, organized by individual tool. " +
"Each tool has a corresponding file (e.g., servers/<serverName>/<toolName>.pyi) that contains compact Python signatures for that specific tool. " +
Expand All @@ -38,7 +40,9 @@ func (s *StarlarkCodeMode) createListToolFilesTool() schemas.ChatTool {
"In code, access tools via: server_name.tool_name(param=value). " +
"The server names used in code correspond to the human-readable names shown in this listing. " +
"This tool is generic and works with any set of servers connected at runtime. " +
"Always check this tool whenever you are unsure about what tools you have available or if you want to verify available servers and their tools."
"CALL THIS TOOL FIRST whenever the user references a server, tool, capability, or action that is not visible in your current tool list — connected MCP servers and their tools are NOT included in your top-level tool schema, so the only way to discover them is by calling listToolFiles. " +
"Examples that should trigger this tool: user names a server you don't recognize (e.g. 'localserver', 'mydb'), asks 'who am I on X', 'what can X do', 'does X have a tool for Y', or asks you to perform an action and you are unsure whether a matching tool exists. " +
"Do NOT tell the user a server or capability is unavailable until you have called listToolFiles and confirmed it is absent."
}

return schemas.ChatTool{
Expand Down
61 changes: 43 additions & 18 deletions core/mcp/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,28 @@ import (

// ResolvePerUserOAuthToken looks up the per-user OAuth access token for the given client.
// If no token exists yet, it initiates an OAuth flow and returns an MCPUserOAuthRequiredError.
//
// Mode-strict: derives AuthMode from context state
// and looks up exactly one identity column. No fallback chain.
func ResolvePerUserOAuthToken(ctx *schemas.BifrostContext, client *schemas.MCPClientState, oauth2Provider schemas.OAuth2Provider) (string, error) {
if oauth2Provider == nil {
return "", fmt.Errorf("per-user OAuth requires an OAuth2Provider but none is configured")
}

virtualKeyID, _ := ctx.Value(schemas.BifrostContextKeyGovernanceVirtualKeyID).(string)
userID, _ := ctx.Value(schemas.BifrostContextKeyUserID).(string)
sessionToken, _ := ctx.Value(schemas.BifrostContextKeyMCPUserSession).(string)
mode := ctx.MCPAuthMode()
identity := identityForMCPAuthMode(ctx, mode)

// Optional X-Bf-User-Id header overrides user identity; if absent, falls back to virtual key
if mcpUserID, _ := ctx.Value(schemas.BifrostContextKeyMCPUserID).(string); mcpUserID != "" {
userID = mcpUserID
if identity == "" {
// No identity column populated for the derived mode. We can neither
// look up an existing token nor mint a flow whose result would be
// findable on subsequent calls, so refuse early with actionable copy.
return "", fmt.Errorf(
"per-user OAuth for %s requires an identity: send a Virtual Key (x-bf-vk), authenticate as a user, or set x-bf-mcp-session-id to any opaque string you'll re-send on subsequent calls",
client.ExecutionConfig.Name,
)
}

accessToken, err := oauth2Provider.GetUserAccessTokenByIdentity(ctx, virtualKeyID, userID, sessionToken, client.ExecutionConfig.ID)
accessToken, err := oauth2Provider.GetUserAccessTokenByMode(ctx, mode, identity, client.ExecutionConfig.ID)
// Both sentinels mean "this user must re-authenticate":
Comment thread
Pratham-Mishra04 marked this conversation as resolved.
Resolved
// - ErrOAuth2TokenNotFound: row missing (never authed, or purged after permanent refresh failure)
// - ErrOAuth2TokenExpired: row present but tokens unusable (access expired + no refresh available)
Expand All @@ -33,23 +40,14 @@ func ResolvePerUserOAuthToken(ctx *schemas.BifrostContext, client *schemas.MCPCl
return "", fmt.Errorf("failed to get user access token for MCP server %s: %w", client.ExecutionConfig.Name, err)
}
if err != nil {
// In LLM gateway mode with no identity, an OAuth flow would produce an orphaned token.
isMCPGateway, _ := ctx.Value(schemas.BifrostContextKeyIsMCPGateway).(bool)
if !isMCPGateway && userID == "" && virtualKeyID == "" {
return "", fmt.Errorf(
"per-user OAuth for %s requires a user identity: include X-Bf-User-Id or a Virtual Key in your request so the token can be linked to you",
client.ExecutionConfig.Name,
)
}

if client.ExecutionConfig.OauthConfigID == nil || *client.ExecutionConfig.OauthConfigID == "" {
return "", fmt.Errorf("per-user OAuth requires an OAuth config but MCP client %s has none", client.ExecutionConfig.Name)
}
redirectURI := BuildRedirectURIFromContext(ctx)
if redirectURI == "" {
return "", fmt.Errorf("per-user OAuth requires a redirect URI but none is available in context")
}
flowInitiation, sessionID, flowErr := oauth2Provider.InitiateUserOAuthFlow(ctx, *client.ExecutionConfig.OauthConfigID, client.ExecutionConfig.ID, redirectURI)
flowInitiation, sessionID, flowErr := oauth2Provider.InitiateUserOAuthFlow(ctx, *client.ExecutionConfig.OauthConfigID, client.ExecutionConfig.ID, redirectURI, mode)
if flowErr != nil {
return "", fmt.Errorf("failed to initiate per-user OAuth flow for %s: %w", client.ExecutionConfig.Name, flowErr)
}
Expand All @@ -58,13 +56,40 @@ func ResolvePerUserOAuthToken(ctx *schemas.BifrostContext, client *schemas.MCPCl
MCPClientName: client.ExecutionConfig.Name,
AuthorizeURL: flowInitiation.AuthorizeURL,
SessionID: sessionID,
Message: fmt.Sprintf("Authentication required for %s. Please visit the authorize URL to connect your account.", client.ExecutionConfig.Name),
// Include the URL in the message itself — plain-text clients
// (curl, basic SDK wrappers) won't parse extra_fields, and a
// "please visit the authorize URL" hint with no URL is
// useless to them. The URL is already exposed on the same
// response via extra_fields.mcp_auth_required.authorize_url,
// so embedding it here doesn't widen the surface.
Message: fmt.Sprintf("Authentication required for %s. Visit %s to connect your account.", client.ExecutionConfig.Name, flowInitiation.AuthorizeURL),
Comment thread
Pratham-Mishra04 marked this conversation as resolved.
Resolved
}
}

return accessToken, nil
}

// identityForMode returns the identity string to look up by, given the derived
// mode. Mirrors the priority used by ctx.AuthMode(): UserID for user mode,
// resolved VK ID for vk mode, session ID for session mode.
func identityForMCPAuthMode(ctx *schemas.BifrostContext, mode schemas.MCPAuthMode) string {
switch mode {
case schemas.MCPAuthModeUser:
if v, _ := ctx.Value(schemas.BifrostContextKeyUserID).(string); v != "" {
return v
}
case schemas.MCPAuthModeVK:
if v, _ := ctx.Value(schemas.BifrostContextKeyGovernanceVirtualKeyID).(string); v != "" {
return v
}
case schemas.MCPAuthModeSession:
if v, _ := ctx.Value(schemas.BifrostContextKeyMCPSessionID).(string); v != "" {
return v
}
}
return ""
}

// BuildPerUserOAuthHeaders clones the provided headers and adds the Bearer token,
// preserving any request-scoped extra headers already present.
func BuildPerUserOAuthHeaders(headers http.Header, accessToken string) http.Header {
Expand Down
25 changes: 23 additions & 2 deletions core/schemas/bifrost.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,28 @@ const (
// BifrostContextKey is a type for context keys used in Bifrost.
type BifrostContextKey string

// MCPAuthMode describes which identity dimension a per-user OAuth row is keyed by.
// It is a derived view of context state at the point of token lookup, never
// stored as a context key. Derived via BifrostContext.MCPAuthMode().
type MCPAuthMode string

const (
// MCPAuthModeUser: identity is a user id populated by an upstream auth
// middleware or plugin. Token rows keyed by user_id.
MCPAuthModeUser MCPAuthMode = "user"
// MCPAuthModeVK: identity is a virtual key. Token rows keyed by vk_id.
MCPAuthModeVK MCPAuthMode = "vk"
// MCPAuthModeSession: identity is a client-issued opaque session ID, asserted
// via the x-bf-mcp-session-id header. Token rows keyed by session_id.
// Used when there's no VK or user; the caller owns the session ID and must
// present it on every subsequent request to use the bound OAuth token.
MCPAuthModeSession MCPAuthMode = "session"
// MCPAuthModeNone: no identity dimension is present on the request (no
// user, no VK, no session header). Lets callers branch on the mode
// without mistaking an unauthenticated request for a session-mode caller.
MCPAuthModeNone MCPAuthMode = "none"
Comment thread
Pratham-Mishra04 marked this conversation as resolved.
Resolved
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// BifrostContextKeyRequestType is a context key for the request type.
const (
BifrostContextKeySessionToken BifrostContextKey = "bifrost-session-token" // string (session token for authentication - set by auth middleware)
Expand Down Expand Up @@ -221,8 +243,7 @@ const (
BifrostContextKeyDeferTraceCompletion BifrostContextKey = "bifrost-defer-trace-completion" // bool (signals trace completion should be deferred for streaming - set by streaming handlers)
BifrostContextKeyTraceCompleter BifrostContextKey = "bifrost-trace-completer" // func([]PluginLogEntry) (callback to complete trace after streaming, receives transport plugin logs - set by tracing middleware)
BifrostContextKeyAccumulatorID BifrostContextKey = "bifrost-accumulator-id" // string (ID for streaming accumulator lookup - set by tracer for accumulator operations)
BifrostContextKeyMCPUserSession BifrostContextKey = "bifrost-mcp-user-session" // string (per-user OAuth session token, automatically generated by bifrost)
BifrostContextKeyMCPUserID BifrostContextKey = "bifrost-mcp-user-id" // string (per-user OAuth user identifier from X-Bf-User-Id header)
BifrostContextKeyMCPSessionID BifrostContextKey = "bifrost-mcp-session-id" // string (session-mode identity: any opaque value asserted by the caller via x-bf-mcp-session-id; binds the OAuth token row to subsequent /mcp calls when no VK or user is present)
BifrostContextKeyOAuthRedirectURI BifrostContextKey = "bifrost-oauth-redirect-uri" // string (OAuth callback URL, e.g. https://host/api/oauth/callback - set by HTTP middleware)
BifrostContextKeyIsMCPGateway BifrostContextKey = "bifrost-is-mcp-gateway" // bool (true when request is being handled via the MCP gateway path)
BifrostContextKeyHasEmittedMessageDelta BifrostContextKey = "bifrost-has-emitted-message-delta" // bool (tracks whether message_delta was already emitted during streaming - avoids duplicates)
Expand Down
25 changes: 25 additions & 0 deletions core/schemas/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,31 @@ func (bc *BifrostContext) Value(key any) any {
return bc.parent.Value(key)
}

// AuthMode derives the per-user OAuth lookup mode from current context state.
// Priority: UserID > VirtualKey > session. Call this at token-lookup time, not
// in middleware — the governance plugin can inject UserID (via VK→owner
// resolution) after middleware runs, and the mode must reflect that.
//
// Returns MCPAuthModeNone when no identity column is populated (no user, no
// VK, no session header), so callers that branch on the returned mode alone
// cannot mistake an unauthenticated request for a session-mode caller.
//
// VK check uses BifrostContextKeyGovernanceVirtualKeyID (the resolved VK row
// ID) rather than BifrostContextKeyVirtualKey (the raw header value) because
// vk-mode token rows are keyed by the resolved VK ID.
func (bc *BifrostContext) MCPAuthMode() MCPAuthMode {
if userID, ok := bc.Value(BifrostContextKeyUserID).(string); ok && userID != "" {
return MCPAuthModeUser
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
if vkID, ok := bc.Value(BifrostContextKeyGovernanceVirtualKeyID).(string); ok && vkID != "" {
return MCPAuthModeVK
}
if sid, ok := bc.Value(BifrostContextKeyMCPSessionID).(string); ok && sid != "" {
return MCPAuthModeSession
}
return MCPAuthModeNone
}
Comment thread
Pratham-Mishra04 marked this conversation as resolved.
Resolved

// SetValue sets a value in the internal userValues map.
// For scoped contexts, delegates to the root context via valueDelegate.
// This is thread-safe and can be called concurrently.
Expand Down
3 changes: 2 additions & 1 deletion core/schemas/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ var (
ErrOAuth2RefreshFailed = errors.New("oauth2 token refresh failed")
ErrOAuth2NotPerUserSession = errors.New("state does not match a per-user oauth session")
ErrOAuth2TokenNotFound = errors.New("per-user oauth token not found for this identity and mcp server")
ErrPerUserOAuthPendingFlowExpired = errors.New("per-user oauth pending flow has expired")
ErrOAuth2FlowNotPending = errors.New("oauth flow is not in pending state")
ErrOAuth2FlowExpired = errors.New("oauth flow has expired")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// ErrMCPReconnectNotApplicable signals that the reconnect operation is not
// meaningful for this client type — e.g. per-user OAuth clients, where
// each user manages their own auth and there is no shared upstream
Expand Down
38 changes: 21 additions & 17 deletions core/schemas/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,28 +21,32 @@ type OAuth2Provider interface {

// Per-user OAuth methods

// GetUserAccessToken retrieves the access token for a per-user OAuth session.
// If the token is expired, it automatically attempts a refresh.
GetUserAccessToken(ctx context.Context, sessionToken string) (string, error)

// GetUserAccessTokenByIdentity retrieves the upstream access token for a user
// identified by virtualKeyID, userID, or sessionToken (fallback), for a specific
// MCP client. Tokens looked up by identity persist across sessions.
GetUserAccessTokenByIdentity(ctx context.Context, virtualKeyID, userID, sessionToken, mcpClientID string) (string, error)

// InitiateUserOAuthFlow creates a per-user OAuth session and returns the authorization URL.
// Returns (flow initiation details, session ID for polling, error).
InitiateUserOAuthFlow(ctx context.Context, oauthConfigID string, mcpClientID string, redirectURI string) (*OAuth2FlowInitiation, string, error)
// GetUserAccessTokenByMode retrieves the upstream access token for a single
// identity dimension determined by mode. No fallback chain — exactly one
// identity column is queried. Filters status='active' so orphaned rows never
// satisfy a lookup. identity is the user ID for MCPAuthModeUser, the VK row
// ID for MCPAuthModeVK, and the raw session ID for MCPAuthModeSession.
GetUserAccessTokenByMode(ctx context.Context, mode MCPAuthMode, identity, mcpClientID string) (string, error)

// InitiateUserOAuthFlow creates or refreshes the per-user OAuth flow row
// for a (mode, identity, mcp_client) binding and returns the auth landing
// URL. flowMode tags the row's flow_mode and decides which identity column
// gets populated from context (UserID for MCPAuthModeUser, the resolved VK
// row ID for MCPAuthModeVK, the session ID for MCPAuthModeSession). For
// MCPAuthModeUser flows where no UserID is available in context yet
// (external MCP client OAuth init), the column is left NULL and stamped
// at completion. Returns (flow initiation details, flow row ID, error).
InitiateUserOAuthFlow(ctx context.Context, oauthConfigID string, mcpClientID string, redirectURI string, flowMode MCPAuthMode) (*OAuth2FlowInitiation, string, error)
Comment thread
Pratham-Mishra04 marked this conversation as resolved.
Resolved

// CompleteUserOAuthFlow handles the OAuth callback for a per-user flow.
// Returns the session token that the user should send on subsequent requests.
// Returns the SessionID stored on the flow row (populated for session-mode,
// empty otherwise).
CompleteUserOAuthFlow(ctx context.Context, state string, code string) (string, error)

// RefreshUserAccessToken refreshes a per-user OAuth access token.
RefreshUserAccessToken(ctx context.Context, sessionToken string) error
// RefreshUserAccessToken refreshes a per-user OAuth access token, looked up
// by the token row's primary-key ID.
RefreshUserAccessToken(ctx context.Context, tokenID string) error

// RevokeUserToken revokes a per-user OAuth token and marks the session as revoked.
RevokeUserToken(ctx context.Context, sessionToken string) error
}

// OauthConfig represents OAuth client configuration
Expand Down
Loading
Loading