MemPalace/mempalace · error · ValueError

--metadata is not valid JSON

Error message

--metadata is not valid JSON: {exc}

What it means

Raised by _parse_metadata_arg() in the CLI when the --metadata option value cannot be parsed by json.loads. The metadata option expects a raw JSON document on the command line; any JSON syntax error (trailing comma, unquoted keys, smart quotes from shell paste, unterminated string) triggers this ValueError with the underlying parser message appended.

Solutions

  1. Quote the JSON correctly for your shell, using single quotes outside and double quotes inside: --metadata '{"source":"cli"}'
  2. Validate the string with `echo "$META" | python3 -m json.tool` or jq before running the command
  3. If the metadata lives in a variable, build it with jq -n or a here-doc to guarantee valid JSON

Example fix

# before
mempalace event add ... --metadata "{'source':'cli'}"

# after
mempalace event add ... --metadata '{"source":"cli"}'
Defensive patterns

Strategy: validation

Validate before calling

import json

# Validate before passing --metadata
try:
    json.loads(metadata_raw)
except ValueError as exc:
    raise SystemExit(f"bad --metadata JSON: {exc}")

Type guard

def is_valid_metadata_json(raw: str) -> bool:
    try:
        json.loads(raw)
        return True
    except (ValueError, TypeError):
        return False

Try / catch

try:
    meta = _parse_metadata_arg(raw)
except ValueError as exc:
    if "not valid JSON" in str(exc):
        meta = _parse_metadata_arg(json.dumps(eval_shorthand(raw)))  # or re-prompt user
    else:
        raise

Prevention

When it happens

Trigger: Passing --metadata with malformed JSON, e.g. `--metadata "{'a':1}"` (single quotes), `--metadata "{a:1}"` (unquoted key), or a value mangled by shell quoting/escaping so the string reaching the CLI is not valid JSON.

Common situations: Single-quoted Python-style dicts pasted into shell; shell interpolation stripping inner quotes; smart quotes introduced by editors/terminals; truncated JSON from variable expansion.

Related errors


AI-assisted analysis of MemPalace/mempalace@06cb6987f0 (2026-08-15). Data as JSON: /api/errors/a3496ce8dd582e0e. Report an issue: GitHub.

Appendix: source

Thrown at mempalace/cli.py:1512

        raise ValueError("pass inline text or a file, not both")
    if file_arg is not None:
        if file_arg == "-":
            return _read_stdin_exact()
        return Path(os.path.expanduser(file_arg)).read_bytes().decode("utf-8")
    if inline is not None:
        return inline
    return default


def _parse_metadata_arg(raw):
    import json

    if raw is None:
        return None
    try:
        value = json.loads(raw)
    except ValueError as exc:
        raise ValueError(f"--metadata is not valid JSON: {exc}") from None
    if not isinstance(value, dict):
        raise ValueError("--metadata must be a JSON object")
    return value


def _print_event_line(event):
    target = event["to_agent"] or "*"
    corr = f" corr={event['correlation_id']}" if event["correlation_id"] else ""
    status = f" [{event['status']}]" if event["status"] else ""
    arts = f" artifacts={len(event['artifact_ids'])}" if event["artifact_ids"] else ""
    body = event["body"].replace("\n", " ")
    if len(body) > 80:
        body = body[:77] + "..."
    body = f" :: {body}" if body else ""
    print(
        f"  {event['id']}  {event['created_at']}  {event['type']}  "
        f"{event['stream']}/{event['room']}  {event['from_agent']}->{target}"
        f"{status}{corr}{arts}{body}"

View on GitHub (pinned to 06cb6987f0)