klaw-sync: Modern Treasury link (/mt/* proxy, /mt/sync snapshot; secrets via Space env; writes gated by MT_ALLOW_WRITES)
Browse files203 unmodified lines204205206203 unmodified lineshits.append({"id": c.get("id"), "doc": c.get("doc"), "url": c.get("url"), "model": c.get("model"), "text": c.get("text", "")[:600]})if len(hits) >= limit: breakreturn {"q": q, "hits": hits}203 unmodified lines204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300203 unmodified lineshits.append({"id": c.get("id"), "doc": c.get("doc"), "url": c.get("url"), "model": c.get("model"), "text": c.get("text", "")[:600]})if len(hits) >= limit: breakreturn {"q": q, "hits": hits}# ─────────────────────────────────────────────────────────────────────────────# MODERN TREASURY LINK — credentials live ONLY in Space secrets:# MT_ORG_ID (organization id) MT_API_KEY (API key) → HTTP Basic auth per MT docs# Base: https://app.moderntreasury.com/api (the key decides live vs sandbox)# Read endpoints are open to the Command Center (optionally gated by KLAW_WS_TOKEN);# write endpoints additionally require the Space secret MT_ALLOW_WRITES=true.# ─────────────────────────────────────────────────────────────────────────────import base64, uuidMT_BASE = "https://app.moderntreasury.com/api"MT_ORG = os.environ.get("MT_ORG_ID", ""); MT_KEY = os.environ.get("MT_API_KEY", "")MT_WRITES = os.environ.get("MT_ALLOW_WRITES", "false").lower() == "true"MT_READ_PATHS = {"internal_accounts", "external_accounts", "counterparties", "payment_orders", "expected_payments","ledger_accounts", "ledgers", "ledger_transactions", "transactions", "returns", "webhooks","connections", "virtual_accounts", "account_collection_flows", "invoices", "paper_items", "incoming_payment_details"}def _mt_headers(idem: str | None = None):if not (MT_ORG and MT_KEY): raise HTTPException(503, "Modern Treasury not linked: set MT_ORG_ID and MT_API_KEY as Space secrets")h = {"Authorization": "Basic " + base64.b64encode(f"{MT_ORG}:{MT_KEY}".encode()).decode(), "Accept": "application/json"}if idem: h["Idempotency-Key"] = idemreturn h@app.get("/mt/health")async def mt_health(token: str | None = None):_auth(token)if not (MT_ORG and MT_KEY): return {"linked": False, "reason": "MT_ORG_ID / MT_API_KEY not set in Space secrets"}async with httpx.AsyncClient(timeout=30) as c:r = await c.get(f"{MT_BASE}/internal_accounts", params={"per_page": 1}, headers=_mt_headers())return {"linked": r.status_code == 200, "status": r.status_code, "writes_enabled": MT_WRITES, "org_id_last4": MT_ORG[-4:]}@app.get("/mt/{resource}")async def mt_list(resource: str, request: Request, token: str | None = None):_auth(token)if resource not in MT_READ_PATHS: raise HTTPException(404, "unknown or non-readable MT resource")params = dict(request.query_params); params.pop("token", None); params.setdefault("per_page", "100")async with httpx.AsyncClient(timeout=60) as c:r = await c.get(f"{MT_BASE}/{resource}", params=params, headers=_mt_headers())body = r.json() if "json" in r.headers.get("content-type", "") else {"raw": r.text[:2000]}return JSONResponse({"resource": resource, "status": r.status_code, "data": body,"next_cursor": r.headers.get("X-After-Cursor"), "per_page": r.headers.get("X-Per-Page")}, status_code=200 if r.status_code < 500 else 502)@app.get("/mt/{resource}/{rid}")async def mt_get(resource: str, rid: str, token: str | None = None):_auth(token)if resource not in MT_READ_PATHS: raise HTTPException(404)async with httpx.AsyncClient(timeout=60) as c:r = await c.get(f"{MT_BASE}/{resource}/{rid}", headers=_mt_headers())return JSONResponse({"resource": resource, "status": r.status_code, "data": r.json()}, status_code=200 if r.status_code < 500 else 502)@app.post("/mt/sync")async def mt_sync(token: str | None = None):"""One call: pull everything the dashboard needs. Returns a normalized snapshot (also cached at /data/mt_snapshot.json)."""_auth(token)out = {"synced_at": time.time(), "resources": {}}async with httpx.AsyncClient(timeout=90) as c:for res in ["internal_accounts", "external_accounts", "counterparties", "payment_orders", "expected_payments", "ledger_accounts", "transactions", "returns", "webhooks", "connections", "virtual_accounts"]:items, cursor = [], Nonefor _ in range(10): # up to 1,000 rows per resourceparams = {"per_page": "100"};if cursor: params["after_cursor"] = cursorr = await c.get(f"{MT_BASE}/{res}", params=params, headers=_mt_headers())if r.status_code != 200: out["resources"][res] = {"error": r.status_code, "detail": r.text[:300]}; breakpage = r.json(); items += page if isinstance(page, list) else []cursor = r.headers.get("X-After-Cursor")if not cursor: breakelse: passif res not in out["resources"]: out["resources"][res] = {"count": len(items), "items": _scrub(items)}# normalized account view for the Treasury cardsaccts = []for a in out["resources"].get("internal_accounts", {}).get("items", []):accts.append({"id": a.get("id"), "name": a.get("name"), "party": a.get("party_name"), "currency": a.get("currency"),"account_type": a.get("account_type"), "connection": (a.get("connection") or {}).get("vendor_name"),"routing_last4": (next((d.get("routing_number","")[-4:] for d in a.get("routing_details", []) if d.get("routing_number")), None)),"account_last4": (next((d.get("account_number","")[-4:] for d in a.get("account_details", []) if d.get("account_number")), None)),"balances": a.get("balances") or {}})out["accounts"] = accts(DATA / "mt_snapshot.json").write_text(json.dumps(out))return out@app.get("/mt_snapshot")def mt_snapshot(token: str | None = None):_auth(token); p = DATA / "mt_snapshot.json"return json.loads(p.read_text()) if p.exists() else {"synced_at": None, "resources": {}, "accounts": []}@app.post("/mt/payment_orders")async def mt_create_payment_order(body: dict, token: str | None = None):"""Creates a real payment order. Disabled unless MT_ALLOW_WRITES=true in Space secrets. Idempotency-Key always sent."""_auth(token)if not MT_WRITES: raise HTTPException(403, "writes disabled: set MT_ALLOW_WRITES=true in Space secrets to enable real payment orders")idem = body.pop("idempotency_key", None) or str(uuid.uuid4())async with httpx.AsyncClient(timeout=60) as c:r = await c.post(f"{MT_BASE}/payment_orders", json=body, headers=_mt_headers(idem))return JSONResponse({"status": r.status_code, "idempotency_key": idem, "data": r.json() if "json" in r.headers.get("content-type","") else r.text[:1000]}, status_code=200 if r.status_code < 500 else 502)
app.py+94