feat(mcp): sérialisation Polars -> JSON pour les tools MCP
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,21 @@
|
|||||||
|
import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import polars as pl
|
||||||
|
|
||||||
|
|
||||||
|
def to_json_records(df: pl.DataFrame) -> list[dict[str, Any]]:
|
||||||
|
"""Convertit un DataFrame Polars en liste de dicts JSON-sérialisables.
|
||||||
|
|
||||||
|
Les dates/datetimes deviennent des chaînes ISO 8601 ; les valeurs nulles
|
||||||
|
restent None. Utilisé par tous les tools MCP pour produire une sortie propre.
|
||||||
|
"""
|
||||||
|
return [
|
||||||
|
{key: _jsonify(value) for key, value in row.items()} for row in df.to_dicts()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _jsonify(value: Any) -> Any:
|
||||||
|
if isinstance(value, (datetime.date, datetime.datetime)):
|
||||||
|
return value.isoformat()
|
||||||
|
return value
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import datetime
|
||||||
|
|
||||||
|
import polars as pl
|
||||||
|
|
||||||
|
from src.mcp.serialization import to_json_records
|
||||||
|
|
||||||
|
|
||||||
|
def test_dates_become_iso_strings():
|
||||||
|
df = pl.DataFrame({"d": [datetime.date(2025, 1, 1)], "n": [10]})
|
||||||
|
assert to_json_records(df) == [{"d": "2025-01-01", "n": 10}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_none_is_preserved():
|
||||||
|
df = pl.DataFrame({"nom": [None], "x": [3]})
|
||||||
|
assert to_json_records(df) == [{"nom": None, "x": 3}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_strings_and_numbers_untouched():
|
||||||
|
df = pl.DataFrame({"s": ["abc"], "f": [1.5]})
|
||||||
|
assert to_json_records(df) == [{"s": "abc", "f": 1.5}]
|
||||||
Reference in New Issue
Block a user