Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Source lives in `src/mcp_server_appwrite/`:
| `context.py` | `appwrite_get_context` — workspace summary (project, services, account/org for OAuth, a focused project's environments). |
| `headers.py` | Per-call request headers: `X-Appwrite-Environment` (a project environment, next to the project's ID) and `X-Appwrite-Reason` (why a write is made, validated and percent-encoded as Appwrite expects). |
| `confirmation.py` | Asks the user, through MCP elicitation, to approve deletes and paid writes (`PAID_TOOLS`) on 2026-07-28 clients that declare form elicitation: an `InputRequiredResult` first, the write on the accepted retry. Other clients keep `confirm_write` alone. |
| `charts.py` | Turns the usage time series a read returns (`usage_list_events`/`usage_list_gauges`, `*_get_usage`) into a Prometheus matrix in `structuredContent`, which Claude Code charts under the result. The text stays as Appwrite sent it. |
| `redaction.py` | Redacts the response fields Appwrite's spec marks `format: password` (carried on Console SDK model fields) from tool results, leaving a fingerprint, unless a call sets `reveal_secrets`. |
| `docs_search.py` | In-process semantic docs search (`appwrite_search_docs`) over a prebuilt index. |
| `docs_server.py` | The public docs MCP server at `/docs/mcp`: `appwrite_search_docs` only, no sign-in. |
Expand Down
108 changes: 108 additions & 0 deletions src/mcp_server_appwrite/charts.py
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
Comment thread
ChiragAgg5k marked this conversation as resolved.
Resolved


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)
18 changes: 12 additions & 6 deletions src/mcp_server_appwrite/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
from collections import OrderedDict
from dataclasses import dataclass
from difflib import get_close_matches
from typing import Any, Callable
from typing import Any, Callable, cast
from urllib.parse import urlparse
from uuid import uuid4

import mcp.types as types
from mcp.server.lowlevel.helper_types import ReadResourceContents

from . import telemetry
from . import charts, telemetry
from .apps import resource as view_resource
from .apps.views import Views
from .constants import (
Expand Down Expand Up @@ -654,22 +654,28 @@ def _search_tools(self, arguments: dict[str, Any]) -> list[ToolContent]:

return [types.TextContent(type="text", text="\n".join(lines))]

def _call_read_tool(self, raw_arguments: dict[str, Any]) -> list[ToolContent]:
def _call_read_tool(self, raw_arguments: dict[str, Any]) -> ToolOutput:
return self._call_hidden_tool(raw_arguments, write=False)

def _call_write_tool(self, raw_arguments: dict[str, Any]) -> list[ToolContent]:
def _call_write_tool(self, raw_arguments: dict[str, Any]) -> ToolOutput:
return self._call_hidden_tool(raw_arguments, write=True)

def _call_hidden_tool(
self, raw_arguments: dict[str, Any], *, write: bool
) -> list[ToolContent]:
) -> ToolOutput:
tool_name = raw_arguments.get("tool_name", raw_arguments.get("toolName"))
content = self._run_hidden_tool(raw_arguments, write)
# Read before a long result is cut to a preview, so the chart has every point.
series = None if write else charts.matrix(content)
content = self._preview_or_store_result(str(tool_name), content)
warning = self._zero.warning() if self._zero is not None else None
if warning:
content = [*content, types.TextContent(type="text", text=warning)]
return content
if series is None:
return content
return types.CallToolResult(
content=cast(list[types.ContentBlock], content), structured_content=series
)

def _run_view_tool(
self, raw_arguments: dict[str, Any], write: bool
Expand Down
17 changes: 17 additions & 0 deletions tests/e2e/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -1511,6 +1511,23 @@ def need(scope: str) -> None:
for metric in metrics
],
}
if path == "/v1/users/usage" and method == "GET":
need("users.read")

def points(metric: str) -> list[dict[str, Any]]:
return [
{"value": value, "date": time}
for time, value in sorted(project.usage.get(metric, {}).items())
]

users, sessions = points("users"), points("sessions")
return 200, {
"range": (query.get("range") or ["30d"])[0],
"usersTotal": users[-1]["value"] if users else 0,
"sessionsTotal": sum(each["value"] for each in sessions),
"users": users,
"sessions": sessions,
}
if match := re.fullmatch(r"/v1/functions/([^/]+)", path):
need("functions.read")
if match.group(1) not in project.functions:
Expand Down
37 changes: 37 additions & 0 deletions tests/e2e/test_apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -871,6 +871,43 @@ def test_usage_view_charts_a_range(self):
]
self.assertEqual(month["totals"]["requests"], 1_149)

# The same points read by the model come back as a Prometheus matrix too,
# which Claude Code charts under the result, in time order.
read = self.call(
"appwrite_call_tool",
{
"tool_name": "usage_list_events",
"project_id": PROJECT,
"arguments": {"metrics": ["network.requests", "executions"]},
},
)
self.assertFalse(read.get("isError"), read)
self.assertIn('"metric": "network.requests"', read["content"][0]["text"])
series = read["structuredContent"]
self.assertEqual(series["resultType"], "matrix")
requests, executions = series["result"]
self.assertEqual(requests["metric"], {"__name__": "network.requests"})
self.assertEqual([v for _, v in requests["values"]], ["999", "30", "120"])
times = [t for t, _ in requests["values"]]
self.assertEqual(times, sorted(times))
self.assertEqual(executions["values"][0][1], "4")
# A get_usage read charts each of its point lists.
users = self.call(
"appwrite_call_tool",
{"tool_name": "users_get_usage", "project_id": PROJECT},
)
self.assertFalse(users.get("isError"), users)
self.assertIn('"usersTotal"', users["content"][0]["text"])
(counted,) = users["structuredContent"]["result"]
self.assertEqual(counted["metric"], {"__name__": "users"})
self.assertEqual([v for _, v in counted["values"]], ["40", "42"])
# Reads without a time series carry no structured content.
plain = self.call(
"appwrite_call_tool", {"tool_name": "webhooks_list", "project_id": PROJECT}
)
self.assertFalse(plain.get("isError"), plain)
self.assertNotIn("structuredContent", plain)

# A range past the plan's history is Appwrite's own refusal.
cloud.fail("GET", r"/v1/usage/events", 402, "limit_history_exceeded")
refused = self.call("appwrite_show", {**show, "range": "30d"})
Expand Down
Loading