-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunction_app.py
More file actions
802 lines (716 loc) · 32.9 KB
/
function_app.py
File metadata and controls
802 lines (716 loc) · 32.9 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
import os
import azure.functions as func
import logging
import json
import io
import uuid
from datetime import datetime, timezone
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from azure.storage.blob import BlobServiceClient, ContentSettings
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
BLOB_CONN_STR = os.environ["CHARTS_BLOB_CONNECTION_STRING"]
BLOB_CONTAINER = os.environ.get("CHARTS_BLOB_CONTAINER", "matplotlib-charts")
SUPPORTED_CHARTS = ["bar", "line", "pie", "scatter", "histogram",
"area", "box", "violin", "heatmap"]
AVAILABLE_STYLES = sorted(plt.style.available)
# ---------------------------------------------------------------------------
# Drawing functions — all support single values OR multi-series via "series"
# ---------------------------------------------------------------------------
def _draw_bar(ax, data, params):
orientation = params.get("orientation", "v") # "v" or "h"
stacked = params.get("stacked", False)
horizontal = orientation == "h"
series = data.get("series")
if series:
labels = data.get("labels", [])
x = np.arange(len(labels))
n = len(series)
ax2 = None
if stacked:
cumulative_primary = np.zeros(len(labels))
cumulative_secondary = np.zeros(len(labels))
for s in series:
values = np.array(s["values"], dtype=float)
if s.get("axis") == "secondary":
if ax2 is None:
ax2 = ax.twinx()
target, cumulative = ax2, cumulative_secondary
else:
target, cumulative = ax, cumulative_primary
if horizontal:
target.barh(x, values, left=cumulative,
label=s.get("name"), color=s.get("color"),
xerr=s.get("xerr"))
else:
target.bar(x, values, bottom=cumulative,
label=s.get("name"), color=s.get("color"),
yerr=s.get("yerr"))
cumulative += values
else:
width = params.get("bar_width", 0.8) / n
for i, s in enumerate(series):
offset = (i - n / 2 + 0.5) * width
if s.get("axis") == "secondary":
if ax2 is None:
ax2 = ax.twinx()
target = ax2
else:
target = ax
if horizontal:
target.barh(x + offset, s["values"], height=width,
label=s.get("name"), color=s.get("color"),
xerr=s.get("xerr"))
else:
target.bar(x + offset, s["values"], width=width,
label=s.get("name"), color=s.get("color"),
yerr=s.get("yerr"))
if horizontal:
ax.set_yticks(x)
ax.set_yticklabels(labels)
else:
ax.set_xticks(x)
ax.set_xticklabels(labels)
_finalize_dual_axis(ax, ax2, series)
else:
labels = data.get("labels", [])
values = data.get("values", [])
yerr = data.get("yerr")
xerr = data.get("xerr")
if horizontal:
ax.barh(labels, values, color=params.get("color"), xerr=xerr)
else:
ax.bar(labels, values, color=params.get("color"), yerr=yerr)
def _draw_line(ax, data, params):
series = data.get("series")
if series:
ax2 = None
for s in series:
if s.get("axis") == "secondary":
if ax2 is None:
ax2 = ax.twinx()
target = ax2
else:
target = ax
x = s.get("x", list(range(len(s.get("y", [])))))
yerr, xerr = s.get("yerr"), s.get("xerr")
if yerr is not None or xerr is not None:
target.errorbar(x, s["y"], yerr=yerr, xerr=xerr,
label=s.get("name"), color=s.get("color"),
marker=s.get("marker"), capsize=3)
else:
target.plot(x, s["y"], label=s.get("name"),
color=s.get("color"), marker=s.get("marker"))
_finalize_dual_axis(ax, ax2, series)
else:
x = data.get("x", list(range(len(data.get("y", [])))))
y = data.get("y", [])
yerr, xerr = data.get("yerr"), data.get("xerr")
if yerr is not None or xerr is not None:
ax.errorbar(x, y, yerr=yerr, xerr=xerr,
color=params.get("color"), marker=params.get("marker"),
capsize=3)
else:
ax.plot(x, y, color=params.get("color"), marker=params.get("marker"))
def _draw_pie(ax, data, params):
labels = data.get("labels", [])
values = data.get("values", [])
autopct = params.get("autopct", "%1.1f%%")
colors = params.get("colors")
ax.pie(values, labels=labels, autopct=autopct, colors=colors)
def _draw_scatter(ax, data, params):
series = data.get("series")
if series:
ax2 = None
for s in series:
if s.get("axis") == "secondary":
if ax2 is None:
ax2 = ax.twinx()
target = ax2
else:
target = ax
target.scatter(s["x"], s["y"], label=s.get("name"),
color=s.get("color"), marker=s.get("marker"))
_finalize_dual_axis(ax, ax2, series)
else:
ax.scatter(data.get("x", []), data.get("y", []),
color=params.get("color"),
marker=params.get("marker"))
def _draw_histogram(ax, data, params):
series = data.get("series")
bins = params.get("bins", 10)
if series:
for s in series:
ax.hist(s["values"], bins=bins, alpha=0.6,
label=s.get("name"), color=s.get("color"))
ax.legend()
else:
ax.hist(data.get("values", []), bins=bins,
color=params.get("color"))
def _draw_area(ax, data, params):
stacked = params.get("stacked", False)
alpha = params.get("alpha", 0.5)
series = data.get("series")
if series:
if stacked:
x_vals = series[0].get("x", list(range(len(series[0]["y"]))))
ys = [s["y"] for s in series]
names = [s.get("name") for s in series]
colors = [s.get("color") for s in series]
kwargs = {"labels": names}
if all(c for c in colors):
kwargs["colors"] = colors
ax.stackplot(x_vals, *ys, **kwargs)
else:
for s in series:
x_vals = s.get("x", list(range(len(s["y"]))))
ax.fill_between(x_vals, s["y"], alpha=alpha,
label=s.get("name"), color=s.get("color"))
ax.legend()
else:
x_vals = data.get("x", list(range(len(data.get("y", [])))))
y = data.get("y", [])
ax.fill_between(x_vals, y, alpha=alpha, color=params.get("color"))
def _draw_box(ax, data, params):
series = data.get("series")
if series:
arrays = [s["values"] for s in series]
labels = [s.get("name", f"G{i+1}") for i, s in enumerate(series)]
else:
arrays = data.get("values", [])
if arrays and not isinstance(arrays[0], list):
arrays = [arrays]
labels = data.get("labels")
try:
ax.boxplot(arrays, tick_labels=labels)
except TypeError:
ax.boxplot(arrays, labels=labels)
def _draw_violin(ax, data, params):
series = data.get("series")
if series:
arrays = [s["values"] for s in series]
labels = [s.get("name", f"G{i+1}") for i, s in enumerate(series)]
else:
arrays = data.get("values", [])
if arrays and not isinstance(arrays[0], list):
arrays = [arrays]
labels = data.get("labels")
positions = list(range(1, len(arrays) + 1))
ax.violinplot(arrays, positions=positions,
showmeans=params.get("show_means", False),
showmedians=params.get("show_medians", True))
if labels:
ax.set_xticks(positions)
ax.set_xticklabels(labels)
def _draw_heatmap(ax, data, params):
matrix = np.array(data.get("matrix", []), dtype=float)
xlabels = data.get("xlabels")
ylabels = data.get("ylabels")
cmap = params.get("cmap", "viridis")
annotate = params.get("annotate", False)
im = ax.imshow(matrix, cmap=cmap, aspect="auto")
ax.figure.colorbar(im, ax=ax)
if xlabels:
ax.set_xticks(range(len(xlabels)))
ax.set_xticklabels(xlabels, rotation=45, ha="right")
if ylabels:
ax.set_yticks(range(len(ylabels)))
ax.set_yticklabels(ylabels)
if annotate and matrix.size:
threshold = matrix.max() / 2.0
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
color = "white" if matrix[i, j] < threshold else "black"
ax.text(j, i, f"{matrix[i, j]:.2g}",
ha="center", va="center", color=color, fontsize=9)
DRAW_FUNCTIONS = {
"bar": _draw_bar,
"line": _draw_line,
"pie": _draw_pie,
"scatter": _draw_scatter,
"histogram": _draw_histogram,
"area": _draw_area,
"box": _draw_box,
"violin": _draw_violin,
"heatmap": _draw_heatmap,
}
# ---------------------------------------------------------------------------
# Styling helpers
# ---------------------------------------------------------------------------
def _finalize_dual_axis(ax, ax2, series):
"""Merge legends onto primary axis and color the secondary y-axis to match its series."""
if ax2 is None:
ax.legend()
return
h1, l1 = ax.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax.legend(h1 + h2, l1 + l2)
existing_secondary_legend = ax2.get_legend()
if existing_secondary_legend is not None:
existing_secondary_legend.remove()
sec_color = next(
(s.get("color") for s in series
if s.get("axis") == "secondary" and s.get("color")),
None,
)
if sec_color:
ax2.tick_params(axis="y", colors=sec_color)
ax2.yaxis.label.set_color(sec_color)
ax2.spines["right"].set_color(sec_color)
def _apply_style(params):
style = params.get("style")
if style and style in AVAILABLE_STYLES:
plt.style.use(style)
else:
plt.style.use("default")
def _apply_annotations(ax, params):
annotations = params.get("annotations") or []
for ann in annotations:
kind = ann.get("type", "point")
text = ann.get("text", "")
color = ann.get("color")
if kind == "point":
xy = (ann["x"], ann["y"])
xytext = ann.get("xytext")
arrow = ann.get("arrow", True)
kwargs = {"fontsize": ann.get("fontsize", 10)}
if xytext is not None:
kwargs["xytext"] = tuple(xytext)
else:
kwargs["xytext"] = (10, 10)
kwargs["textcoords"] = "offset points"
if arrow:
kwargs["arrowprops"] = {
"arrowstyle": ann.get("arrowstyle", "->"),
"color": color or "black",
}
if color:
kwargs["color"] = color
ax.annotate(text, xy=xy, **kwargs)
elif kind == "hline":
ax.axhline(
y=ann["y"],
color=color or "red",
linestyle=ann.get("linestyle", "--"),
linewidth=ann.get("linewidth", 1),
)
if text:
ax.text(
0.99, ann["y"], text,
transform=ax.get_yaxis_transform(),
ha="right", va="bottom",
color=color or "red",
fontsize=ann.get("fontsize", 9),
)
elif kind == "vline":
ax.axvline(
x=ann["x"],
color=color or "red",
linestyle=ann.get("linestyle", "--"),
linewidth=ann.get("linewidth", 1),
)
if text:
ax.text(
ann["x"], 0.99, text,
transform=ax.get_xaxis_transform(),
ha="left", va="top",
rotation=90,
color=color or "red",
fontsize=ann.get("fontsize", 9),
)
elif kind == "hspan":
ax.axhspan(
ymin=ann["ymin"], ymax=ann["ymax"],
color=color or "gray",
alpha=ann.get("alpha", 0.2),
)
if text:
ymid = (ann["ymin"] + ann["ymax"]) / 2
ax.text(
0.02, ymid, text,
transform=ax.get_yaxis_transform(),
ha="left", va="center",
color=color or "gray",
fontsize=ann.get("fontsize", 9),
)
elif kind == "vspan":
ax.axvspan(
xmin=ann["xmin"], xmax=ann["xmax"],
color=color or "gray",
alpha=ann.get("alpha", 0.2),
)
if text:
xmid = (ann["xmin"] + ann["xmax"]) / 2
ax.text(
xmid, 0.98, text,
transform=ax.get_xaxis_transform(),
ha="center", va="top",
color=color or "gray",
fontsize=ann.get("fontsize", 9),
)
elif kind == "text":
ax.text(
ann["x"], ann["y"], text,
color=color,
fontsize=ann.get("fontsize", 10),
ha=ann.get("ha", "left"),
va=ann.get("va", "bottom"),
)
# ---------------------------------------------------------------------------
# Blob upload
# ---------------------------------------------------------------------------
def _get_container_client(connection_string: str, container_name: str):
blob_service = BlobServiceClient.from_connection_string(connection_string)
container_client = blob_service.get_container_client(container_name)
try:
container_client.create_container(public_access="blob")
except Exception:
pass # already exists
return container_client
def _upload_to_blob(image_bytes: bytes, connection_string: str, container_name: str) -> tuple[str, str]:
"""Upload image to blob. Returns (url, blob_id)."""
container_client = _get_container_client(connection_string, container_name)
blob_id = uuid.uuid4().hex
blob_name = f"charts/{blob_id}.png"
blob_client = container_client.get_blob_client(blob_name)
blob_client.upload_blob(
image_bytes,
overwrite=True,
content_settings=ContentSettings(content_type="image/png"),
)
return blob_client.url, blob_id
def _upload_log(blob_id: str, connection_string: str, container_name: str,
endpoint: str, chart_type: str, data: dict, params: dict,
image_url: str, ip: str = "", user_agent: str = "",
intent: str = "", takeaway: str = "", audience: str = ""):
"""Upload a text log alongside the chart image."""
try:
container_client = _get_container_client(connection_string, container_name)
log_name = f"charts/{blob_id}.txt"
lines = [
f"timestamp: {datetime.now(timezone.utc).isoformat()}",
f"endpoint: {endpoint}",
f"ip: {ip}",
f"user_agent: {user_agent}",
f"intent: {intent}",
f"takeaway: {takeaway}",
f"audience: {audience}",
f"chart_type: {chart_type}",
f"data: {json.dumps(data)}",
f"params: {json.dumps(params)}",
f"image_url: {image_url}",
]
log_content = "\n".join(lines)
blob_client = container_client.get_blob_client(log_name)
blob_client.upload_blob(
log_content,
overwrite=True,
content_settings=ContentSettings(content_type="text/plain"),
)
except Exception as e:
logging.error(f"Log upload failed: {e}")
# ---------------------------------------------------------------------------
# Shared chart generation logic
# ---------------------------------------------------------------------------
def _generate_chart(chart_type: str, data: dict, params: dict) -> tuple[str, str]:
"""Generate a chart and upload to blob. Returns (url, blob_id)."""
if chart_type not in SUPPORTED_CHARTS:
raise ValueError(f"Unsupported chart_type '{chart_type}'. Supported: {SUPPORTED_CHARTS}")
title = params.get("title", "")
xlabel = params.get("xlabel", "")
ylabel = params.get("ylabel", "")
figsize_w = params.get("figsize_w", 8)
figsize_h = params.get("figsize_h", 6)
dpi = params.get("dpi", 150)
grid = params.get("grid", False)
title_fontsize = params.get("title_fontsize", 14)
label_fontsize = params.get("label_fontsize", 12)
_apply_style(params)
fig, ax = plt.subplots(figsize=(figsize_w, figsize_h))
DRAW_FUNCTIONS[chart_type](ax, data, params)
if title:
ax.set_title(title, fontsize=title_fontsize)
if xlabel:
ax.set_xlabel(xlabel, fontsize=label_fontsize)
if ylabel:
ax.set_ylabel(ylabel, fontsize=label_fontsize)
if grid:
ax.grid(True, alpha=0.3)
if params.get("xscale"):
ax.set_xscale(params["xscale"])
if params.get("yscale"):
ax.set_yscale(params["yscale"])
if params.get("xlim"):
ax.set_xlim(params["xlim"])
if params.get("ylim"):
ax.set_ylim(params["ylim"])
ax2 = fig.axes[1] if len(fig.axes) > 1 else None
if ax2 is not None:
ylabel_sec = params.get("ylabel_secondary")
if ylabel_sec:
ax2.set_ylabel(ylabel_sec, fontsize=label_fontsize)
if params.get("yscale_secondary"):
ax2.set_yscale(params["yscale_secondary"])
if params.get("ylim_secondary"):
ax2.set_ylim(params["ylim_secondary"])
_apply_annotations(ax, params)
fig.tight_layout()
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=dpi)
plt.close(fig)
buf.seek(0)
url, blob_id = _upload_to_blob(buf.getvalue(), BLOB_CONN_STR, BLOB_CONTAINER)
return url, blob_id
# ---------------------------------------------------------------------------
# HTTP trigger (REST API) — POST /api/chart
# ---------------------------------------------------------------------------
@app.route(route="chart", methods=["POST"])
def chart(req: func.HttpRequest) -> func.HttpResponse:
logging.info("Chart generation request received.")
try:
body = req.get_json()
except ValueError:
return func.HttpResponse(
json.dumps({"error": "Invalid JSON body"}),
status_code=400,
mimetype="application/json",
)
intent = body.get("intent")
takeaway = body.get("takeaway")
audience = body.get("audience")
chart_type = body.get("chart_type")
data = body.get("data")
params = body.get("params")
missing = [f for f, v in [
("intent", intent), ("takeaway", takeaway), ("audience", audience),
("chart_type", chart_type), ("data", data), ("params", params),
] if not v]
if missing:
return func.HttpResponse(
json.dumps({"error": f"Missing or empty required fields: {', '.join(missing)}"}),
status_code=400,
mimetype="application/json",
)
try:
url, blob_id = _generate_chart(chart_type, data, params)
except Exception as e:
logging.error(f"Chart generation failed: {e}")
return func.HttpResponse(
json.dumps({"error": str(e)}),
status_code=500,
mimetype="application/json",
)
_upload_log(
blob_id=blob_id,
connection_string=BLOB_CONN_STR,
container_name=BLOB_CONTAINER,
endpoint="REST",
chart_type=chart_type,
data=data,
params=params,
image_url=url,
ip=req.headers.get("X-Forwarded-For", req.headers.get("REMOTE_ADDR", "")),
user_agent=req.headers.get("User-Agent", ""),
intent=intent,
takeaway=takeaway,
audience=audience,
)
return func.HttpResponse(
json.dumps({"url": url}),
status_code=200,
mimetype="application/json",
)
# ---------------------------------------------------------------------------
# MCP tool trigger — available at /runtime/webhooks/mcp
# ---------------------------------------------------------------------------
MCP_TOOL_PROPERTIES = json.dumps([
{
"propertyName": "intent",
"propertyType": "string",
"description": (
"REQUIRED reasoning note (for you, not the server). The specific analytical question or "
"decision this chart supports. One sentence. Avoid generic phrasing like \"visualize data\" "
"or \"show trends\" — if you can't state a specific question, you probably shouldn't be "
"making this chart. Example: \"Identify which regions missed Q1 revenue target so "
"leadership knows where to focus.\" Writing this first forces you to clarify what the chart "
"is really for, which leads to sharper chart_type and annotation choices below."
),
"isRequired": True,
},
{
"propertyName": "takeaway",
"propertyType": "string",
"description": (
"REQUIRED reasoning note (for you, not the server). The single-sentence headline conclusion "
"the viewer should reach, phrased as a statement of fact. Write it like a news headline. "
"Example: \"North America drove +18% growth while EMEA declined 4%.\" "
"USE THIS DIRECTLY to drive later fields: (1) pick the chart_type that best supports this "
"statement (a takeaway about a trend needs a line; about a peak needs a line or bar with a "
"point annotation; about composition needs a pie or stacked bar); (2) pick annotations that "
"make the takeaway visually unavoidable — if the takeaway is \"peaked in March\", add a "
"point annotation on March labeled \"Peak\"; if it's \"exceeded target\", add an hline at "
"the target and a point annotation on the data crossing it. A chart whose annotations "
"don't obviously support the takeaway has probably been poorly parameterized."
),
"isRequired": True,
},
{
"propertyName": "audience",
"propertyType": "string",
"description": (
"REQUIRED reasoning note (for you, not the server). Who will read this. Examples: "
"\"CFO in weekly review\", \"on-call engineer debugging a latency spike\", "
"\"slide 4 of board deck\", \"analyst exploring a dataset\". "
"USE THIS DIRECTLY to drive params: an executive audience needs a clean style "
"(seaborn-v0_8 or fivethirtyeight), large title/label fonts, minimal grid, few series, "
"short labels; a technical analyst can handle denser charts (ggplot, grid on, many series, "
"log scales when relevant); a print/grayscale audience needs the grayscale style with "
"markers/linestyles distinguishing series rather than color. The server does NOT apply "
"any audience-based defaults — you own every param choice explicitly."
),
"isRequired": True,
},
{
"propertyName": "chart_type",
"propertyType": "string",
"description": (
"One of: bar, line, pie, scatter, histogram, area, box, violin, heatmap. "
"Pick the type that best supports your takeaway — bar for category comparison, "
"line for trends over time, pie for parts of a whole, scatter for two-variable "
"relationships, histogram for distribution of one variable, area for cumulative/filled "
"trends, box/violin for distribution across groups, heatmap for a 2D matrix of values. "
"If two chart types could work, prefer the one that makes the takeaway visually clearer."
),
"isRequired": True,
},
{
"propertyName": "data",
"propertyType": "string",
"description": (
"JSON string with the data to plot. Shape depends on chart_type. Examples below are pasteable.\n"
"Single-series:\n"
" bar/pie: {\"labels\":[\"A\",\"B\",\"C\"],\"values\":[10,20,15]}\n"
" line/scatter/area: {\"x\":[1,2,3],\"y\":[10,20,30]}\n"
" histogram: {\"values\":[1,2,2,3,3,3,4,5]}\n"
" box/violin: {\"labels\":[\"A\",\"B\"],\"values\":[[1,2,3,4],[2,3,4,5,6]]} (outer list = groups, each inner list = that group's observations)\n"
" heatmap: {\"matrix\":[[1,2,3],[4,5,6]],\"xlabels\":[\"c1\",\"c2\",\"c3\"],\"ylabels\":[\"r1\",\"r2\"]}\n"
"Multi-series (all except pie/heatmap) — use a \"series\" array, each item with name/color plus the type-appropriate values:\n"
" bar: {\"labels\":[\"Q1\",\"Q2\"],\"series\":[{\"name\":\"North\",\"values\":[10,20],\"color\":\"steelblue\"},{\"name\":\"South\",\"values\":[15,25],\"color\":\"coral\"}]}\n"
" line/scatter/area: {\"series\":[{\"name\":\"2024\",\"x\":[1,2,3],\"y\":[10,20,30],\"marker\":\"o\"},{\"name\":\"2025\",\"x\":[1,2,3],\"y\":[15,25,35]}]}\n"
" box/violin: {\"series\":[{\"name\":\"A\",\"values\":[1,2,3,4]},{\"name\":\"B\",\"values\":[2,3,4,5]}]}\n"
"Error bars (bar/line) — add \"yerr\" or \"xerr\" arrays, top-level for single-series or per series for multi-series:\n"
" single: {\"x\":[1,2,3],\"y\":[10,20,30],\"yerr\":[1,2,1.5]}\n"
" multi: {\"labels\":[\"Q1\",\"Q2\"],\"series\":[{\"name\":\"A\",\"values\":[10,20],\"yerr\":[1,2]}]}\n"
"Dual y-axes (line/scatter/bar only) — add \"axis\":\"secondary\" to a series to route it to "
"the right-hand y-axis. Only use this when series have genuinely different units or magnitudes "
"(e.g. revenue in USD vs. conversion rate in %) that would make one flatline on a shared axis. "
"Do NOT use dual axes to fit two same-unit series — that misleads the viewer. Example:\n"
" {\"x\":[\"Jan\",\"Feb\",\"Mar\"],\"series\":[{\"name\":\"Revenue\",\"y\":[100,120,140],\"color\":\"steelblue\"},{\"name\":\"Conversion %\",\"y\":[2.1,2.4,2.6],\"color\":\"coral\",\"axis\":\"secondary\"}]}"
),
"isRequired": True,
},
{
"propertyName": "params",
"propertyType": "string",
"description": (
"REQUIRED JSON string for styling and annotations. Must be a non-empty object — "
"at minimum set \"title\" (matching your takeaway) and \"style\" (matching your audience). "
"Style choices should reflect your audience (executive = clean/large fonts/minimal grid; "
"analyst = ggplot/grid/dense; print = grayscale). "
"Use a specific title that matches your takeaway — \"Revenue by region\" is weak, "
"\"North America led Q1 growth\" is strong. Annotations (see below) should make the takeaway "
"visually unavoidable — a chart with a strong takeaway but no supporting annotations is "
"missing the point.\n"
"Typical well-formed params (title matches takeaway, style matches audience, annotations reinforce takeaway):\n"
" {\"title\":\"Revenue peaked in March before flattening\",\"xlabel\":\"Month\",\"ylabel\":\"Revenue (USD)\","
"\"style\":\"ggplot\",\"grid\":true,\"annotations\":["
"{\"type\":\"point\",\"x\":3,\"y\":150,\"text\":\"Peak\",\"arrow\":true,\"color\":\"red\"},"
"{\"type\":\"hline\",\"y\":100,\"text\":\"Target\",\"color\":\"gray\",\"linestyle\":\"--\"}]}\n"
"Available keys by group:\n"
"Titles/axes: title, xlabel, ylabel, title_fontsize, label_fontsize.\n"
"Theme/grid: style (default/ggplot/seaborn-v0_8/dark_background/fivethirtyeight/bmh/grayscale), grid (bool).\n"
"Figure: figsize_w, figsize_h, dpi.\n"
"Scale/limits: xscale/yscale (\"linear\"|\"log\"|\"symlog\"), xlim/ylim (2-element arrays).\n"
"Dual y-axes (when any series has \"axis\":\"secondary\"): ylabel_secondary, "
"yscale_secondary (\"linear\"|\"log\"|\"symlog\"), ylim_secondary (2-element array). "
"The server auto-colors the right axis's ticks and label to match the first secondary series' color.\n"
"Color (single-series): color, colors (pie), marker (line/scatter).\n"
"Bar: orientation (\"v\"|\"h\"), stacked (bool), bar_width.\n"
"Area: stacked (bool), alpha.\n"
"Histogram: bins.\n"
"Pie: autopct.\n"
"Violin: show_means, show_medians.\n"
"Heatmap: cmap (viridis/plasma/coolwarm/...), annotate (bool).\n"
"Annotations: \"annotations\" is an array of typed items drawn on top of the chart. "
"Use them to make your takeaway visually unavoidable — each annotation should exist "
"because it directly supports the one-sentence conclusion you wrote in takeaway above. "
"If you can't say \"this annotation supports the takeaway because...\", drop it.\n"
" point: {\"type\":\"point\",\"x\":<x>,\"y\":<y>,\"text\":\"Peak\",\"arrow\":true,\"color\":\"red\"} — callout with optional arrow.\n"
" hline: {\"type\":\"hline\",\"y\":<y>,\"text\":\"Target\",\"color\":\"red\",\"linestyle\":\"--\"} — horizontal reference line.\n"
" vline: {\"type\":\"vline\",\"x\":<x>,\"text\":\"Launch\",\"color\":\"green\"} — vertical event line.\n"
" hspan: {\"type\":\"hspan\",\"ymin\":<lo>,\"ymax\":<hi>,\"text\":\"SLA band\",\"color\":\"gray\",\"alpha\":0.2} — shaded y-range.\n"
" vspan: {\"type\":\"vspan\",\"xmin\":<lo>,\"xmax\":<hi>,\"text\":\"Outage\",\"color\":\"yellow\"} — shaded x-range.\n"
" text: {\"type\":\"text\",\"x\":<x>,\"y\":<y>,\"text\":\"Note\"} — free-placed text.\n"
"Coordinates are in data space (e.g. for bar charts with labels ['A','B','C'], x=1 means 'B')."
),
"isRequired": True,
},
])
@app.mcp_tool_trigger(
arg_name="context",
tool_name="generate_chart",
description=(
"Generates a matplotlib chart image and returns a public URL to the PNG. "
"WORKFLOW: before picking chart_type/data/params/annotations, first articulate three things — "
"intent (why this chart exists), takeaway (the one-sentence conclusion the viewer should reach), "
"and audience (who will read it). Then use those notes to drive every later choice: "
"pick the chart_type that best supports the takeaway, set params (fonts, density, style) "
"appropriate for the audience, and add annotations (arrows, reference lines, shaded regions) "
"that make the takeaway visually unavoidable. The server does not post-process your choices based "
"on intent/takeaway/audience — they exist so YOU reason well. "
"Supports chart types: bar, line, pie, scatter, histogram, area, box, violin, heatmap. "
"Features: multi-series (not pie/heatmap); dual y-axes (line/scatter/bar) for comparing series "
"with different units; error bars (bar/line); stacked variants (bar/area); "
"horizontal orientation (bar); log scales; axis limits; "
"six annotation types (point, hline, vline, hspan, vspan, text)."
),
tool_properties=MCP_TOOL_PROPERTIES,
)
def generate_chart_mcp(context) -> str:
content = json.loads(context)
args = content.get("arguments", {})
intent = args.get("intent", "")
takeaway = args.get("takeaway", "")
audience = args.get("audience", "")
chart_type = args.get("chart_type", "")
data_raw = args.get("data", "")
params_raw = args.get("params", "")
data = json.loads(data_raw) if isinstance(data_raw, str) and data_raw else data_raw or {}
params = json.loads(params_raw) if isinstance(params_raw, str) and params_raw else params_raw or {}
missing = [f for f, v in [
("intent", intent), ("takeaway", takeaway), ("audience", audience),
("chart_type", chart_type), ("data", data), ("params", params),
] if not v]
if missing:
return json.dumps({"error": f"Missing or empty required fields: {', '.join(missing)}"})
try:
url, blob_id = _generate_chart(chart_type, data, params)
except Exception as e:
logging.error(f"MCP chart generation failed: {e}")
return json.dumps({"error": str(e)})
_upload_log(
blob_id=blob_id,
connection_string=BLOB_CONN_STR,
container_name=BLOB_CONTAINER,
endpoint="MCP",
chart_type=chart_type,
data=data,
params=params,
image_url=url,
intent=intent,
takeaway=takeaway,
audience=audience,
)
return json.dumps({"url": url})