Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
b7e0e7c
feat(billing): refund/revocation webhooks + Polar ID tracking + MCP r…
Coding-Dev-Tools Jul 20, 2026
f93128a
merge: resolve all conflicts with origin/main
Coding-Dev-Tools Jul 20, 2026
847d447
fix(billing): restore _polar_order_id body after merge resolution
Coding-Dev-Tools Jul 20, 2026
f4336be
fix: remove blanket member gate (per-tool roles), reject trialing in …
Coding-Dev-Tools Jul 20, 2026
6391c14
fix(lint): remove duplicate function definitions (ruff F811) + fix tr…
Jul 20, 2026
e16e1d3
fix(lint): remove duplicate revoke_by_subscription/revoke_by_order (r…
Jul 20, 2026
62b6f4f
test: add invite_url to team-invite test payloads + missing-invite_ur…
Coding-Dev-Tools Jul 20, 2026
2fac3d2
fix(lint): remove remaining duplicate definitions (ruff F811)
Coding-Dev-Tools Jul 20, 2026
feb808e
fix(mcp): restore engraphis_answer tool registration
Coding-Dev-Tools Jul 20, 2026
7ba0ed6
fix: make invite_url required in team-invite endpoint (test_team_invi…
Coding-Dev-Tools Jul 20, 2026
e8e5516
test: add invite_url to all team-invite test payloads (server now req…
Coding-Dev-Tools Jul 20, 2026
d36b3f9
merge: resolve invite_url error-message conflict + add invite_url to …
Coding-Dev-Tools Jul 20, 2026
921c5c9
test: add invite_url to remaining team-invite payloads (non-team, rev…
Coding-Dev-Tools Jul 20, 2026
dbd14d4
fix(billing,mcp): address Codex review — claim_webhook 3-state, order…
Coding-Dev-Tools Jul 20, 2026
6bf3811
fix(merge): deduplicate colliding live edges in merge_workspaces + in…
Coding-Dev-Tools Jul 20, 2026
12cd334
fix(service): relabel expired collision edge to target workspace on m…
Coding-Dev-Tools Jul 20, 2026
d4cdb15
fix(lint): resolve E501 line-too-long in test_workspace_ops.py (ruff)
Coding-Dev-Tools Jul 20, 2026
8fc4fcd
fix(merge): merge survivor provenance with transferred edge supports
Jul 21, 2026
a146ca7
Merge remote-tracking branch 'origin/main' into feat/agent-connect-re…
Coding-Dev-Tools Jul 21, 2026
a8ba7a3
fix(tests): remove duplicate test_merge_deduplicates_colliding_live_e…
Coding-Dev-Tools Jul 21, 2026
8343352
Merge branch 'main' into feat/agent-connect-refund-revoke
Coding-Dev-Tools Jul 21, 2026
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
115 changes: 112 additions & 3 deletions engraphis/billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,30 @@ def _finalize_webhook(delivery_id: str, fulfillment_id: str,
finally:
conn.close()

def _polar_subscription_id(data: dict, *, object_is_subscription: bool = False) -> str:
"""Extract a Polar subscription id from direct or nested event data."""
from engraphis.inspector.webhooks import _extract_subscription_id
sub_id = _extract_subscription_id(data, object_is_subscription=object_is_subscription)
if sub_id:
return sub_id
order = data.get("order") or {}
if isinstance(order, dict):
return _extract_subscription_id(order)
return ""


def _polar_order_id(data: dict) -> str:
"""Extract a Polar order id from direct or nested event data."""
from engraphis.inspector.webhooks import _extract_order_id
order_id = _extract_order_id(data)
if order_id:
return order_id
order = data.get("order") or {}
if isinstance(order, dict):
return _extract_order_id(order)
return ""


def _release_claims(*claim_ids: str) -> None:
"""Best-effort rollback used only while returning a retryable failure."""
for claim_id in claim_ids:
Expand Down Expand Up @@ -485,6 +509,74 @@ def _order_id(data: dict) -> str:
return ""


def _revoke_refunded_order(data: dict, webhook_id: str) -> JSONResponse:
"""Refunds return the money, so revoke the affected key(s) immediately."""
subscription_id = _polar_subscription_id(data)
order_id = _polar_order_id(data)
if not subscription_id and not order_id:
return JSONResponse({"status": "ignored", "reason": "missing refund target",
"type": "order.refunded"}, status_code=202)

delivery_claim = "dlv:" + webhook_id
claim_state = claim_webhook(delivery_claim)
if claim_state == "fulfilled":
logger.info("polar webhook: duplicate refund delivery %s ignored", webhook_id)
return JSONResponse({"status": "duplicate", "revoked": 0}, status_code=202)
if claim_state == "in_flight":
return JSONResponse({"status": "processing", "revoked": 0}, status_code=503)

try:
from engraphis.inspector.license_registry import (
revoke_by_order, revoke_by_subscription)
if order_id:
revoked = revoke_by_order(order_id)
target = {"order_id": order_id}
else:
revoked = revoke_by_subscription(subscription_id)
target = {"subscription_id": subscription_id}
except Exception: # noqa: BLE001 — force Polar to retry if durable revoke failed
release_webhook(delivery_claim)
logger.exception("polar webhook: refund revocation failed")
return JSONResponse({"error": "revocation failed"}, status_code=503)

complete_webhook(delivery_claim)
logger.warning("polar webhook: refund revoked %d license key(s) for %s",
revoked, target)
return JSONResponse({"status": "revoked", "reason": "refund",
"revoked": revoked, **target}, status_code=202)
Comment on lines +543 to +546

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Complete successful revocation claims

The successful path returns without calling complete_webhook(delivery_claim), leaving every handled refund in the durable processing state. Once its lease expires, webhook_backlog_healthy() reports a stuck Polar delivery and vendor_readiness() becomes unhealthy; a later duplicate can also be reclaimed and reprocessed instead of recognized as fulfilled. Finalize the claim before returning 202.

Useful? React with 👍 / 👎.



def _revoke_subscription_event(data: dict, webhook_id: str, *,
reason: str) -> JSONResponse:
"""Definitive subscription revocation: access should end now, not at expiry."""
subscription_id = _polar_subscription_id(data, object_is_subscription=True)
if not subscription_id:
return JSONResponse({"status": "ignored", "reason": "missing subscription id",
"type": "subscription.revoked"}, status_code=202)

delivery_claim = "dlv:" + webhook_id
claim_state = claim_webhook(delivery_claim)
if claim_state == "fulfilled":
logger.info("polar webhook: duplicate revocation delivery %s ignored", webhook_id)
return JSONResponse({"status": "duplicate", "revoked": 0}, status_code=202)
if claim_state == "in_flight":
return JSONResponse({"status": "processing", "revoked": 0}, status_code=503)

try:
from engraphis.inspector.license_registry import revoke_by_subscription
revoked = revoke_by_subscription(subscription_id)
except Exception: # noqa: BLE001 — force Polar to retry if durable revoke failed
release_webhook(delivery_claim)
logger.exception("polar webhook: subscription revocation failed")
return JSONResponse({"error": "revocation failed"}, status_code=503)

complete_webhook(delivery_claim)
logger.warning("polar webhook: %s revoked %d license key(s) for subscription %s",
reason, revoked, subscription_id)
return JSONResponse({"status": "revoked", "reason": reason, "revoked": revoked,
"subscription_id": subscription_id}, status_code=202)


def _event_modified_at(data: dict) -> Optional[float]:
"""Epoch of the event object's own last-modification time, if the payload carries
one (Polar sends ``modified_at`` on Subscription objects). Used to reject an
Expand Down Expand Up @@ -758,16 +850,30 @@ async def polar_webhook(request: Request):
# ONE key per order and ONE per trial, no matter which/how many events fire:
# order.paid -> paid activation, trial conversion, and each renewal
# (a fresh order.paid per cycle). Fulfillment "order:<id>".
# order.refunded -> immediate revocation. Money returned means the key is
# returned too.
# subscription.canceled -> no revocation. The customer paid for the current period;
# the signed key expiry remains the entitlement boundary.
# subscription.revoked -> immediate revocation after the paid period actually ends
# or on merchant/admin immediate revocation.
# subscription.created -> ONLY when the subscription is in a free trial, to grant
# an immediate trial-length key. Fulfillment "trial:<sub id>".
# subscription.updated -> Team seat count changed mid-cycle (add/remove seats via
# the Customer Portal). Only when status is active AND the
# seat count actually differs from the last known baseline
# for this subscription (see get_known_seats /
# the Customer Portal). Only when status is active/trialing
# AND the seat count actually differs from the last known
# baseline for this subscription (see get_known_seats /
# record_known_seats) — trialing updates wait for payment,
# and unrelated updates cannot spam replacement keys.
# A non-trial subscription.created is a no-op: its paid key comes from order.paid, so
# a canceled trial can never keep Pro — the short trial key just expires.
if event_type == "order.refunded":
return _revoke_refunded_order(data, webhook_id)
if event_type in ("subscription.canceled", "subscription.cancelled"):
return JSONResponse({"status": "ignored", "reason": "paid period honored",
"type": event_type}, status_code=202)
if event_type == "subscription.revoked":
return _revoke_subscription_event(data, webhook_id,
reason="subscription_revoked")
pending_seat_baseline = None # (sub_id, seats, event_ts); persisted after key issuance
seat_lock_claim = ""
if event_type == "order.paid":
Expand All @@ -792,6 +898,9 @@ async def polar_webhook(request: Request):
elif event_type == "subscription.updated":
status = event_status
sub_id = str(data.get("id") or "").strip()[:128]
if status == "revoked":
return _revoke_subscription_event(data, webhook_id,
reason="subscription_revoked")
if status != "active" or not sub_id:
return JSONResponse({"status": "ignored", "reason": "not an active "
"subscription", "type": event_type}, status_code=202)
Expand Down
6 changes: 4 additions & 2 deletions engraphis/dashboard_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,12 @@ def create_app() -> FastAPI:
# which is why a naive app.mount('/mcp', mcp.streamable_http_app()) raises
# 'Task group is not initialized'). The endpoint is built at '/' inside the sub-app
# so mounting under /mcp lines up (Starlette strips the mount prefix).
import importlib.util as _importlib_util
import contextlib as _contextlib
_mcp_asgi = None
_mcp_mgr = None
try:
if importlib.util.find_spec("mcp") is None:
if _importlib_util.find_spec("mcp") is None:
raise ImportError("the optional mcp package is not installed")
import engraphis.mcp_server as _mcp_mod
# The MCP session manager's run() is once-per-instance, but create_app() may be
Expand Down Expand Up @@ -149,7 +150,7 @@ async def _lifespan(app: FastAPI):
# dashboard; the machine-readable schema remains available behind the normal gate.
app = FastAPI(title="Engraphis Dashboard", docs_url=None, redoc_url=None,
openapi_url="/api/openapi.json", lifespan=_lifespan)
app.state.mcp_over_http = False
app.state.mcp_over_http = _mcp_asgi is not None

# Honour the advertised allow-list on the actual GA dashboard entrypoint. A
# wildcard can never carry browser credentials.
Expand Down Expand Up @@ -322,6 +323,7 @@ async def _auth_gate(request: Request, call_next):
# and authenticated with a per-user bearer token. Each MCP tool then enforces its
# own viewer/member/admin role while reusing the dashboard's shared MemoryService.
if path == "/mcp" or path.startswith("/mcp/"):

if not (team_enabled and auth_store is not None
and licensing.has_feature("team")):
return JSONResponse({"error": "a Team license is required to connect agents",
Expand Down
1 change: 0 additions & 1 deletion engraphis/inspector/webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,6 @@ def _extract_order_id(data: dict) -> str:
"""Normalized Polar order id from an order-shaped payload."""
return str(data.get("id") or data.get("order_id") or "").strip()[:128]


def _extract_product_name(data: dict) -> str:
product = data.get("product")
if not isinstance(product, dict):
Expand Down
2 changes: 0 additions & 2 deletions engraphis/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1136,8 +1136,6 @@ def engraphis_consolidate(
return _err(exc)




def main() -> None:
"""Console entry point (``engraphis-mcp``). Runs over stdio."""
mcp.run()
6 changes: 4 additions & 2 deletions engraphis/routes/v2_team.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,10 @@ class TokenReq(BaseModel):


def _enabled() -> bool:
return os.environ.get("ENGRAPHIS_TEAM_MODE", "1").strip().lower() not in (
"0", "false", "no", "off")
raw = os.environ.get("ENGRAPHIS_TEAM_MODE")
if raw is not None:
return raw.strip().lower() not in {"0", "false", "no", "off"}
return bool(settings.team_mode)


def _users_db_path(db_path: str) -> str:
Expand Down
10 changes: 10 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import os

import pytest
from engraphis import cloud_license, licensing
from engraphis.config import settings
from engraphis.inspector import license_registry

# A developer's real ENGRAPHIS_LICENSE_KEY — loaded into os.environ from a gitignored .env by
# engraphis.config's load_dotenv at the import above — must never leak a paid license into the
# hermetic suite: an active Team key flips inspector /api/* to auth-required and 401s every
# unauthenticated test. Strip it ONCE here at collection, before any test runs, so tests that
# need a key still set their own via monkeypatch.setenv (function-scoped, restored per test)
# without this clobbering them.
os.environ.pop("ENGRAPHIS_LICENSE_KEY", None)

# Opt the licensing module into honoring ENGRAPHIS_LICENSE_PUBKEY, which is otherwise
# dead in a shipped process. Set at import time so it covers both collection and
# execution. This is the ONLY place that flips the switch — production never imports
Expand Down
40 changes: 40 additions & 0 deletions tests/test_agent_connect_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
real socket needed). The dashboard app's lifespan must run (TestClient used as a context
manager) so the MCP session manager's task group initializes.
"""
import json
import time

import pytest
Expand Down Expand Up @@ -140,6 +141,28 @@ def test_mcp_requires_team_license_402(monkeypatch, tmp_path):
assert r.json()["feature"] == "team"



def test_mcp_viewer_token_can_initialize(monkeypatch, tmp_path):
with _client(monkeypatch, tmp_path, key=_team_key()) as c:
_setup_admin(c)
member = c.post("/api/auth/users", json={"email": "viewer@x.co", "name": "Viewer",
"password": "viewerpass1", "role": "member"}).json()["user"]
c.post("/api/auth/logout")
assert c.post("/api/auth/login", json={"email": "viewer@x.co",
"password": "viewerpass1"}).status_code == 200
token = _mint(c, label="viewer-agent")
c.post("/api/auth/logout")
c.post("/api/auth/login", json={"email": "admin@x.co",
"password": "supersecret1"})
assert c.post("/api/auth/users/update",
json={"user_id": member["id"], "role": "viewer"}).status_code == 200
c.cookies.clear()
r = c.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": _PROTO, "capabilities": {},
"clientInfo": {"name": "t", "version": "1"}}},
headers=_h(token))
assert r.status_code == 200

def test_mcp_rejects_unconfigured_host(monkeypatch, tmp_path):
with _client(monkeypatch, tmp_path, key=_team_key()) as c:
_setup_admin(c)
Expand Down Expand Up @@ -290,6 +313,23 @@ def test_mcp_write_shares_the_dashboard_store(monkeypatch, tmp_path):
assert any("MCP" in (m.get("content") or "")
for m in rec.json()["memories"])


def test_mcp_answer_returns_grounded_result(monkeypatch, tmp_path):
with _client(monkeypatch, tmp_path, key=_team_key()) as c:
_setup_admin(c)
token = _mint(c)
c.cookies.clear()
h = _init(c, token)
r = _rpc(c, h, "tools/call",
{"name": "engraphis_answer",
"arguments": {"query": "Which database does the team use?",
"workspace": "demo"}}, id=11)
assert "Postgres" in r.text
event = json.loads(r.text.split("data: ", 1)[1])
payload = json.loads(event["result"]["content"][0]["text"])
assert payload["grounded"] is True


def test_connect_info_reports_mcp_available(monkeypatch, tmp_path):
with _client(monkeypatch, tmp_path, key=_team_key()) as c:
_setup_admin(c)
Expand Down
Loading