ctfy.sdk.client
Platform HTTP client — the player-facing client for the ctfy platform.
This is the client agents and players reach for. It drives the platform's
/api/v1/* REST API with typed Pydantic returns and auto-retry on transient
errors. Operations split into two tiers:
- Global / account namespaces on the client itself —
~PlatformClient.auth,~PlatformClient.me,~PlatformClient.users,~PlatformClient.teams,~PlatformClient.challenges(global catalog),~PlatformClient.instances,~PlatformClient.submissions,~PlatformClient.achievements,~PlatformClient.activities,~PlatformClient.nodes, and~PlatformClient.competitions(discovery). A competition scope —
competition()returns a~ctfy.sdk.competition.Competitionhandle for the operations that are inherently competition-scoped (register, your team, the comp's challenges, team search, standings), socompetition_idis named once. Instance lifecycle and answer submission stay flat (keyed byinstance_id)::from ctfy.sdk import PlatformClient client = PlatformClient("http://localhost:8100", token="pf_xxx") comp = client.competition(client.competitions.list(phase="running")[0].id) comp.register(mode="solo") ready = client.instances.start(comp.challenges()[0].id, competition_id=comp.id) result = client.submissions.submit(ready.id, "FLAG{...}") board = comp.scoreboard()
The admin / operator surface is a separate
~ctfy.sdk.admin.AdminClient, reached via admin. A few
server-status / realtime / version helpers stay top-level on the client:
health(), get_meta(), cluster_info(), events(),
check_server_compatibility().
1"""Platform HTTP client — the player-facing client for the ctfy platform. 2 3This is the client agents and players reach for. It drives the platform's 4``/api/v1/*`` REST API with typed Pydantic returns and auto-retry on transient 5errors. Operations split into two tiers: 6 7* **Global / account** namespaces on the client itself — 8 :attr:`~PlatformClient.auth`, :attr:`~PlatformClient.me`, 9 :attr:`~PlatformClient.users`, :attr:`~PlatformClient.teams`, 10 :attr:`~PlatformClient.challenges` (global catalog), 11 :attr:`~PlatformClient.instances`, :attr:`~PlatformClient.submissions`, 12 :attr:`~PlatformClient.achievements`, :attr:`~PlatformClient.activities`, 13 :attr:`~PlatformClient.nodes`, and 14 :attr:`~PlatformClient.competitions` (discovery). 15* **A competition scope** — :meth:`competition` returns a 16 :class:`~ctfy.sdk.competition.Competition` handle for the operations that are 17 inherently competition-scoped (register, your team, the comp's challenges, 18 team search, standings), so ``competition_id`` is named once. Instance 19 lifecycle and answer submission stay flat (keyed by ``instance_id``):: 20 21 from ctfy.sdk import PlatformClient 22 23 client = PlatformClient("http://localhost:8100", token="pf_xxx") 24 comp = client.competition(client.competitions.list(phase="running")[0].id) 25 comp.register(mode="solo") 26 ready = client.instances.start(comp.challenges()[0].id, competition_id=comp.id) 27 result = client.submissions.submit(ready.id, "FLAG{...}") 28 board = comp.scoreboard() 29 30The admin / operator surface is a separate 31:class:`~ctfy.sdk.admin.AdminClient`, reached via :attr:`admin`. A few 32server-status / realtime / version helpers stay top-level on the client: 33:meth:`health`, :meth:`get_meta`, :meth:`cluster_info`, :meth:`events`, 34:meth:`check_server_compatibility`. 35""" 36 37from __future__ import annotations 38 39from collections.abc import Callable, Sequence 40from functools import cached_property 41 42import httpx 43 44from ctfy.core.constants import DEFAULT_PLATFORM_TIMEOUT 45from ctfy.core.unavailable import UNAVAILABLE_BUDGET_S 46from ctfy.core.version import VersionCheck, check_compatibility, package_version 47from ctfy.sdk._helpers import ( 48 InstanceReadyResult, 49 _raise_for_status, 50) 51from ctfy.sdk._helpers import ( 52 _extract_items as _extract_items, 53) 54from ctfy.sdk._helpers import ( 55 _poll_instance_ready as _poll_instance_ready, 56) 57from ctfy.sdk.admin import AdminClient 58from ctfy.sdk.base import BaseHttpClient 59from ctfy.sdk.competition import Competition 60from ctfy.sdk.events import EventStream 61from ctfy.sdk.resources.achievements import AchievementsResource 62from ctfy.sdk.resources.activities import ActivitiesResource 63from ctfy.sdk.resources.auth import AuthResource 64from ctfy.sdk.resources.authoring import AuthoringResource 65from ctfy.sdk.resources.awd import AwdResource 66from ctfy.sdk.resources.challenges import ChallengesResource 67from ctfy.sdk.resources.changelog import ChangelogResource 68from ctfy.sdk.resources.competitions import CompetitionsResource 69from ctfy.sdk.resources.eval import EvalResource, RegistryResource 70from ctfy.sdk.resources.hints import HintsResource 71from ctfy.sdk.resources.instances import InstancesResource 72from ctfy.sdk.resources.llm_sessions import LlmSessionsResource 73from ctfy.sdk.resources.me import MeResource 74from ctfy.sdk.resources.messages import MessagesResource 75from ctfy.sdk.resources.nodes import NodesResource 76from ctfy.sdk.resources.registration import RegistrationResource 77from ctfy.sdk.resources.reports import ReportsResource 78from ctfy.sdk.resources.search import SearchResource 79from ctfy.sdk.resources.series import SeriesResource 80from ctfy.sdk.resources.site import SiteResource 81from ctfy.sdk.resources.submissions import PatchesResource, SubmissionsResource 82from ctfy.sdk.resources.suites import SuitesResource 83from ctfy.sdk.resources.tasks import TasksResource 84from ctfy.sdk.resources.teams import TeamsResource 85from ctfy.sdk.resources.users import UsersResource 86from ctfy.sdk.resources.vendor import VendorResource 87from ctfy.server.models import ( 88 ClusterInfo, 89 HealthResponse, 90 LandingResponse, 91 MetaResponse, 92 PublicStatsResponse, 93) 94 95__all__ = ["InstanceReadyResult", "PlatformClient"] 96 97 98class PlatformClient(BaseHttpClient): 99 """Player-facing HTTP client for the ctfy platform. 100 101 Methods are grouped into resource namespaces (``client.teams.list()``, …) 102 plus a per-competition scope via ``client.competition(id)``. The admin 103 surface is a separate :class:`~ctfy.sdk.admin.AdminClient` reached via 104 :attr:`admin`. Used by the CLI, the SDK, the MCP server, and external callers. 105 """ 106 107 def __init__( 108 self, 109 server_url: str, 110 token: str = "", 111 max_retries: int = 2, 112 timeout: int = DEFAULT_PLATFORM_TIMEOUT, 113 transport: httpx.BaseTransport | None = None, 114 unavailable_budget_s: float = UNAVAILABLE_BUDGET_S, 115 request_hooks: Sequence[Callable[[httpx.Request], None]] = (), 116 ): 117 """``unavailable_budget_s``: how long one call waits out a ``503`` + 118 ``Retry-After`` (#3312: a redeploy is a wait, not a failed tool 119 call). ``0`` never waits — the platform's own MCP endpoint calling 120 itself, whose tool thread holds one of the pool's slots (#3504).""" 121 self._url = server_url.rstrip("/") 122 super().__init__( 123 f"{self._url}/api/v1", 124 token, 125 timeout=timeout, 126 max_retries=max_retries, 127 transport=transport, 128 unavailable_budget_s=unavailable_budget_s, 129 request_hooks=request_hooks, 130 ) 131 132 @property 133 def server_url(self) -> str: 134 """The platform root, without the ``/api/v1`` suffix. 135 136 Exposed for callers that must build a non-``/api/v1`` URL of 137 their own — today the shell WebSocket, whose ticket carries a 138 platform-relative path the client has to absolutise against the 139 scheme and host *it* reached us on. 140 """ 141 return self._url 142 143 # -- resource namespaces ------------------------------------------------ 144 145 @cached_property 146 def registration(self) -> RegistrationResource: 147 """The caller's own per-competition registration + team logo.""" 148 return RegistrationResource(self) 149 150 @property 151 def authoring(self) -> AuthoringResource: 152 """Upload a challenge your team wrote, for a peer-authored event.""" 153 return AuthoringResource(self) 154 155 @cached_property 156 def teams(self) -> TeamsResource: 157 """Public team discovery + profile reads.""" 158 return TeamsResource(self) 159 160 @cached_property 161 def users(self) -> UsersResource: 162 """Public per-user profile reads.""" 163 return UsersResource(self) 164 165 @cached_property 166 def me(self) -> MeResource: 167 """The calling user's profile, inbox, account, and progress.""" 168 return MeResource(self) 169 170 @cached_property 171 def messages(self) -> MessagesResource: 172 """Site messages and the inbox stream (#2073).""" 173 return MessagesResource(self) 174 175 @cached_property 176 def auth(self) -> AuthResource: 177 """Password auth, OAuth identities, API tokens, sign-in discovery.""" 178 return AuthResource(self) 179 180 @cached_property 181 def achievements(self) -> AchievementsResource: 182 """Public badge catalog, recent-unlock feed, easter eggs.""" 183 return AchievementsResource(self) 184 185 @cached_property 186 def challenges(self) -> ChallengesResource: 187 """Global challenge catalog, attachments, facets, feedback chips.""" 188 return ChallengesResource(self) 189 190 @cached_property 191 def site(self) -> SiteResource: 192 """The operator's site pages and their Contact form (#3414).""" 193 return SiteResource(self) 194 195 @cached_property 196 def hints(self) -> HintsResource: 197 """A challenge's hint tiers in a competition: read, and open (#2101).""" 198 return HintsResource(self) 199 200 @cached_property 201 def changelog(self) -> ChangelogResource: 202 """Public "What's New" feed, plus this account's seen marker.""" 203 return ChangelogResource(self) 204 205 @cached_property 206 def competitions(self) -> CompetitionsResource: 207 """Discover competitions (``list`` / ``get``). To act within one, use 208 :meth:`competition`.""" 209 return CompetitionsResource(self) 210 211 def competition(self, competition_id: str) -> Competition: 212 """Scope to one competition. The inherently competition-scoped 213 operations — register, your team (captain tooling + invites + 214 join-requests), the comp's challenges, team search, and standings — 215 hang off the returned :class:`~ctfy.sdk.competition.Competition` 216 handle, so ``competition_id`` is named once instead of on every call. 217 (Instance lifecycle and answer submission stay on :attr:`instances` / 218 :attr:`submissions`, keyed by ``instance_id``.)""" 219 return Competition(self, competition_id) 220 221 @cached_property 222 def series(self) -> SeriesResource: 223 """A recurring contest's ladder (public), not its schedule — 224 configuring a series is ``client.admin.series``.""" 225 return SeriesResource(self) 226 227 @property 228 def suites(self) -> SuitesResource: 229 """The benchmark suites -- public challenge sets anybody practises or 230 evaluates against at any time (#2097). Playing one is 231 ``client.competition(id)``, like any competition.""" 232 return SuitesResource(self) 233 234 @cached_property 235 def eval(self) -> EvalResource: 236 """Public model-evaluation leaderboard (ranking + dimensional breakdowns).""" 237 return EvalResource(self) 238 239 @property 240 def registry(self) -> RegistryResource: 241 """The container registry's token endpoint (docker follows it itself).""" 242 return RegistryResource(self) 243 244 @cached_property 245 def vendor(self) -> VendorResource: 246 """Vendor tenancy — the calling vendor's own models / runs (``pv_`` bearer).""" 247 return VendorResource(self) 248 249 @cached_property 250 def instances(self) -> InstancesResource: 251 """Launch / control / inspect challenge instances by instance id 252 (the competition is inferred server-side).""" 253 return InstancesResource(self) 254 255 @cached_property 256 def submissions(self) -> SubmissionsResource: 257 """Submit / verify answers + list submissions (by instance id), plus 258 the instance-less QA challenges.""" 259 return SubmissionsResource(self) 260 261 @cached_property 262 def patches(self) -> PatchesResource: 263 """AWD+ defence: submit a patch, then watch for its verdict.""" 264 return PatchesResource(self) 265 266 @cached_property 267 def awd(self) -> AwdResource: 268 """Classic AWD: submit a round's captured flags in one batch.""" 269 return AwdResource(self) 270 271 @cached_property 272 def reports(self) -> ReportsResource: 273 """The engagement report: save a version, read the current one.""" 274 return ReportsResource(self) 275 276 @cached_property 277 def search(self) -> SearchResource: 278 """Global search: competitions, challenges and teams by name.""" 279 return SearchResource(self) 280 281 @cached_property 282 def llm_sessions(self) -> LlmSessionsResource: 283 """Your local agent sessions on the platform's model gateway (#3307).""" 284 return LlmSessionsResource(self) 285 286 @cached_property 287 def tasks(self) -> TasksResource: 288 """The background tasks you may see: when each waited, ran and ended.""" 289 return TasksResource(self) 290 291 @cached_property 292 def activities(self) -> ActivitiesResource: 293 """Platform activity log + histogram.""" 294 return ActivitiesResource(self) 295 296 @cached_property 297 def nodes(self) -> NodesResource: 298 """Public worker-node list (operator node mgmt is on ``admin.nodes``).""" 299 return NodesResource(self) 300 301 @cached_property 302 def admin(self) -> AdminClient: 303 """Admin / operator surface (separate, role-gated server-side). 304 305 Shares this client's transport. See :class:`~ctfy.sdk.admin.AdminClient`. 306 """ 307 return AdminClient(self) 308 309 # -- top-level convenience: server status / realtime / version ---------- 310 311 def health(self) -> HealthResponse: 312 resp = self.request("GET", "/health") 313 _raise_for_status(resp) 314 return HealthResponse.model_validate(resp.json()) 315 316 def get_meta(self) -> MetaResponse: 317 """Server identity + challenge repo SHA + build version. 318 Admin tokens additionally see cluster capacity + team / solve 319 counts in the same payload.""" 320 resp = self.request("GET", "/meta") 321 _raise_for_status(resp) 322 return MetaResponse.model_validate(resp.json()) 323 324 def get_landing(self) -> LandingResponse: 325 """What the public home page shows: the featured event (``None`` 326 when nothing featured may be shown) and the catalog by domain.""" 327 resp = self.request("GET", "/landing") 328 _raise_for_status(resp) 329 return LandingResponse.model_validate(resp.json()) 330 331 def get_public_stats(self) -> PublicStatsResponse: 332 """The home page's live eval numbers and rounded platform scale 333 (#3413). Public and the same for every caller.""" 334 resp = self.request("GET", "/stats/public") 335 _raise_for_status(resp) 336 return PublicStatsResponse.model_validate(resp.json()) 337 338 def cluster_info(self) -> ClusterInfo: 339 """Aggregate worker-node capacity / utilisation (the public 340 capacity banner; no per-node detail).""" 341 resp = self.request("GET", "/cluster-info") 342 _raise_for_status(resp) 343 return ClusterInfo.model_validate(resp.json()) 344 345 def check_server_compatibility(self, *, health: HealthResponse | None = None) -> VersionCheck: 346 """Compare this client's ``ctfy`` version against the server's. 347 348 Uses the cheap unauthenticated ``/health`` probe (pass an 349 already-fetched :class:`HealthResponse` to avoid a second round 350 trip). Pure classification — never prints, never raises on a 351 mismatch, never mutates anything. The caller (CLI, MCP, harness) 352 decides what to do with :class:`~ctfy.core.version.VersionCheck` 353 (typically: print ``.message`` to stderr when not ``.quiet``). 354 355 A server too old to report its version yields 356 :attr:`Compatibility.UNKNOWN` (``health.version == ""``), which 357 is ``.quiet`` — so this stays silent against legacy servers 358 rather than crying wolf. 359 """ 360 h = health if health is not None else self.health() 361 return check_compatibility(package_version(), h.version) 362 363 def events(self, *, auto_reconnect: bool = True) -> EventStream: 364 """Open the platform SSE event stream. 365 366 Yields ``{"event": <name>, "data": <dict>}`` for each frame. 367 Filters: team-scoped events for every team the caller's user is 368 on (across every per-comp competition), plus all global events; 369 admin tokens additionally see admin-only frames. 370 371 Usage:: 372 373 with client.events() as stream: 374 for event in stream: 375 if event["event"] == "solve": 376 ... 377 378 Auto-reconnects on transient network errors with exponential 379 backoff (1s → 30s capped). Set ``auto_reconnect=False`` to make 380 the iterator raise instead. 381 """ 382 token = self._token 383 384 def _factory() -> httpx.Client: 385 # New client per session so a reconnect after a stale 386 # connection drops fresh sockets, not warmed-over ones. 387 return httpx.Client(base_url=self._base_url, timeout=None) 388 389 return EventStream( 390 client_factory=_factory, 391 path="/events", 392 token=token, 393 auto_reconnect=auto_reconnect, 394 )
90@dataclass 91class InstanceReadyResult: 92 """Result of polling an instance until ready.""" 93 94 id: str 95 surface: AttackSurface 96 cert_volume: str = ""
Result of polling an instance until ready.
99class PlatformClient(BaseHttpClient): 100 """Player-facing HTTP client for the ctfy platform. 101 102 Methods are grouped into resource namespaces (``client.teams.list()``, …) 103 plus a per-competition scope via ``client.competition(id)``. The admin 104 surface is a separate :class:`~ctfy.sdk.admin.AdminClient` reached via 105 :attr:`admin`. Used by the CLI, the SDK, the MCP server, and external callers. 106 """ 107 108 def __init__( 109 self, 110 server_url: str, 111 token: str = "", 112 max_retries: int = 2, 113 timeout: int = DEFAULT_PLATFORM_TIMEOUT, 114 transport: httpx.BaseTransport | None = None, 115 unavailable_budget_s: float = UNAVAILABLE_BUDGET_S, 116 request_hooks: Sequence[Callable[[httpx.Request], None]] = (), 117 ): 118 """``unavailable_budget_s``: how long one call waits out a ``503`` + 119 ``Retry-After`` (#3312: a redeploy is a wait, not a failed tool 120 call). ``0`` never waits — the platform's own MCP endpoint calling 121 itself, whose tool thread holds one of the pool's slots (#3504).""" 122 self._url = server_url.rstrip("/") 123 super().__init__( 124 f"{self._url}/api/v1", 125 token, 126 timeout=timeout, 127 max_retries=max_retries, 128 transport=transport, 129 unavailable_budget_s=unavailable_budget_s, 130 request_hooks=request_hooks, 131 ) 132 133 @property 134 def server_url(self) -> str: 135 """The platform root, without the ``/api/v1`` suffix. 136 137 Exposed for callers that must build a non-``/api/v1`` URL of 138 their own — today the shell WebSocket, whose ticket carries a 139 platform-relative path the client has to absolutise against the 140 scheme and host *it* reached us on. 141 """ 142 return self._url 143 144 # -- resource namespaces ------------------------------------------------ 145 146 @cached_property 147 def registration(self) -> RegistrationResource: 148 """The caller's own per-competition registration + team logo.""" 149 return RegistrationResource(self) 150 151 @property 152 def authoring(self) -> AuthoringResource: 153 """Upload a challenge your team wrote, for a peer-authored event.""" 154 return AuthoringResource(self) 155 156 @cached_property 157 def teams(self) -> TeamsResource: 158 """Public team discovery + profile reads.""" 159 return TeamsResource(self) 160 161 @cached_property 162 def users(self) -> UsersResource: 163 """Public per-user profile reads.""" 164 return UsersResource(self) 165 166 @cached_property 167 def me(self) -> MeResource: 168 """The calling user's profile, inbox, account, and progress.""" 169 return MeResource(self) 170 171 @cached_property 172 def messages(self) -> MessagesResource: 173 """Site messages and the inbox stream (#2073).""" 174 return MessagesResource(self) 175 176 @cached_property 177 def auth(self) -> AuthResource: 178 """Password auth, OAuth identities, API tokens, sign-in discovery.""" 179 return AuthResource(self) 180 181 @cached_property 182 def achievements(self) -> AchievementsResource: 183 """Public badge catalog, recent-unlock feed, easter eggs.""" 184 return AchievementsResource(self) 185 186 @cached_property 187 def challenges(self) -> ChallengesResource: 188 """Global challenge catalog, attachments, facets, feedback chips.""" 189 return ChallengesResource(self) 190 191 @cached_property 192 def site(self) -> SiteResource: 193 """The operator's site pages and their Contact form (#3414).""" 194 return SiteResource(self) 195 196 @cached_property 197 def hints(self) -> HintsResource: 198 """A challenge's hint tiers in a competition: read, and open (#2101).""" 199 return HintsResource(self) 200 201 @cached_property 202 def changelog(self) -> ChangelogResource: 203 """Public "What's New" feed, plus this account's seen marker.""" 204 return ChangelogResource(self) 205 206 @cached_property 207 def competitions(self) -> CompetitionsResource: 208 """Discover competitions (``list`` / ``get``). To act within one, use 209 :meth:`competition`.""" 210 return CompetitionsResource(self) 211 212 def competition(self, competition_id: str) -> Competition: 213 """Scope to one competition. The inherently competition-scoped 214 operations — register, your team (captain tooling + invites + 215 join-requests), the comp's challenges, team search, and standings — 216 hang off the returned :class:`~ctfy.sdk.competition.Competition` 217 handle, so ``competition_id`` is named once instead of on every call. 218 (Instance lifecycle and answer submission stay on :attr:`instances` / 219 :attr:`submissions`, keyed by ``instance_id``.)""" 220 return Competition(self, competition_id) 221 222 @cached_property 223 def series(self) -> SeriesResource: 224 """A recurring contest's ladder (public), not its schedule — 225 configuring a series is ``client.admin.series``.""" 226 return SeriesResource(self) 227 228 @property 229 def suites(self) -> SuitesResource: 230 """The benchmark suites -- public challenge sets anybody practises or 231 evaluates against at any time (#2097). Playing one is 232 ``client.competition(id)``, like any competition.""" 233 return SuitesResource(self) 234 235 @cached_property 236 def eval(self) -> EvalResource: 237 """Public model-evaluation leaderboard (ranking + dimensional breakdowns).""" 238 return EvalResource(self) 239 240 @property 241 def registry(self) -> RegistryResource: 242 """The container registry's token endpoint (docker follows it itself).""" 243 return RegistryResource(self) 244 245 @cached_property 246 def vendor(self) -> VendorResource: 247 """Vendor tenancy — the calling vendor's own models / runs (``pv_`` bearer).""" 248 return VendorResource(self) 249 250 @cached_property 251 def instances(self) -> InstancesResource: 252 """Launch / control / inspect challenge instances by instance id 253 (the competition is inferred server-side).""" 254 return InstancesResource(self) 255 256 @cached_property 257 def submissions(self) -> SubmissionsResource: 258 """Submit / verify answers + list submissions (by instance id), plus 259 the instance-less QA challenges.""" 260 return SubmissionsResource(self) 261 262 @cached_property 263 def patches(self) -> PatchesResource: 264 """AWD+ defence: submit a patch, then watch for its verdict.""" 265 return PatchesResource(self) 266 267 @cached_property 268 def awd(self) -> AwdResource: 269 """Classic AWD: submit a round's captured flags in one batch.""" 270 return AwdResource(self) 271 272 @cached_property 273 def reports(self) -> ReportsResource: 274 """The engagement report: save a version, read the current one.""" 275 return ReportsResource(self) 276 277 @cached_property 278 def search(self) -> SearchResource: 279 """Global search: competitions, challenges and teams by name.""" 280 return SearchResource(self) 281 282 @cached_property 283 def llm_sessions(self) -> LlmSessionsResource: 284 """Your local agent sessions on the platform's model gateway (#3307).""" 285 return LlmSessionsResource(self) 286 287 @cached_property 288 def tasks(self) -> TasksResource: 289 """The background tasks you may see: when each waited, ran and ended.""" 290 return TasksResource(self) 291 292 @cached_property 293 def activities(self) -> ActivitiesResource: 294 """Platform activity log + histogram.""" 295 return ActivitiesResource(self) 296 297 @cached_property 298 def nodes(self) -> NodesResource: 299 """Public worker-node list (operator node mgmt is on ``admin.nodes``).""" 300 return NodesResource(self) 301 302 @cached_property 303 def admin(self) -> AdminClient: 304 """Admin / operator surface (separate, role-gated server-side). 305 306 Shares this client's transport. See :class:`~ctfy.sdk.admin.AdminClient`. 307 """ 308 return AdminClient(self) 309 310 # -- top-level convenience: server status / realtime / version ---------- 311 312 def health(self) -> HealthResponse: 313 resp = self.request("GET", "/health") 314 _raise_for_status(resp) 315 return HealthResponse.model_validate(resp.json()) 316 317 def get_meta(self) -> MetaResponse: 318 """Server identity + challenge repo SHA + build version. 319 Admin tokens additionally see cluster capacity + team / solve 320 counts in the same payload.""" 321 resp = self.request("GET", "/meta") 322 _raise_for_status(resp) 323 return MetaResponse.model_validate(resp.json()) 324 325 def get_landing(self) -> LandingResponse: 326 """What the public home page shows: the featured event (``None`` 327 when nothing featured may be shown) and the catalog by domain.""" 328 resp = self.request("GET", "/landing") 329 _raise_for_status(resp) 330 return LandingResponse.model_validate(resp.json()) 331 332 def get_public_stats(self) -> PublicStatsResponse: 333 """The home page's live eval numbers and rounded platform scale 334 (#3413). Public and the same for every caller.""" 335 resp = self.request("GET", "/stats/public") 336 _raise_for_status(resp) 337 return PublicStatsResponse.model_validate(resp.json()) 338 339 def cluster_info(self) -> ClusterInfo: 340 """Aggregate worker-node capacity / utilisation (the public 341 capacity banner; no per-node detail).""" 342 resp = self.request("GET", "/cluster-info") 343 _raise_for_status(resp) 344 return ClusterInfo.model_validate(resp.json()) 345 346 def check_server_compatibility(self, *, health: HealthResponse | None = None) -> VersionCheck: 347 """Compare this client's ``ctfy`` version against the server's. 348 349 Uses the cheap unauthenticated ``/health`` probe (pass an 350 already-fetched :class:`HealthResponse` to avoid a second round 351 trip). Pure classification — never prints, never raises on a 352 mismatch, never mutates anything. The caller (CLI, MCP, harness) 353 decides what to do with :class:`~ctfy.core.version.VersionCheck` 354 (typically: print ``.message`` to stderr when not ``.quiet``). 355 356 A server too old to report its version yields 357 :attr:`Compatibility.UNKNOWN` (``health.version == ""``), which 358 is ``.quiet`` — so this stays silent against legacy servers 359 rather than crying wolf. 360 """ 361 h = health if health is not None else self.health() 362 return check_compatibility(package_version(), h.version) 363 364 def events(self, *, auto_reconnect: bool = True) -> EventStream: 365 """Open the platform SSE event stream. 366 367 Yields ``{"event": <name>, "data": <dict>}`` for each frame. 368 Filters: team-scoped events for every team the caller's user is 369 on (across every per-comp competition), plus all global events; 370 admin tokens additionally see admin-only frames. 371 372 Usage:: 373 374 with client.events() as stream: 375 for event in stream: 376 if event["event"] == "solve": 377 ... 378 379 Auto-reconnects on transient network errors with exponential 380 backoff (1s → 30s capped). Set ``auto_reconnect=False`` to make 381 the iterator raise instead. 382 """ 383 token = self._token 384 385 def _factory() -> httpx.Client: 386 # New client per session so a reconnect after a stale 387 # connection drops fresh sockets, not warmed-over ones. 388 return httpx.Client(base_url=self._base_url, timeout=None) 389 390 return EventStream( 391 client_factory=_factory, 392 path="/events", 393 token=token, 394 auto_reconnect=auto_reconnect, 395 )
Player-facing HTTP client for the ctfy platform.
Methods are grouped into resource namespaces (client.teams.list(), …)
plus a per-competition scope via client.competition(id). The admin
surface is a separate ~ctfy.sdk.admin.AdminClient reached via
admin. Used by the CLI, the SDK, the MCP server, and external callers.
108 def __init__( 109 self, 110 server_url: str, 111 token: str = "", 112 max_retries: int = 2, 113 timeout: int = DEFAULT_PLATFORM_TIMEOUT, 114 transport: httpx.BaseTransport | None = None, 115 unavailable_budget_s: float = UNAVAILABLE_BUDGET_S, 116 request_hooks: Sequence[Callable[[httpx.Request], None]] = (), 117 ): 118 """``unavailable_budget_s``: how long one call waits out a ``503`` + 119 ``Retry-After`` (#3312: a redeploy is a wait, not a failed tool 120 call). ``0`` never waits — the platform's own MCP endpoint calling 121 itself, whose tool thread holds one of the pool's slots (#3504).""" 122 self._url = server_url.rstrip("/") 123 super().__init__( 124 f"{self._url}/api/v1", 125 token, 126 timeout=timeout, 127 max_retries=max_retries, 128 transport=transport, 129 unavailable_budget_s=unavailable_budget_s, 130 request_hooks=request_hooks, 131 )
unavailable_budget_s: how long one call waits out a 503 +
Retry-After (#3312: a redeploy is a wait, not a failed tool
call). 0 never waits — the platform's own MCP endpoint calling
itself, whose tool thread holds one of the pool's slots (#3504).
133 @property 134 def server_url(self) -> str: 135 """The platform root, without the ``/api/v1`` suffix. 136 137 Exposed for callers that must build a non-``/api/v1`` URL of 138 their own — today the shell WebSocket, whose ticket carries a 139 platform-relative path the client has to absolutise against the 140 scheme and host *it* reached us on. 141 """ 142 return self._url
The platform root, without the /api/v1 suffix.
Exposed for callers that must build a non-/api/v1 URL of
their own — today the shell WebSocket, whose ticket carries a
platform-relative path the client has to absolutise against the
scheme and host it reached us on.
146 @cached_property 147 def registration(self) -> RegistrationResource: 148 """The caller's own per-competition registration + team logo.""" 149 return RegistrationResource(self)
The caller's own per-competition registration + team logo.
156 @cached_property 157 def teams(self) -> TeamsResource: 158 """Public team discovery + profile reads.""" 159 return TeamsResource(self)
Public team discovery + profile reads.
161 @cached_property 162 def users(self) -> UsersResource: 163 """Public per-user profile reads.""" 164 return UsersResource(self)
Public per-user profile reads.
166 @cached_property 167 def me(self) -> MeResource: 168 """The calling user's profile, inbox, account, and progress.""" 169 return MeResource(self)
The calling user's profile, inbox, account, and progress.
171 @cached_property 172 def messages(self) -> MessagesResource: 173 """Site messages and the inbox stream (#2073).""" 174 return MessagesResource(self)
Site messages and the inbox stream (#2073).
176 @cached_property 177 def auth(self) -> AuthResource: 178 """Password auth, OAuth identities, API tokens, sign-in discovery.""" 179 return AuthResource(self)
Password auth, OAuth identities, API tokens, sign-in discovery.
181 @cached_property 182 def achievements(self) -> AchievementsResource: 183 """Public badge catalog, recent-unlock feed, easter eggs.""" 184 return AchievementsResource(self)
Public badge catalog, recent-unlock feed, easter eggs.
186 @cached_property 187 def challenges(self) -> ChallengesResource: 188 """Global challenge catalog, attachments, facets, feedback chips.""" 189 return ChallengesResource(self)
Global challenge catalog, attachments, facets, feedback chips.
191 @cached_property 192 def site(self) -> SiteResource: 193 """The operator's site pages and their Contact form (#3414).""" 194 return SiteResource(self)
The operator's site pages and their Contact form (#3414).
196 @cached_property 197 def hints(self) -> HintsResource: 198 """A challenge's hint tiers in a competition: read, and open (#2101).""" 199 return HintsResource(self)
A challenge's hint tiers in a competition: read, and open (#2101).
201 @cached_property 202 def changelog(self) -> ChangelogResource: 203 """Public "What's New" feed, plus this account's seen marker.""" 204 return ChangelogResource(self)
Public "What's New" feed, plus this account's seen marker.
206 @cached_property 207 def competitions(self) -> CompetitionsResource: 208 """Discover competitions (``list`` / ``get``). To act within one, use 209 :meth:`competition`.""" 210 return CompetitionsResource(self)
Discover competitions (list / get). To act within one, use
competition().
212 def competition(self, competition_id: str) -> Competition: 213 """Scope to one competition. The inherently competition-scoped 214 operations — register, your team (captain tooling + invites + 215 join-requests), the comp's challenges, team search, and standings — 216 hang off the returned :class:`~ctfy.sdk.competition.Competition` 217 handle, so ``competition_id`` is named once instead of on every call. 218 (Instance lifecycle and answer submission stay on :attr:`instances` / 219 :attr:`submissions`, keyed by ``instance_id``.)""" 220 return Competition(self, competition_id)
Scope to one competition. The inherently competition-scoped
operations — register, your team (captain tooling + invites +
join-requests), the comp's challenges, team search, and standings —
hang off the returned ~ctfy.sdk.competition.Competition
handle, so competition_id is named once instead of on every call.
(Instance lifecycle and answer submission stay on instances /
submissions, keyed by instance_id.)
222 @cached_property 223 def series(self) -> SeriesResource: 224 """A recurring contest's ladder (public), not its schedule — 225 configuring a series is ``client.admin.series``.""" 226 return SeriesResource(self)
A recurring contest's ladder (public), not its schedule —
configuring a series is client.admin.series.
228 @property 229 def suites(self) -> SuitesResource: 230 """The benchmark suites -- public challenge sets anybody practises or 231 evaluates against at any time (#2097). Playing one is 232 ``client.competition(id)``, like any competition.""" 233 return SuitesResource(self)
The benchmark suites -- public challenge sets anybody practises or
evaluates against at any time (#2097). Playing one is
client.competition(id), like any competition.
235 @cached_property 236 def eval(self) -> EvalResource: 237 """Public model-evaluation leaderboard (ranking + dimensional breakdowns).""" 238 return EvalResource(self)
Public model-evaluation leaderboard (ranking + dimensional breakdowns).
240 @property 241 def registry(self) -> RegistryResource: 242 """The container registry's token endpoint (docker follows it itself).""" 243 return RegistryResource(self)
The container registry's token endpoint (docker follows it itself).
245 @cached_property 246 def vendor(self) -> VendorResource: 247 """Vendor tenancy — the calling vendor's own models / runs (``pv_`` bearer).""" 248 return VendorResource(self)
Vendor tenancy — the calling vendor's own models / runs (pv_ bearer).
250 @cached_property 251 def instances(self) -> InstancesResource: 252 """Launch / control / inspect challenge instances by instance id 253 (the competition is inferred server-side).""" 254 return InstancesResource(self)
Launch / control / inspect challenge instances by instance id (the competition is inferred server-side).
256 @cached_property 257 def submissions(self) -> SubmissionsResource: 258 """Submit / verify answers + list submissions (by instance id), plus 259 the instance-less QA challenges.""" 260 return SubmissionsResource(self)
Submit / verify answers + list submissions (by instance id), plus the instance-less QA challenges.
262 @cached_property 263 def patches(self) -> PatchesResource: 264 """AWD+ defence: submit a patch, then watch for its verdict.""" 265 return PatchesResource(self)
AWD+ defence: submit a patch, then watch for its verdict.
267 @cached_property 268 def awd(self) -> AwdResource: 269 """Classic AWD: submit a round's captured flags in one batch.""" 270 return AwdResource(self)
Classic AWD: submit a round's captured flags in one batch.
272 @cached_property 273 def reports(self) -> ReportsResource: 274 """The engagement report: save a version, read the current one.""" 275 return ReportsResource(self)
The engagement report: save a version, read the current one.
277 @cached_property 278 def search(self) -> SearchResource: 279 """Global search: competitions, challenges and teams by name.""" 280 return SearchResource(self)
Global search: competitions, challenges and teams by name.
282 @cached_property 283 def llm_sessions(self) -> LlmSessionsResource: 284 """Your local agent sessions on the platform's model gateway (#3307).""" 285 return LlmSessionsResource(self)
Your local agent sessions on the platform's model gateway (#3307).
287 @cached_property 288 def tasks(self) -> TasksResource: 289 """The background tasks you may see: when each waited, ran and ended.""" 290 return TasksResource(self)
The background tasks you may see: when each waited, ran and ended.
292 @cached_property 293 def activities(self) -> ActivitiesResource: 294 """Platform activity log + histogram.""" 295 return ActivitiesResource(self)
Platform activity log + histogram.
297 @cached_property 298 def nodes(self) -> NodesResource: 299 """Public worker-node list (operator node mgmt is on ``admin.nodes``).""" 300 return NodesResource(self)
Public worker-node list (operator node mgmt is on admin.nodes).
302 @cached_property 303 def admin(self) -> AdminClient: 304 """Admin / operator surface (separate, role-gated server-side). 305 306 Shares this client's transport. See :class:`~ctfy.sdk.admin.AdminClient`. 307 """ 308 return AdminClient(self)
Admin / operator surface (separate, role-gated server-side).
Shares this client's transport. See ~ctfy.sdk.admin.AdminClient.
317 def get_meta(self) -> MetaResponse: 318 """Server identity + challenge repo SHA + build version. 319 Admin tokens additionally see cluster capacity + team / solve 320 counts in the same payload.""" 321 resp = self.request("GET", "/meta") 322 _raise_for_status(resp) 323 return MetaResponse.model_validate(resp.json())
Server identity + challenge repo SHA + build version. Admin tokens additionally see cluster capacity + team / solve counts in the same payload.
325 def get_landing(self) -> LandingResponse: 326 """What the public home page shows: the featured event (``None`` 327 when nothing featured may be shown) and the catalog by domain.""" 328 resp = self.request("GET", "/landing") 329 _raise_for_status(resp) 330 return LandingResponse.model_validate(resp.json())
What the public home page shows: the featured event (None
when nothing featured may be shown) and the catalog by domain.
332 def get_public_stats(self) -> PublicStatsResponse: 333 """The home page's live eval numbers and rounded platform scale 334 (#3413). Public and the same for every caller.""" 335 resp = self.request("GET", "/stats/public") 336 _raise_for_status(resp) 337 return PublicStatsResponse.model_validate(resp.json())
The home page's live eval numbers and rounded platform scale (#3413). Public and the same for every caller.
339 def cluster_info(self) -> ClusterInfo: 340 """Aggregate worker-node capacity / utilisation (the public 341 capacity banner; no per-node detail).""" 342 resp = self.request("GET", "/cluster-info") 343 _raise_for_status(resp) 344 return ClusterInfo.model_validate(resp.json())
Aggregate worker-node capacity / utilisation (the public capacity banner; no per-node detail).
346 def check_server_compatibility(self, *, health: HealthResponse | None = None) -> VersionCheck: 347 """Compare this client's ``ctfy`` version against the server's. 348 349 Uses the cheap unauthenticated ``/health`` probe (pass an 350 already-fetched :class:`HealthResponse` to avoid a second round 351 trip). Pure classification — never prints, never raises on a 352 mismatch, never mutates anything. The caller (CLI, MCP, harness) 353 decides what to do with :class:`~ctfy.core.version.VersionCheck` 354 (typically: print ``.message`` to stderr when not ``.quiet``). 355 356 A server too old to report its version yields 357 :attr:`Compatibility.UNKNOWN` (``health.version == ""``), which 358 is ``.quiet`` — so this stays silent against legacy servers 359 rather than crying wolf. 360 """ 361 h = health if health is not None else self.health() 362 return check_compatibility(package_version(), h.version)
Compare this client's ctfy version against the server's.
Uses the cheap unauthenticated /health probe (pass an
already-fetched HealthResponse to avoid a second round
trip). Pure classification — never prints, never raises on a
mismatch, never mutates anything. The caller (CLI, MCP, harness)
decides what to do with ~ctfy.core.version.VersionCheck
(typically: print .message to stderr when not .quiet).
A server too old to report its version yields
Compatibility.UNKNOWN (health.version == ""), which
is .quiet — so this stays silent against legacy servers
rather than crying wolf.
364 def events(self, *, auto_reconnect: bool = True) -> EventStream: 365 """Open the platform SSE event stream. 366 367 Yields ``{"event": <name>, "data": <dict>}`` for each frame. 368 Filters: team-scoped events for every team the caller's user is 369 on (across every per-comp competition), plus all global events; 370 admin tokens additionally see admin-only frames. 371 372 Usage:: 373 374 with client.events() as stream: 375 for event in stream: 376 if event["event"] == "solve": 377 ... 378 379 Auto-reconnects on transient network errors with exponential 380 backoff (1s → 30s capped). Set ``auto_reconnect=False`` to make 381 the iterator raise instead. 382 """ 383 token = self._token 384 385 def _factory() -> httpx.Client: 386 # New client per session so a reconnect after a stale 387 # connection drops fresh sockets, not warmed-over ones. 388 return httpx.Client(base_url=self._base_url, timeout=None) 389 390 return EventStream( 391 client_factory=_factory, 392 path="/events", 393 token=token, 394 auto_reconnect=auto_reconnect, 395 )
Open the platform SSE event stream.
Yields {"event": <name>, "data": <dict>} for each frame.
Filters: team-scoped events for every team the caller's user is
on (across every per-comp competition), plus all global events;
admin tokens additionally see admin-only frames.
Usage::
with client.events() as stream:
for event in stream:
if event["event"] == "solve":
...
Auto-reconnects on transient network errors with exponential
backoff (1s → 30s capped). Set auto_reconnect=False to make
the iterator raise instead.