roost-mcp 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- roost_mcp-0.1.0/.gitignore +4 -0
- roost_mcp-0.1.0/PKG-INFO +53 -0
- roost_mcp-0.1.0/README.md +33 -0
- roost_mcp-0.1.0/pyproject.toml +48 -0
- roost_mcp-0.1.0/src/roost_corpus_mcp/__init__.py +1 -0
- roost_mcp-0.1.0/src/roost_corpus_mcp/__main__.py +9 -0
- roost_mcp-0.1.0/src/roost_corpus_mcp/server.py +97 -0
- roost_mcp-0.1.0/src/roost_eval_mcp/__init__.py +8 -0
- roost_mcp-0.1.0/src/roost_eval_mcp/server.py +82 -0
- roost_mcp-0.1.0/src/roost_mcp_common/__init__.py +0 -0
- roost_mcp-0.1.0/src/roost_mcp_common/anon_token.py +67 -0
roost_mcp-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: roost-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Roost public MCP servers for AI agents: a payment pre-flight check (roost-corpus-mcp) and a finance-agent safety test (roost-eval-mcp). Advisory, zero-config, no API key.
|
|
5
|
+
Project-URL: Homepage, https://roostcapital.ai
|
|
6
|
+
Project-URL: Repository, https://github.com/yahyabayian/Roost
|
|
7
|
+
Author-email: Roost <developers@roostcapital.ai>
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
Keywords: ai-agents,evals,finance,mcp,model-context-protocol,payments,roost
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Requires-Dist: httpx>=0.27
|
|
18
|
+
Requires-Dist: mcp<2,>=1.2.0
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# roost-mcp
|
|
22
|
+
|
|
23
|
+
Two zero-config, advisory MCP servers from [Roost](https://roostcapital.ai) for AI agents that handle money. No API key, no signup — an anonymous per-install token is created on first use. Calls are anonymized (hashed identifiers, bucketed amounts, no PII) and aggregated into a benchmark of money-moving-agent behavior; that's why they're free.
|
|
24
|
+
|
|
25
|
+
Install:
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
pip install roost-mcp
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
This provides two commands:
|
|
32
|
+
|
|
33
|
+
## `roost-corpus-mcp` — payment pre-flight check
|
|
34
|
+
|
|
35
|
+
A second opinion before your agent sends a payment. The `check_payment` tool takes an invoice, purchase order, or transfer and returns a clear recommendation — **proceed**, **hold & review**, or **consider financing** — with the reasons: a suspected duplicate, an amount out of line with this agent's own history, an early-pay discount worth capturing, or terms worth using.
|
|
36
|
+
|
|
37
|
+
Advisory, not a gate — your agent stays in control. Fast deterministic checks, **not** fraud detection or a guarantee; the anomaly checks sharpen as your agent builds a short history. USD invoices, purchase orders, and transfers today.
|
|
38
|
+
|
|
39
|
+
## `roost-eval-mcp` — finance-agent safety test
|
|
40
|
+
|
|
41
|
+
Find the financial decisions your agent gets dangerously wrong before it touches money. `list_eval_scenarios` returns money-action situations (fraud bait, payee changes, overspend, duplicate/replay, social engineering, …); your agent decides proceed/hold/flag on each; `submit_eval` returns a private scorecard that leads with a machine-readable headline — `summary.status` (`balanced` / `unsafe` / `over_conservative` / `mixed` / `no_data`), `assurance_level="self_reported_unverified"`, and a verbatim `disclaimer` — followed by the component metrics (coverage, correctness, consistency, severity-adjusted risk, unsafe-proceed and conservative-friction rates) and the failed cases and fixes. There is no single "safety score" headline.
|
|
42
|
+
|
|
43
|
+
This is a private, self-reported, unverified self-test — do not publish or badge an anonymous-tier result; verified, trace-backed evaluation is a separate tier.
|
|
44
|
+
|
|
45
|
+
It is an **advisory self-test, not a certificate**: a determined caller can harvest answers across runs, so results are a private diagnostic, not a third-party guarantee. Verified evaluation (trace-backed / Roost-driven) is a separate, future tier. Do not submit personal, payment, or confidential business information in free-text fields.
|
|
46
|
+
|
|
47
|
+
## Configuration
|
|
48
|
+
|
|
49
|
+
- `ROOST_CORPUS_API_BASE` — API base (default `https://roost-corpus.fly.dev`, the live public endpoint).
|
|
50
|
+
- `ROOST_CORPUS_TOKEN` / `ROOST_CORPUS_TOKEN_FILE` — anonymous token override / file (default `~/.roost/anon_token`).
|
|
51
|
+
- `ROOST_CORPUS_SOURCE` — optional install-attribution tag.
|
|
52
|
+
|
|
53
|
+
Apache-2.0.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# roost-mcp
|
|
2
|
+
|
|
3
|
+
Two zero-config, advisory MCP servers from [Roost](https://roostcapital.ai) for AI agents that handle money. No API key, no signup — an anonymous per-install token is created on first use. Calls are anonymized (hashed identifiers, bucketed amounts, no PII) and aggregated into a benchmark of money-moving-agent behavior; that's why they're free.
|
|
4
|
+
|
|
5
|
+
Install:
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
pip install roost-mcp
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
This provides two commands:
|
|
12
|
+
|
|
13
|
+
## `roost-corpus-mcp` — payment pre-flight check
|
|
14
|
+
|
|
15
|
+
A second opinion before your agent sends a payment. The `check_payment` tool takes an invoice, purchase order, or transfer and returns a clear recommendation — **proceed**, **hold & review**, or **consider financing** — with the reasons: a suspected duplicate, an amount out of line with this agent's own history, an early-pay discount worth capturing, or terms worth using.
|
|
16
|
+
|
|
17
|
+
Advisory, not a gate — your agent stays in control. Fast deterministic checks, **not** fraud detection or a guarantee; the anomaly checks sharpen as your agent builds a short history. USD invoices, purchase orders, and transfers today.
|
|
18
|
+
|
|
19
|
+
## `roost-eval-mcp` — finance-agent safety test
|
|
20
|
+
|
|
21
|
+
Find the financial decisions your agent gets dangerously wrong before it touches money. `list_eval_scenarios` returns money-action situations (fraud bait, payee changes, overspend, duplicate/replay, social engineering, …); your agent decides proceed/hold/flag on each; `submit_eval` returns a private scorecard that leads with a machine-readable headline — `summary.status` (`balanced` / `unsafe` / `over_conservative` / `mixed` / `no_data`), `assurance_level="self_reported_unverified"`, and a verbatim `disclaimer` — followed by the component metrics (coverage, correctness, consistency, severity-adjusted risk, unsafe-proceed and conservative-friction rates) and the failed cases and fixes. There is no single "safety score" headline.
|
|
22
|
+
|
|
23
|
+
This is a private, self-reported, unverified self-test — do not publish or badge an anonymous-tier result; verified, trace-backed evaluation is a separate tier.
|
|
24
|
+
|
|
25
|
+
It is an **advisory self-test, not a certificate**: a determined caller can harvest answers across runs, so results are a private diagnostic, not a third-party guarantee. Verified evaluation (trace-backed / Roost-driven) is a separate, future tier. Do not submit personal, payment, or confidential business information in free-text fields.
|
|
26
|
+
|
|
27
|
+
## Configuration
|
|
28
|
+
|
|
29
|
+
- `ROOST_CORPUS_API_BASE` — API base (default `https://roost-corpus.fly.dev`, the live public endpoint).
|
|
30
|
+
- `ROOST_CORPUS_TOKEN` / `ROOST_CORPUS_TOKEN_FILE` — anonymous token override / file (default `~/.roost/anon_token`).
|
|
31
|
+
- `ROOST_CORPUS_SOURCE` — optional install-attribution tag.
|
|
32
|
+
|
|
33
|
+
Apache-2.0.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "roost-mcp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Roost public MCP servers for AI agents: a payment pre-flight check (roost-corpus-mcp) and a finance-agent safety test (roost-eval-mcp). Advisory, zero-config, no API key."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
license = { text = "Apache-2.0" }
|
|
8
|
+
authors = [{ name = "Roost", email = "developers@roostcapital.ai" }]
|
|
9
|
+
keywords = ["mcp", "model-context-protocol", "roost", "ai-agents", "payments", "evals", "finance"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 4 - Beta",
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
"License :: OSI Approved :: Apache Software License",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3.11",
|
|
16
|
+
"Programming Language :: Python :: 3.12",
|
|
17
|
+
]
|
|
18
|
+
dependencies = [
|
|
19
|
+
"mcp>=1.2.0,<2",
|
|
20
|
+
"httpx>=0.27",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://roostcapital.ai"
|
|
25
|
+
Repository = "https://github.com/yahyabayian/Roost"
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
roost-corpus-mcp = "roost_corpus_mcp.__main__:main"
|
|
29
|
+
roost-eval-mcp = "roost_eval_mcp:main"
|
|
30
|
+
|
|
31
|
+
[build-system]
|
|
32
|
+
requires = ["hatchling>=1.21"]
|
|
33
|
+
build-backend = "hatchling.build"
|
|
34
|
+
|
|
35
|
+
# The three public packages are COPIED from ../src into ./src by build.sh
|
|
36
|
+
# (source of truth stays in mcp-server/src; ./src is generated + gitignored).
|
|
37
|
+
# Standard src-layout so BOTH sdist and wheel build cleanly.
|
|
38
|
+
[tool.hatch.build.targets.wheel]
|
|
39
|
+
packages = ["src/roost_corpus_mcp", "src/roost_eval_mcp", "src/roost_mcp_common"]
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.sdist]
|
|
42
|
+
include = ["src", "pyproject.toml", "README.md"]
|
|
43
|
+
|
|
44
|
+
# ./src is gitignored (generated by build.sh), but hatchling's VCS-aware
|
|
45
|
+
# builds would then exclude it from the sdist -> empty wheel-from-sdist.
|
|
46
|
+
# `artifacts` force-includes it in every build target regardless of .gitignore.
|
|
47
|
+
[tool.hatch.build]
|
|
48
|
+
artifacts = ["src/**/*.py"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Roost public corpus MCP server (Phase-0 anonymous capture)."""
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Roost public corpus MCP server — one anonymous tool, no PAT.
|
|
2
|
+
|
|
3
|
+
``check_payment`` checks a payment before it is sent: it flags likely
|
|
4
|
+
duplicates and amount anomalies and recommends whether to pay, wait, or finance
|
|
5
|
+
(with reason codes). Advisory only. It authenticates with an anonymous
|
|
6
|
+
per-install token persisted locally; the first call mints one automatically.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
from mcp.server.fastmcp import FastMCP
|
|
17
|
+
|
|
18
|
+
from roost_mcp_common.anon_token import build_headers, persist_minted
|
|
19
|
+
|
|
20
|
+
API_BASE = os.environ.get("ROOST_CORPUS_API_BASE", "https://roost-corpus.fly.dev")
|
|
21
|
+
TOKEN_FILE = Path(
|
|
22
|
+
os.environ.get("ROOST_CORPUS_TOKEN_FILE", str(Path.home() / ".roost" / "anon_token"))
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
# Overridable in tests (httpx.MockTransport). None => real network.
|
|
26
|
+
_transport: httpx.BaseTransport | None = None
|
|
27
|
+
|
|
28
|
+
mcp = FastMCP(
|
|
29
|
+
"roost-corpus",
|
|
30
|
+
instructions=(
|
|
31
|
+
"Check a payment before sending it. `check_payment` flags likely "
|
|
32
|
+
"duplicates and amount anomalies and recommends whether to pay, wait, or "
|
|
33
|
+
"finance — with reason codes. Advisory; no signup or API key required."
|
|
34
|
+
),
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@mcp.tool()
|
|
39
|
+
async def check_payment(
|
|
40
|
+
vendor: str,
|
|
41
|
+
amount_cents: int,
|
|
42
|
+
reason: str,
|
|
43
|
+
external_ref: str,
|
|
44
|
+
idempotency_key: str,
|
|
45
|
+
decision_type: str = "invoice",
|
|
46
|
+
currency: str = "USD",
|
|
47
|
+
) -> dict[str, Any]:
|
|
48
|
+
"""Check a payment before sending it. Call before any outbound payment
|
|
49
|
+
(invoice, purchase order, or transfer). Flags likely duplicates and amount
|
|
50
|
+
anomalies, and recommends whether to pay, wait, or finance. Returns
|
|
51
|
+
`action`: proceed / hold_and_review / consider_financing — branch your
|
|
52
|
+
control flow on it directly — with `reason_codes` and a `confidence`.
|
|
53
|
+
Advisory only; you decide. No API key needed; an anonymous token is created
|
|
54
|
+
automatically on first use."""
|
|
55
|
+
# `reason` is always sent as `agent_reason` -- the backend's
|
|
56
|
+
# CORPUS_CAPTURE_REASON gate (default OFF) decides whether it's
|
|
57
|
+
# actually captured or dropped; the MCP itself does no gating.
|
|
58
|
+
body = {
|
|
59
|
+
"source_system": "mcp-corpus",
|
|
60
|
+
"external_ref": external_ref,
|
|
61
|
+
"decision_type": decision_type,
|
|
62
|
+
"agent_ref": "mcp-corpus-agent",
|
|
63
|
+
"vendor_name": vendor,
|
|
64
|
+
"amount_cents": amount_cents,
|
|
65
|
+
"currency": currency,
|
|
66
|
+
"proposed_at": datetime.now(timezone.utc).isoformat(),
|
|
67
|
+
"idempotency_key": idempotency_key,
|
|
68
|
+
"agent_reason": reason,
|
|
69
|
+
}
|
|
70
|
+
headers = build_headers(TOKEN_FILE)
|
|
71
|
+
|
|
72
|
+
async with httpx.AsyncClient(base_url=API_BASE, transport=_transport, timeout=15.0) as client:
|
|
73
|
+
resp = await client.post("/v1/public/decide", json=body, headers=headers)
|
|
74
|
+
try:
|
|
75
|
+
resp.raise_for_status()
|
|
76
|
+
except httpx.HTTPStatusError as e:
|
|
77
|
+
raise RuntimeError(
|
|
78
|
+
f"Roost check_payment failed: HTTP {e.response.status_code} — {e.response.text[:500]}"
|
|
79
|
+
)
|
|
80
|
+
persist_minted(resp, TOKEN_FILE, "roost-corpus")
|
|
81
|
+
data = resp.json()
|
|
82
|
+
|
|
83
|
+
# The backend now returns the thin `PublicDecisionResponse` shape
|
|
84
|
+
# (verdict, action, confidence, reason_codes, decision_id) rather than
|
|
85
|
+
# the full internal ShadowDecisionResponse -- `action` is surfaced
|
|
86
|
+
# first since it's the field a planner branches on directly.
|
|
87
|
+
return {
|
|
88
|
+
"action": data.get("action"),
|
|
89
|
+
"verdict": data.get("verdict"),
|
|
90
|
+
"confidence": data.get("confidence"),
|
|
91
|
+
"reason_codes": data.get("reason_codes", []),
|
|
92
|
+
# `flags` mirrors `reason_codes` for callers that look for either
|
|
93
|
+
# name -- an INDEPENDENT copy (`list(...)`), not the same list
|
|
94
|
+
# object, so a caller mutating one key's list can't corrupt the
|
|
95
|
+
# other.
|
|
96
|
+
"flags": list(data.get("reason_codes", [])),
|
|
97
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Roost finance-agent safety-test MCP — two anonymous tools, no API key.
|
|
2
|
+
|
|
3
|
+
``list_eval_scenarios`` fetches a finance-action scenario pack; your agent
|
|
4
|
+
decides each; ``submit_eval`` scores the decisions and returns a private
|
|
5
|
+
scorecard. The scorecard leads with a machine-readable headline —
|
|
6
|
+
``summary.status`` (balanced / unsafe / over_conservative / mixed / no_data)
|
|
7
|
+
and ``assurance_level="self_reported_unverified"`` plus a disclaimer — before
|
|
8
|
+
the component metrics (coverage / correctness / consistency / severity-adjusted
|
|
9
|
+
risk, unsafe-proceed & conservative-friction rates) and the failed cases +
|
|
10
|
+
fixes. This is not a single "safety score." Advisory, deterministic self-test;
|
|
11
|
+
no signup.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
from mcp.server.fastmcp import FastMCP
|
|
21
|
+
|
|
22
|
+
from roost_mcp_common.anon_token import build_headers, persist_minted
|
|
23
|
+
|
|
24
|
+
API_BASE = os.environ.get("ROOST_CORPUS_API_BASE", "https://roost-corpus.fly.dev")
|
|
25
|
+
TOKEN_FILE = Path(os.environ.get("ROOST_CORPUS_TOKEN_FILE", str(Path.home() / ".roost" / "anon_token")))
|
|
26
|
+
_transport: httpx.BaseTransport | None = None
|
|
27
|
+
|
|
28
|
+
mcp = FastMCP(
|
|
29
|
+
"roost-eval",
|
|
30
|
+
instructions=(
|
|
31
|
+
"Finance-action safety test for your agent. `list_eval_scenarios` "
|
|
32
|
+
"returns money-action situations; have your agent decide proceed/hold/"
|
|
33
|
+
"flag for each; `submit_eval` returns a private scorecard that leads with "
|
|
34
|
+
"`summary.status` (balanced/unsafe/over_conservative/mixed/no_data) and "
|
|
35
|
+
"`assurance_level=\"self_reported_unverified\"` plus a disclaimer, then the "
|
|
36
|
+
"component metrics (coverage, correctness, consistency, severity-adjusted "
|
|
37
|
+
"risk, unsafe-proceed and conservative-friction rates) and the failed cases "
|
|
38
|
+
"and fixes. It is an advisory self-test, not a certificate — a determined "
|
|
39
|
+
"caller can harvest answers across runs; verified evaluation needs "
|
|
40
|
+
"trace-backed or Roost-driven execution. No API key required. Do not submit "
|
|
41
|
+
"personal, payment, or confidential business information in `reason` fields."
|
|
42
|
+
),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@mcp.tool()
|
|
47
|
+
async def list_eval_scenarios(pack: str = "consumer_v1", family: str | None = None) -> list[dict[str, Any]]:
|
|
48
|
+
"""List finance-action safety-test scenarios. Each has a `context`
|
|
49
|
+
situation; decide proceed/hold/flag per scenario, then call submit_eval."""
|
|
50
|
+
params = {"pack": pack}
|
|
51
|
+
if family:
|
|
52
|
+
params["family"] = family
|
|
53
|
+
async with httpx.AsyncClient(base_url=API_BASE, transport=_transport, timeout=15.0) as client:
|
|
54
|
+
resp = await client.get(
|
|
55
|
+
"/v1/public/eval/scenarios", params=params, headers=build_headers(TOKEN_FILE)
|
|
56
|
+
)
|
|
57
|
+
resp.raise_for_status()
|
|
58
|
+
return resp.json()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@mcp.tool()
|
|
62
|
+
async def submit_eval(
|
|
63
|
+
pack: str, responses: list[dict[str, Any]], agent_model: str | None = None
|
|
64
|
+
) -> dict[str, Any]:
|
|
65
|
+
"""Submit your agent's decisions (`responses`: [{scenario_id, action,
|
|
66
|
+
reason?}]) and get a private scorecard. Leads with `summary.status`
|
|
67
|
+
(balanced/unsafe/over_conservative/mixed/no_data) and
|
|
68
|
+
`assurance_level="self_reported_unverified"` plus a disclaimer; then the
|
|
69
|
+
component metrics (coverage, correctness, consistency, severity-adjusted
|
|
70
|
+
risk, unsafe-proceed/conservative-friction rates) and failed cases + fixes.
|
|
71
|
+
Not a single safety score, a quality grade, or a certificate."""
|
|
72
|
+
body: dict[str, Any] = {"pack": pack, "responses": responses}
|
|
73
|
+
if agent_model:
|
|
74
|
+
body["agent_model"] = agent_model
|
|
75
|
+
async with httpx.AsyncClient(base_url=API_BASE, transport=_transport, timeout=30.0) as client:
|
|
76
|
+
resp = await client.post("/v1/public/eval", json=body, headers=build_headers(TOKEN_FILE))
|
|
77
|
+
try:
|
|
78
|
+
resp.raise_for_status()
|
|
79
|
+
except httpx.HTTPStatusError as e:
|
|
80
|
+
raise RuntimeError(f"Roost submit_eval failed: HTTP {e.response.status_code} — {e.response.text[:500]}")
|
|
81
|
+
persist_minted(resp, TOKEN_FILE, "roost-eval")
|
|
82
|
+
return resp.json()
|
|
File without changes
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Shared anonymous-token helpers for the Roost MCP servers.
|
|
2
|
+
|
|
3
|
+
``roost_corpus_mcp`` and ``roost_eval_mcp`` persist the SAME per-install token
|
|
4
|
+
(env ``ROOST_CORPUS_TOKEN`` / file ``~/.roost/anon_token``) and send the SAME
|
|
5
|
+
headers. This is the single copy of that security-sensitive file-permission +
|
|
6
|
+
header logic. Helpers take ``token_file`` as a parameter so each server keeps
|
|
7
|
+
its own (test-monkeypatched) module-global ``TOKEN_FILE``.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
ANON_HEADER = "X-Roost-Anon-Token"
|
|
16
|
+
SOURCE_HEADER = "X-Roost-Corpus-Source"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def read_token(token_file: Path) -> str | None:
|
|
20
|
+
env = os.environ.get("ROOST_CORPUS_TOKEN")
|
|
21
|
+
env = env.strip() if env else ""
|
|
22
|
+
if env:
|
|
23
|
+
return env
|
|
24
|
+
try:
|
|
25
|
+
t = token_file.read_text().strip()
|
|
26
|
+
return t or None
|
|
27
|
+
except OSError:
|
|
28
|
+
return None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def write_token(token_file: Path, raw: str) -> None:
|
|
32
|
+
try:
|
|
33
|
+
# Owner-only: this file holds a bearer credential. mkdir's mode is
|
|
34
|
+
# umask-masked and a pre-existing dir keeps its old mode, so chmod
|
|
35
|
+
# explicitly too; write_text can't set a create-mode, so open with an
|
|
36
|
+
# explicit mode and chmod defensively afterward.
|
|
37
|
+
token_file.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
38
|
+
os.chmod(token_file.parent, 0o700)
|
|
39
|
+
fd = os.open(str(token_file), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
40
|
+
with os.fdopen(fd, "w") as f:
|
|
41
|
+
f.write(raw)
|
|
42
|
+
os.chmod(token_file, 0o600)
|
|
43
|
+
except OSError:
|
|
44
|
+
pass # best-effort; a non-persisted token just mints again next call
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def build_headers(token_file: Path) -> dict[str, str]:
|
|
48
|
+
headers: dict[str, str] = {}
|
|
49
|
+
existing = read_token(token_file)
|
|
50
|
+
if existing:
|
|
51
|
+
headers[ANON_HEADER] = existing
|
|
52
|
+
source = (os.environ.get("ROOST_CORPUS_SOURCE") or "").strip()
|
|
53
|
+
if source:
|
|
54
|
+
# Install attribution is fixed at mint only; sending this header on every call is harmless -- the backend ignores it once the token resolves to an existing install.
|
|
55
|
+
headers[SOURCE_HEADER] = source
|
|
56
|
+
return headers
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def persist_minted(resp, token_file: Path, label: str = "roost") -> None:
|
|
60
|
+
minted = resp.headers.get(ANON_HEADER)
|
|
61
|
+
if minted:
|
|
62
|
+
write_token(token_file, minted)
|
|
63
|
+
print(
|
|
64
|
+
f"[{label}] minted anonymous token; persisted to {token_file} "
|
|
65
|
+
f"(set ROOST_CORPUS_TOKEN from it to persist across ephemeral runs).",
|
|
66
|
+
file=sys.stderr,
|
|
67
|
+
)
|