Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix: mcp oauth session user scoping (#8630)
jnjpngeb748b8f1a23
diff --git a/letta/services/mcp_manager.py b/letta/services/mcp_manager.pyindex a47084842..2167882a5 100644--- a/letta/services/mcp_manager.py+++ b/letta/services/mcp_manager.py@@ -372,7 +372,9 @@ class MCPManager:# Link existing OAuth sessions for the same user and server URL# This ensures OAuth sessions created during testing get linked to the server+ # Also updates the server_name to match the new MCP server's nameserver_url = getattr(mcp_server, "server_url", None)+ server_name = getattr(mcp_server, "server_name", None)if server_url:result = await session.execute(select(MCPOAuth).where(@@ -387,11 +389,15 @@ class MCPManager:# TODO: @jnjpng we should update sessions in bulkfor oauth_session in oauth_sessions:oauth_session.server_id = mcp_server.id+ # Update server_name to match the persisted MCP server's name+ if server_name:+ oauth_session.server_name = server_nameawait oauth_session.update_async(db_session=session, actor=actor, no_commit=True)if oauth_sessions:logger.info(- f"Linked {len(oauth_sessions)} OAuth sessions to MCP server {mcp_server.id} (URL: {server_url}) for user {actor.id}"+ f"Linked {len(oauth_sessions)} OAuth sessions to MCP server {mcp_server.id} "+ f"(URL: {server_url}, name: {server_name}) for user {actor.id}")# context manager now handles commits@@ -676,22 +682,37 @@ class MCPManager:if tools_deleted > 0:logger.info(f"Deleted {tools_deleted} MCP tools associated with MCP server {mcp_server_id}")- # Delete OAuth sessions for the same user and server URL in the same transaction- # This handles orphaned sessions that were created during testing/connection+ # Delete OAuth sessions associated with this MCP server+ # 1. Delete sessions directly linked to this server (server_id matches)+ # 2. Delete orphaned pending sessions (server_id IS NULL) for same server_url + user+ # 3. Keep authorized sessions linked to OTHER MCP servers (different server_id)oauth_count = 0++ # Delete sessions directly linked to this server+ result = await session.execute(+ delete(MCPOAuth).where(+ MCPOAuth.server_id == mcp_server_id,+ MCPOAuth.organization_id == actor.organization_id,+ )+ )+ oauth_count += result.rowcount++ # Delete orphaned sessions (no server_id) for same server_url + userif server_url:result = await session.execute(delete(MCPOAuth).where(MCPOAuth.server_url == server_url,+ MCPOAuth.server_id.is_(None), # Only orphaned sessions (not linked to any server)MCPOAuth.organization_id == actor.organization_id,- MCPOAuth.user_id == actor.id, # Only delete sessions for the same user+ MCPOAuth.user_id == actor.id,))- oauth_count = result.rowcount- if oauth_count > 0:- logger.info(- f"Deleting {oauth_count} OAuth sessions for MCP server {mcp_server_id} (URL: {server_url}) for user {actor.id}"- )+ oauth_count += result.rowcount++ if oauth_count > 0:+ logger.info(+ f"Deleted {oauth_count} OAuth sessions for MCP server {mcp_server_id} (URL: {server_url}) for user {actor.id}"+ )# Delete the MCP server, will cascade delete to linked OAuth sessionsawait session.execute(@@ -795,7 +816,7 @@ class MCPManager:"""# If no OAuth is provided, check if we have stored OAuth credentialsif oauth is None and hasattr(server_config, "server_url"):- oauth_session = await self.get_oauth_session_by_server(server_config.server_url, actor)+ oauth_session = await self.get_oauth_session_by_server(server_config.server_url, actor, status=OAuthSessionStatus.AUTHORIZED)# Check if access token exists by attempting to decrypt itif oauth_session and oauth_session.access_token_enc and await oauth_session.access_token_enc.get_plaintext_async():# Create ServerSideOAuth from stored credentials@@ -901,22 +922,31 @@ class MCPManager:return None@enforce_types- async def get_oauth_session_by_server(self, server_url: str, actor: PydanticUser) -> Optional[MCPOAuthSession]:- """Get the latest OAuth session by server URL, organization, and user."""+ async def get_oauth_session_by_server(+ self, server_url: str, actor: PydanticUser, status: Optional[OAuthSessionStatus] = None+ ) -> Optional[MCPOAuthSession]:+ """Get the latest OAuth session by server URL, organization, and user.++ Args:+ server_url: The MCP server URL+ actor: The user making the request+ status: Optional status filter. If None, returns the most recent session regardless of status.+ If specified, only returns sessions with that status.+ """async with db_registry.async_session() as session:- # Query for OAuth session matching organization, user, server URL, and status+ # Query for OAuth session matching organization, user, server URL# Order by updated_at desc to get the most recent record- result = await session.execute(- select(MCPOAuth)- .where(- MCPOAuth.organization_id == actor.organization_id,- MCPOAuth.user_id == actor.id,- MCPOAuth.server_url == server_url,- MCPOAuth.status == OAuthSessionStatus.AUTHORIZED,- )- .order_by(desc(MCPOAuth.updated_at))- .limit(1)+ query = select(MCPOAuth).where(+ MCPOAuth.organization_id == actor.organization_id,+ MCPOAuth.user_id == actor.id,+ MCPOAuth.server_url == server_url,)++ # Optionally filter by status+ if status is not None:+ query = query.where(MCPOAuth.status == status)++ result = await session.execute(query.order_by(desc(MCPOAuth.updated_at)).limit(1))oauth_session = result.scalar_one_or_none()if not oauth_session:@@ -948,7 +978,8 @@ class MCPManager:if session_update.authorization_url is not None:oauth_session.authorization_url = session_update.authorization_url- # Handle encryption for authorization_code - write only to _enc column+ # Handle encryption for authorization_code+ # Only re-encrypt if the value has actually changedif session_update.authorization_code is not None:# Check if value changed by reading from _enc column onlyexisting_code = None@@ -1073,9 +1104,11 @@ class MCPManager:from letta.services.mcp.types import OauthStreamEvent# OAuth required, yield state to client to prepare to handle authorization URL+ # Note: Existing AUTHORIZED sessions are already checked upstream in get_mcp_clientyield oauth_stream_event(OauthStreamEvent.OAUTH_REQUIRED, message="OAuth authentication required")- # Create OAuth session to persist the state of the OAuth flow+ # Create new OAuth session for each test connection attempt+ # Note: Old pending sessions will be cleaned up when an MCP server is created/deletedsession_create = MCPOAuthSessionCreate(server_url=request.server_url,server_name=request.server_name,diff --git a/letta/services/mcp_server_manager.py b/letta/services/mcp_server_manager.pyindex 6c71dedb0..fcf6ed187 100644--- a/letta/services/mcp_server_manager.py+++ b/letta/services/mcp_server_manager.py@@ -469,7 +469,9 @@ class MCPServerManager:# Link existing OAuth sessions for the same user and server URL# This ensures OAuth sessions created during testing get linked to the server+ # Also updates the server_name to match the new MCP server's nameserver_url = getattr(mcp_server, "server_url", None)+ server_name = getattr(mcp_server, "server_name", None)if server_url:result = await session.execute(select(MCPOAuth).where(@@ -484,11 +486,15 @@ class MCPServerManager:# TODO: @jnjpng we should update sessions in bulkfor oauth_session in oauth_sessions:oauth_session.server_id = mcp_server.id+ # Update server_name to match the persisted MCP server's name+ if server_name:+ oauth_session.server_name = server_nameawait oauth_session.update_async(db_session=session, actor=actor, no_commit=True)if oauth_sessions:logger.info(- f"Linked {len(oauth_sessions)} OAuth sessions to MCP server {mcp_server.id} (URL: {server_url}) for user {actor.id}"+ f"Linked {len(oauth_sessions)} OAuth sessions to MCP server {mcp_server.id} "+ f"(URL: {server_url}, name: {server_name}) for user {actor.id}")# context manager now handles commits@@ -851,22 +857,37 @@ class MCPServerManager:)logger.info(f"Deleted MCPTools mappings for MCP server {mcp_server_id}")- # Delete OAuth sessions for the same user and server URL in the same transaction- # This handles orphaned sessions that were created during testing/connection+ # Delete OAuth sessions associated with this MCP server+ # 1. Delete sessions directly linked to this server (server_id matches)+ # 2. Delete orphaned pending sessions (server_id IS NULL) for same server_url + user+ # 3. Keep authorized sessions linked to OTHER MCP servers (different server_id)oauth_count = 0++ # Delete sessions directly linked to this server+ result = await session.execute(+ delete(MCPOAuth).where(+ MCPOAuth.server_id == mcp_server_id,+ MCPOAuth.organization_id == actor.organization_id,+ )+ )+ oauth_count += result.rowcount++ # Delete orphaned sessions (no server_id) for same server_url + userif server_url:result = await session.execute(delete(MCPOAuth).where(MCPOAuth.server_url == server_url,+ MCPOAuth.server_id.is_(None), # Only orphaned sessions (not linked to any server)MCPOAuth.organization_id == actor.organization_id,- MCPOAuth.user_id == actor.id, # Only delete sessions for the same user+ MCPOAuth.user_id == actor.id,))- oauth_count = result.rowcount- if oauth_count > 0:- logger.info(- f"Deleting {oauth_count} OAuth sessions for MCP server {mcp_server_id} (URL: {server_url}) for user {actor.id}"- )+ oauth_count += result.rowcount++ if oauth_count > 0:+ logger.info(+ f"Deleted {oauth_count} OAuth sessions for MCP server {mcp_server_id} (URL: {server_url}) for user {actor.id}"+ )# Delete the MCP server, will cascade delete to linked OAuth sessionsawait session.execute(@@ -966,7 +987,7 @@ class MCPServerManager:"""# If no OAuth provider is provided, check if we have stored OAuth credentialsif oauth is None and hasattr(server_config, "server_url"):- oauth_session = await self.get_oauth_session_by_server(server_config.server_url, actor)+ oauth_session = await self.get_oauth_session_by_server(server_config.server_url, actor, status=OAuthSessionStatus.AUTHORIZED)# Check if access token exists by attempting to decrypt itif oauth_session and oauth_session.access_token_enc and await oauth_session.access_token_enc.get_plaintext_async():# Create ServerSideOAuth from stored credentials@@ -1074,22 +1095,31 @@ class MCPServerManager:return None@enforce_types- async def get_oauth_session_by_server(self, server_url: str, actor: PydanticUser) -> Optional[MCPOAuthSession]:- """Get the latest OAuth session by server URL, organization, and user."""+ async def get_oauth_session_by_server(+ self, server_url: str, actor: PydanticUser, status: Optional[OAuthSessionStatus] = None+ ) -> Optional[MCPOAuthSession]:+ """Get the latest OAuth session by server URL, organization, and user.++ Args:+ server_url: The MCP server URL+ actor: The user making the request+ status: Optional status filter. If None, returns the most recent session regardless of status.+ If specified, only returns sessions with that status.+ """async with db_registry.async_session() as session:- # Query for OAuth session matching organization, user, server URL, and status+ # Query for OAuth session matching organization, user, server URL# Order by updated_at desc to get the most recent record- result = await session.execute(- select(MCPOAuth)- .where(- MCPOAuth.organization_id == actor.organization_id,- MCPOAuth.user_id == actor.id,- MCPOAuth.server_url == server_url,- MCPOAuth.status == OAuthSessionStatus.AUTHORIZED,- )- .order_by(desc(MCPOAuth.updated_at))- .limit(1)+ query = select(MCPOAuth).where(+ MCPOAuth.organization_id == actor.organization_id,+ MCPOAuth.user_id == actor.id,+ MCPOAuth.server_url == server_url,)++ # Optionally filter by status+ if status is not None:+ query = query.where(MCPOAuth.status == status)++ result = await session.execute(query.order_by(desc(MCPOAuth.updated_at)).limit(1))oauth_session = result.scalar_one_or_none()if not oauth_session:@@ -1116,6 +1146,8 @@ class MCPServerManager:oauth_session = await MCPOAuth.read_async(db_session=session, identifier=session_id, actor=actor)# Update fields that are provided+ if session_update.state is not None:+ oauth_session.state = session_update.stateif session_update.authorization_url is not None:oauth_session.authorization_url = session_update.authorization_url@@ -1268,9 +1300,11 @@ class MCPServerManager:from letta.services.mcp.types import OauthStreamEvent# OAuth required, yield state to client to prepare to handle authorization URL+ # Note: Existing AUTHORIZED sessions are already checked upstream in get_mcp_clientyield oauth_stream_event(OauthStreamEvent.OAUTH_REQUIRED, message="OAuth authentication required")- # Create OAuth session to persist the state of the OAuth flow+ # Create new OAuth session for each test connection attempt+ # Note: Old pending sessions will be cleaned up when an MCP server is created/deletedsession_create = MCPOAuthSessionCreate(server_url=request.server_url,server_name=request.server_name,