Files
insights/bin/build-mcp-oauth-scopes.py
zeekay 1b367e2b62 chore: rebase the tree onto upstream master
The tree was a debranded snapshot of upstream taken around 2026-02-20, and
upstream has moved about five months since. This replaces it with upstream
master, mechanically re-derived: bin/debrand does the rename, and the
pipeline and squashed migrations are restored from the shipped tree.

Not a merge. The previous import replaced the tree wholesale in a single
commit, so there is no shared content history to merge against. Reproducing
the rename on the new tree is what actually converges.

What survives: .hanzo/workflows, the Dockerfiles and bin/docker* entrypoints,
compose files, LLM.md, and insights/migrations. The squashed initial
migration is load-bearing — the live database records it by name, so
upstream's ~918 individual migrations cannot come back.

Nine products are dropped as unreferenced. Twenty-one more that we do not run
are kept anyway because the core app still imports them; unpicking those is a
refactor and does not belong in a rebase.

This base does not build yet, and the reasons are not in the rename:
upstream now wants Python 3.13.13 against our 3.12.12 and Django 5.2 against
our 4.2, and the dependency manifests still name upstream packages that we
republish under our own names. Those are decisions, not renames.
2026-08-01 15:44:40 -07:00

92 lines
4.3 KiB
Python
Executable File

#!/usr/bin/env python3
"""Generate the MCP server's view of the OAuth scope universe from insights/scopes.py.
Emits two constants into `services/mcp/src/lib/oauth-scopes.generated.ts`:
- OAUTH_SCOPES_SUPPORTED (from `get_oauth_scopes_supported()`): the MCP server
publishes RFC 9728 protected-resource metadata at
`/.well-known/oauth-protected-resource`. Spec-compliant clients (e.g. Claude
Code) read `scopes_supported` from there and pass every entry to the
authorization server's `/oauth/authorize`. If the resource list contains a
scope the AS does not recognize, sign-in fails with `?error=invalid_scope`,
so this list must stay a subset of the AS's.
- OAUTH_SCOPES_HIDDEN: PAT-grantable scopes deliberately excluded from the
list above (staff-only surfaces like `batch_import_support`). The MCP server
uses this at runtime to gate tool discovery (`src/lib/staff-only-tools.ts`)
and in tests to allow tools to require a non-advertised scope on purpose.
Generating both from `insights/scopes.py` keeps that module the single
authority for scope classification; the TS side is a projection of it.
Run via insightscli: `insightscli build:openapi-mcp-scopes` (also runs as part of
`build:openapi`). See `common/insightscli/manifest.yaml`.
"""
# ruff: noqa: T201
from __future__ import annotations
import sys
import runpy
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
SCOPES_PY = REPO_ROOT / "insights" / "scopes.py"
OUTPUT_TS = REPO_ROOT / "services" / "mcp" / "src" / "lib" / "oauth-scopes.generated.ts"
def main() -> int:
# runpy.run_path loads the file by filesystem path, bypassing the normal
# import machinery and therefore insights/__init__.py (which pulls in
# Celery and Django settings). Any import that scopes.py doesn't satisfy
# from stdlib will raise ImportError here, failing the build loudly.
scopes_globals = runpy.run_path(str(SCOPES_PY))
all_scopes: list[str] = scopes_globals["get_oauth_scopes_supported"]()
hidden_scopes: list[str] = sorted(scopes_globals["OAUTH_SCOPES_HIDDEN"])
# oxfmt enforces single quotes; format manually rather than json.dumps so
# the generator output is byte-stable regardless of formatter rules. Scope
# names are simple snake_case identifiers + colons and never need escaping,
# but assert that to fail loudly if a scope ever does.
for s in [*all_scopes, *hidden_scopes]:
if "'" in s or "\\" in s:
raise RuntimeError(f"unexpected character in scope name: {s!r}")
body = ",\n".join(f" '{s}'" for s in all_scopes)
hidden_body = ",\n".join(f" '{s}'" for s in hidden_scopes)
output = (
"// AUTO-GENERATED by bin/build-mcp-oauth-scopes.py from insights/scopes.py.\n"
"// Regenerate with `insightscli build:openapi`. Do not edit.\n"
"//\n"
"// Published as `scopes_supported` in MCP protected-resource metadata\n"
"// (RFC 9728). The OAuth authorization server publishes the same list\n"
"// from get_oauth_scopes_supported() at `/.well-known/oauth-authorization-server`.\n"
"// Keeping them aligned is what stops spec-compliant clients (e.g. Claude\n"
"// Code) from hitting `invalid_scope` at sign-in.\n"
"\n"
"export const OAUTH_SCOPES_SUPPORTED = [\n"
f"{body},\n"
"] as const\n"
"\n"
"export type OAuthScope = (typeof OAUTH_SCOPES_SUPPORTED)[number]\n"
"\n"
"// PAT-grantable but deliberately absent from OAUTH_SCOPES_SUPPORTED, so OAuth\n"
"// clients can never request them (mirrors OAUTH_SCOPES_HIDDEN in insights/scopes.py).\n"
"// Tools requiring one of these only surface for staff users whose personal API key\n"
"// explicitly carries it (plus `user:read` for the staff lookup); `*` does not match.\n"
"export const OAUTH_SCOPES_HIDDEN = [\n"
f"{hidden_body},\n"
"] as const\n"
)
OUTPUT_TS.parent.mkdir(parents=True, exist_ok=True)
existing = OUTPUT_TS.read_text() if OUTPUT_TS.exists() else None
if existing != output:
OUTPUT_TS.write_text(output)
print(f"wrote {OUTPUT_TS} ({len(all_scopes)} scopes)")
else:
print(f"{OUTPUT_TS} already up to date ({len(all_scopes)} scopes)")
return 0
if __name__ == "__main__":
sys.exit(main())