rohitg00/ai-engineering-from-scratch · error · ValueError

title and body must be strings

Error message

title and body must be strings

What it means

Type guard in the notes/create tool handler: both 'title' and 'body' arguments must be str; any non-string value (None, int, dict) is rejected before the note is stored in NOTES.

Solutions

  1. Coerce inputs to strings with str(title) and str(body)
  2. Validate client form fields before sending the tool call
  3. Return the tool error to the caller so it can re-prompt for valid input
Defensive patterns

Strategy: type-guard

When it happens

Trigger: Thrown at phases/13-tools-and-protocols/07-building-an-mcp-server/code/main.py:215 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/32279e520f4ae281. Report an issue: GitHub.

Appendix: source

Thrown at phases/13-tools-and-protocols/07-building-an-mcp-server/code/main.py:215

    if not isinstance(query, str) or not query:
        raise ValueError("query must be a non-empty string")
    limit = arguments.get("limit", 10)
    if not isinstance(limit, int) or not 1 <= limit <= 50:
        raise ValueError("limit must be an integer from 1 through 50")
    needle = query.lower()
    hits = [
        {"id": note_id, "title": note["title"]}
        for note_id, note in sorted(NOTES.items())
        if needle in note["title"].lower() or needle in note["body"].lower()
    ]
    return [{"type": "text", "text": json.dumps(hits[:limit], sort_keys=True)}]


def exec_notes_create(arguments: dict[str, Any]) -> list[dict[str, Any]]:
    title = arguments.get("title")
    body = arguments.get("body")
    if not isinstance(title, str) or not isinstance(body, str):
        raise ValueError("title and body must be strings")
    note_id = f"note-{uuid.uuid4().hex[:6]}"
    NOTES[note_id] = {"title": title, "body": body, "tag": str(arguments.get("tag", ""))}
    return [
        {"type": "text", "text": f"Created {note_id}"},
        {
            "type": "resource",
            "resource": {"uri": f"notes://{note_id}", "text": body},
        },
    ]


TOOL_EXECUTORS: dict[str, Callable[[dict[str, Any]], list[dict[str, Any]]]] = {
    "notes_create": exec_notes_create,
    "notes_list": exec_notes_list,
    "notes_search": exec_notes_search,
}

View on GitHub (pinned to 39ea8a1c6d)