Skip to content

fix(kg): validate ISO-8601 date formats in temporal parameters at MCP boundary #1164

@arnoldwender

Description

@arnoldwender

Finding split from #809 per @bensig's review request. This is a data-integrity bug, not a security issue.

Summary

tool_kg_query (as_of) and tool_kg_add (valid_from) accept any string and forward it to SQLite without format validation. Parameterized queries prevent SQL injection, but invalid date strings silently produce empty result sets instead of matching facts — users cannot distinguish "no fact at this time" from "your date format was unrecognized."

This is particularly painful for natural-language LLM callers that may synthesize dates like "March 2026" or "Jan 2025" instead of the expected YYYY-MM / YYYY-MM-DD.

Affected version

v3.3.3 — verified against develop @ 8ac98f0:

Reproduction

from mempalace.knowledge_graph import KnowledgeGraph
kg = KnowledgeGraph(":memory:")
kg.add_triple("Alice", "lives_in", "Halle", valid_from="2025-01-01")

# Typical natural-language caller:
print(kg.query_entity("Alice", as_of="Jan 2025"))    # -> []   (silent miss)
print(kg.query_entity("Alice", as_of="2025-01-01"))  # -> 1 fact

# add_triple swallows garbage too:
kg.add_triple("Bob", "born_on", "Earth", valid_from="not-a-date")  # stored without complaint

Suggested fix

Add an ISO-8601 validator at the MCP boundary (before values reach the storage layer):

import re

_DATE_RE = re.compile(r'^\d{4}(?:-(?:0[1-9]|1[0-2])(?:-(?:0[1-9]|[12]\d|3[01]))?)?$')


def _validate_iso_date(value, param_name):
    if value and not _DATE_RE.match(value):
        raise ValueError(
            f"{param_name}={value!r} is not a valid ISO-8601 date "
            f"(expected YYYY, YYYY-MM, or YYYY-MM-DD)"
        )
    return value

Apply in tool_kg_query and tool_kg_add before delegating to _kg.

Happy to submit a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/kgKnowledge grapharea/mcpMCP server and toolsbugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions