Spaces:
Running
Running
File size: 1,575 Bytes
7114af0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
"""Handler for creating Datawrapper charts."""
import json
from mcp.types import TextContent
from ..config import CHART_CLASSES
from ..utils import get_api_token, json_to_dataframe
async def create_chart(arguments: dict) -> list[TextContent]:
"""Create a chart with full Pydantic model configuration."""
api_token = get_api_token()
# Convert data to DataFrame
df = json_to_dataframe(arguments["data"])
# Get chart class and validate config
chart_type = arguments["chart_type"]
chart_class = CHART_CLASSES[chart_type]
# Validate and create chart using Pydantic model
try:
chart = chart_class.model_validate(arguments["chart_config"])
except Exception as e:
return [
TextContent(
type="text",
text=f"Invalid chart configuration: {str(e)}\n\n"
f"Use get_chart_schema with chart_type '{chart_type}' "
f"to see the valid schema.",
)
]
# Set data on chart instance
chart.data = df
# Create chart using Pydantic instance method
chart.create(access_token=api_token)
result = {
"chart_id": chart.chart_id,
"chart_type": chart_type,
"title": chart.title,
"edit_url": chart.get_editor_url(),
"message": (
f"Chart created successfully! Edit it at: {chart.get_editor_url()}\n"
f"Use publish_chart with chart_id '{chart.chart_id}' to make it public."
),
}
return [TextContent(type="text", text=json.dumps(result, indent=2))]
|