Files
bilalmk__todo_correct/EMPTY_STRING_FIX.md
T
Bilal Muhammad Khan fdf30c1a61 feat(phase3): implement ChatKit server with OpenAI Agents SDK and MCP integration
Implements Phase III AI-powered chatbot backend architecture:

Backend Changes:
- Add ChatKit API endpoint (/api/v1/chatkit/chat) with streaming support
- Integrate OpenAI Agents SDK with GPT-4 model configuration
- Implement Conversation and Message database models with SQLModel
- Add comprehensive test coverage (unit, integration, E2E)
- Configure environment variables for OpenAI API and MCP server

MCP Server Changes:
- Migrate to Official MCP SDK with JSON-RPC 2.0 protocol
- Implement tool registry pattern for dynamic tool registration
- Add natural language parsing for conversational task creation
- Enhance response formatting with hybrid approach (natural + structured)
- Fix empty string validation and Pydantic datetime serialization

Configuration:
- Add OPENAI_API_KEY, OPENAI_MODEL, MCP_SERVER_URL to Settings
- Add ChatKit message/history limits per constitutional requirements
- Validate MCP URL scheme (http/https only)

Testing:
- Unit tests for ChatKit store and utilities
- Integration tests for API, persistence, logging, truncation
- E2E tests for workflow and edge cases
- Database configuration tests

Documentation:
- Add verification guides and test results
- Document response format standards (CHATKIT_RESPONSE_FORMAT.md)
- Record troubleshooting for 500 errors and empty string fixes

Satisfies Phase III hackathon requirements:
- OpenAI ChatKit UI integration ready
- Stateless backend with database state persistence
- All 5 MCP tools (add/list/complete/delete/update tasks)
- Conversation history storage

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-15 00:12:12 +05:00

3.6 KiB

Fix: Empty String Validation Error for DateTime Fields

Problem

When testing: "I need to submit the quarterly report by January 20th at 2pm, this is very urgent and important"

Error:

ValidationError: 1 validation error for AddTaskInput
reminder_at
  Input should be a valid datetime or date, input is too short
  [type=datetime_from_date_parsing, input_value='', input_type=str]

Root Cause

The AI was sending empty strings '' for datetime fields it didn't want to set, instead of:

  • Omitting the field entirely
  • Sending null
  • Sending None

Example of what the AI sent:

{
  "user_id": "550e8400-...",
  "title": "Submit quarterly report",
  "priority": "high",
  "due_date": "2026-01-20T14:00:00Z",
  "reminder_at": ""   Empty string causes Pydantic error
}

Pydantic's datetime validator cannot parse an empty string, so it threw a validation error.

Solution

Added a @field_validator to convert empty strings to None before the datetime validation:

@field_validator("due_date", "reminder_at", mode="before")
@classmethod
def validate_datetime_fields(cls, v):
    """
    Convert empty strings to None for datetime fields.

    AI may send empty strings when it doesn't want to set a field.
    Pydantic can't parse empty strings as datetimes, so convert to None.
    """
    if v == "" or v is None:
        return None
    return v

Location: mcp_server/src/todo_mcp/models/inputs.py

  • Added to AddTaskInput class (line ~117)
  • Added to UpdateTaskInput class (line ~307)

What's Fixed

Empty strings → None: AI can send reminder_at="" and it converts to None Validation passes: Pydantic validates None successfully for Optional[datetime] No more 500 errors: MCP tool handles all AI inputs correctly

Test Results

Before Fix:

AddTaskInput(
    user_id="...",
    title="Test",
    reminder_at=""  # ❌ ValidationError
)

After Fix:

AddTaskInput(
    user_id="...",
    title="Test",
    reminder_at=""  # ✅ Converted to None, validation passes
)
# reminder_at = None

Files Changed

  1. mcp_server/src/todo_mcp/models/inputs.py

    • Added datetime validator to AddTaskInput
    • Added datetime validator to UpdateTaskInput
  2. mcp_server/src/todo_mcp/utils/responses.py (previous fix)

    • Updated response formatting to include all fields
  3. mcp_server/src/todo_mcp/tools_registry.py (previous fix)

    • Updated tool schemas with advanced fields

Ready to Test

The MCP server has already reloaded with these changes. Your test should now work:

curl -N -X POST http://localhost:8000/api/chatkit/chat \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{"message": "I need to submit the quarterly report by January 20th at 2pm, this is very urgent and important"}'

Expected Success:

{
  "type": "message",
  "content": "✅ Created task #X: 'Submit the quarterly report' (Priority: High, Due: Jan 20, 2026 at 2:00 PM)",
  "tool_results": [{
    "tool": "todo_add_task",
    "result": {
      "task_id": 20,
      "title": "Submit the quarterly report",
      "priority": "high",
      "due_date": "2026-01-20T14:00:00+00:00",
      "reminder_at": null   Empty string converted to null
    }
  }]
}

All Fixes Applied

  1. Tool Schema - Added advanced fields so AI knows about them
  2. Response Formatting - Include all fields and serialize datetimes
  3. Empty String Handling - Convert empty strings to None for datetime fields

Your natural language task creation should now work perfectly! 🎉