Skip to content

Commit 21929c7

Browse files
committed
Fix MCP endpoint thread_id to use valid MongoDB ObjectId
- Changed thread_id from ISO timestamp format to valid ObjectId - MongoDB expects 24-character hex string for ObjectId - Fixes error: 'mcp_2025-08-16T06:43:58...' is not a valid ObjectId - Updated tests to verify ObjectId format
1 parent 5cdca9c commit 21929c7

File tree

2 files changed

+10
-9
lines changed

2 files changed

+10
-9
lines changed

src/ansari/app/main_api.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -986,8 +986,10 @@ async def mcp_complete(request: Request):
986986

987987
# Create a message logger with MCP source type for tracking
988988
# Note: Since this is unauthenticated, we use a system user ID for MCP traffic
989+
from bson import ObjectId
989990
mcp_user_id = "mcp_system_user"
990-
thread_id = f"mcp_{datetime.now(timezone.utc).isoformat()}"
991+
# Generate a new ObjectId for the thread
992+
thread_id = str(ObjectId())
991993

992994
message_logger = MessageLogger(
993995
db,

tests/unit/test_mcp_endpoint.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,10 @@ def test_mcp_endpoint_uses_mcp_source_type(self, mock_db, mock_message_logger, c
9292
call_args = mock_message_logger.call_args
9393
assert call_args[0][1] == SourceType.MCP # Second argument is source_type
9494
assert call_args[0][2] == "mcp_system_user" # Third argument is user_id
95-
assert call_args[0][3].startswith("mcp_") # Fourth argument is thread_id
95+
# Fourth argument is thread_id - should be a valid ObjectId string (24 hex chars)
96+
thread_id = call_args[0][3]
97+
assert len(thread_id) == 24 # ObjectId strings are 24 characters
98+
assert all(c in '0123456789abcdef' for c in thread_id) # All hex characters
9699

97100
def test_mcp_endpoint_handles_empty_messages(self, client):
98101
"""Test that the MCP endpoint handles empty message lists gracefully."""
@@ -164,10 +167,6 @@ def test_mcp_endpoint_thread_id_format(self, client, mock_presenter):
164167
call_args = mock_message_logger.call_args
165168
thread_id = call_args[0][3]
166169

167-
# Verify thread_id starts with "mcp_" and contains ISO timestamp
168-
assert thread_id.startswith("mcp_")
169-
# The rest should be an ISO timestamp
170-
timestamp_part = thread_id[4:] # Remove "mcp_" prefix
171-
# Basic check that it looks like an ISO timestamp
172-
assert "T" in timestamp_part # ISO format has T separator
173-
assert ":" in timestamp_part # Has time components
170+
# Verify thread_id is a valid ObjectId string
171+
assert len(thread_id) == 24 # ObjectId strings are 24 characters
172+
assert all(c in '0123456789abcdef' for c in thread_id) # All hex characters

0 commit comments

Comments
 (0)