Repository navigation
feat: chart usage reads in Claude Code #205
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+175
−6
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| """Usage time series as ``structuredContent`` that clients can chart. | ||
|
|
||
| Claude Code draws a chart under a tool result whose structured content is a | ||
| Prometheus range answer: ``{"resultType": "matrix", "result": [{"metric": | ||
| {labels}, "values": [[unix seconds, "value"], ...]}]}``. It does not recognise | ||
| Appwrite's own usage shapes, so a read that returns one also carries the same | ||
| points in that form. The text the model reads is left as Appwrite sent it. | ||
|
|
||
| Two Appwrite shapes hold time series: | ||
|
|
||
| - the usage service (``usage_list_events``, ``usage_list_gauges``): | ||
| ``{"metrics": [{"metric": name, "points": [{"time", "value", <dimension>...}]}]}``, | ||
| one series per metric and set of dimension values; | ||
| - the ``*_get_usage`` reads: ``{name: [{"date", "value"}], ...}``, one series | ||
| per list of points. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from datetime import datetime | ||
| from typing import Any | ||
|
|
||
| import mcp.types as types | ||
|
|
||
| Labels = tuple[tuple[str, str], ...] | ||
| Points = list[tuple[float, float]] | ||
|
|
||
|
|
||
| def matrix(content: list[Any]) -> dict[str, Any] | None: | ||
| """The time series in a hidden tool's JSON result as a Prometheus matrix, or | ||
| ``None`` when it holds none.""" | ||
| first = content[0] if content else None | ||
| if not isinstance(first, types.TextContent): | ||
| return None | ||
| try: | ||
| data = json.loads(first.text) | ||
| except ValueError: | ||
| return None | ||
| if not isinstance(data, dict): | ||
| return None | ||
| series = _events(data) if "metrics" in data else _usage(data) | ||
| if not series: | ||
| return None | ||
| return { | ||
| "resultType": "matrix", | ||
| "result": [ | ||
| { | ||
| "metric": dict(labels), | ||
| "values": [[time, _number(value)] for time, value in sorted(points)], | ||
| } | ||
| for labels, points in series.items() | ||
| ], | ||
| } | ||
|
|
||
|
|
||
| def _events(data: dict[str, Any]) -> dict[Labels, Points]: | ||
| series: dict[Labels, Points] = {} | ||
| metrics = data["metrics"] | ||
| if not isinstance(metrics, list): | ||
| return series | ||
| for metric in metrics: | ||
| if not isinstance(metric, dict) or not isinstance(metric.get("points"), list): | ||
| continue | ||
| for point in metric["points"]: | ||
| sample = _sample(point, "time") | ||
| if sample is None: | ||
| continue | ||
| dimensions = tuple( | ||
| sorted( | ||
| (key, str(value)) | ||
| for key, value in point.items() | ||
| if key not in ("time", "value") and value is not None | ||
| ) | ||
| ) | ||
| labels = (("__name__", str(metric.get("metric"))), *dimensions) | ||
| series.setdefault(labels, []).append(sample) | ||
| return series | ||
|
|
||
|
|
||
| def _usage(data: dict[str, Any]) -> dict[Labels, Points]: | ||
| series: dict[Labels, Points] = {} | ||
| for name, points in data.items(): | ||
| if not isinstance(points, list) or not points: | ||
| continue | ||
| samples = [_sample(point, "date") for point in points] | ||
| if all(sample is not None for sample in samples): | ||
| series[(("__name__", name),)] = [s for s in samples if s is not None] | ||
| return series | ||
|
|
||
|
|
||
| def _sample(point: Any, key: str) -> tuple[float, float] | None: | ||
| if not isinstance(point, dict): | ||
| return None | ||
| value = point.get("value") | ||
| if isinstance(value, bool) or not isinstance(value, (int, float)): | ||
| return None | ||
| try: | ||
| time = datetime.fromisoformat(str(point.get(key))) | ||
| except ValueError: | ||
| return None | ||
| if time.tzinfo is None: | ||
| return None | ||
| return time.timestamp(), float(value) | ||
|
|
||
|
|
||
| def _number(value: float) -> str: | ||
| return str(int(value)) if value.is_integer() else str(value) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.