verifiers 0.4.2.dev59__py3-none-any.whl → 0.4.2.dev60__py3-none-any.whl

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.
verifiers/v1/env.py CHANGED
@@ -30,7 +30,8 @@ from verifiers.v1.interception import (
30
30
  requires_tunnel,
31
31
  )
32
32
  from verifiers.v1.mcp import SharedToolServer, serve_shared
33
- from verifiers.v1.runtimes import runtime_is_local
33
+ from verifiers.v1.mcp.launch import check_reachable, tool_runtime
34
+ from verifiers.v1.runtimes import RuntimeConfig, runtime_is_local
34
35
  from verifiers.v1.task import Task
35
36
  from verifiers.v1.trace import Error, Trace, TraceTask
36
37
  from verifiers.v1.utils.format import format_time
@@ -435,11 +436,26 @@ class Env(ABC, Generic[ConfigT]):
435
436
  ]
436
437
  return requires_tunnel(self._runs_local(), configs, shared.values())
437
438
 
439
+ def tool_provider(self) -> RuntimeConfig:
440
+ """The runtime shared servers default to: the roles' provider, or a remote role's
441
+ when roles mix providers, since a local server cannot serve a remote harness."""
442
+ runtimes = [spec.runtime for spec in self._agent_specs.values()]
443
+ remote = [config for config in runtimes if not runtime_is_local(config)]
444
+ return (remote or runtimes)[0]
445
+
438
446
  @contextlib.asynccontextmanager
439
447
  async def shared_tools(self):
440
448
  servers = self.taskset.toolsets(self.taskset.config)
441
449
  if not servers:
442
450
  yield {}
443
451
  return
444
- async with serve_shared(servers, harness_is_local=self._runs_local()) as shared:
452
+ provider = self.tool_provider()
453
+ for server in servers:
454
+ if not server.config.url:
455
+ check_reachable(
456
+ server.server_name,
457
+ tool_runtime(server.config, provider),
458
+ self._runs_local(),
459
+ )
460
+ async with serve_shared(servers, provider) as shared:
445
461
  yield shared
@@ -32,19 +32,21 @@ def requires_tunnel(
32
32
  """Whether the interception must be exposed via a tunnel — some consumer is off the
33
33
  host network: the harness itself, a live `shared` server in a remote runtime, or a
34
34
  tool server config placing one there (each reaches the `/state` channel from
35
- its own runtime). Task-format adapters share the harness's locality. Skipped as
36
- non-consumers: a config-`url` server (external —
37
- it connects out), and an `external` shared server (outside the state machinery
38
- entirely). False means every consumer reaches the server at localhost."""
35
+ its own runtime). A server without a runtime of its own shares the harness's
36
+ locality, as do task-format adapters. Skipped as non-consumers: a config-`url`
37
+ server (external — it connects out), and an `external` shared server (outside the
38
+ state machinery entirely). False means every consumer reaches the server at
39
+ localhost."""
39
40
  from verifiers.v1.mcp.toolset import BaseToolsetConfig
40
41
 
41
42
  if not harness_is_local:
42
43
  return True
43
- if any(not s.external and not s.local for s in shared):
44
+ if any(s.runtime is not None and not s.runtime.is_local for s in shared):
44
45
  return True
45
46
  return any(
46
47
  isinstance(config, BaseToolsetConfig)
47
48
  and not config.url
49
+ and config.runtime is not None
48
50
  and not runtime_is_local(config.runtime)
49
51
  for config in server_configs
50
52
  )
@@ -30,8 +30,7 @@ import time
30
30
  import traceback
31
31
  from collections.abc import AsyncIterator, Awaitable, Collection, Mapping
32
32
  from contextlib import asynccontextmanager
33
- from dataclasses import dataclass, field
34
- from functools import partial
33
+ from dataclasses import dataclass
35
34
 
36
35
  import httpx
37
36
  from aiohttp import web
@@ -68,7 +67,6 @@ from verifiers.v1.semantic import ACPInfo, extract_acp_info, routing_session_id
68
67
  from verifiers.v1.session import IdempotentRequest, ReplayResponse, RolloutSession
69
68
  from verifiers.v1.trace import Error, ModelCall, PolicyEvent, TimeSpan
70
69
  from verifiers.v1.types import FinishReason, Response, Usage
71
- from verifiers.v1.utils.aio import run_shielded
72
70
  from verifiers.v1.utils.format import format_time
73
71
  from verifiers.v1.utils.logging import clip, get_logger, isolated
74
72
 
@@ -95,25 +93,6 @@ RETRY_COUNT_HEADER = "x-stainless-retry-count"
95
93
  IDEMPOTENCY_KEY_HEADER = "Idempotency-Key"
96
94
  IDEMPOTENCY_CACHE_TTL_SECONDS = 600
97
95
  IDEMPOTENCY_CACHE_MAX_COMPLETED = 64
98
- _HOP_HEADERS = {
99
- "connection",
100
- "keep-alive",
101
- "proxy-authenticate",
102
- "proxy-authorization",
103
- "proxy-connection",
104
- "te",
105
- "trailer",
106
- "transfer-encoding",
107
- "upgrade",
108
- }
109
-
110
-
111
- @dataclass
112
- class _MCPRoute:
113
- session: RolloutSession
114
- url: str
115
- client: httpx.AsyncClient
116
- handlers: set[asyncio.Task] = field(default_factory=set)
117
96
 
118
97
 
119
98
  def is_retried_request(headers: Mapping[str, str]) -> bool:
@@ -363,7 +342,6 @@ class InterceptionServer(Interception):
363
342
  self.clients: dict[str, Client] = {}
364
343
  self.state_sessions: dict[str, RolloutSession] = {}
365
344
  self.state_routes: dict[str, RolloutSession] = {}
366
- self.mcp_routes: dict[str, _MCPRoute] = {}
367
345
  self.state_service_secrets = frozenset(state_service_secrets)
368
346
  self.config = config or InterceptionServerConfig()
369
347
  self.tunnel: Tunnel | None = (
@@ -413,18 +391,13 @@ class InterceptionServer(Interception):
413
391
  self.sessions[model_secret] = session
414
392
  self.state_sessions[state_secret] = session
415
393
  self.state_routes[session.trace.id] = session
416
- session.proxy_mcp = partial(self.proxy_mcp, model_secret)
417
394
  return model_secret, state_secret
418
395
 
419
396
  def unregister(self, model_secret: str, state_secret: str) -> None:
420
397
  session = self.sessions.pop(model_secret, None)
421
398
  self.state_sessions.pop(state_secret, None)
422
399
  if session is not None:
423
- session.proxy_mcp = None
424
400
  self.state_routes.pop(session.trace.id, None)
425
- for capability, route in list(self.mcp_routes.items()):
426
- if route.session is session:
427
- del self.mcp_routes[capability]
428
401
  # The rollout concluded; its trace is sealed. Cancel straggler handlers
429
402
  # (aiohttp keeps them alive past client death) so a slow upstream call
430
403
  # can't commit a late turn onto the concluded trace.
@@ -438,107 +411,6 @@ class InterceptionServer(Interception):
438
411
  finally:
439
412
  self.unregister(model_secret, state_secret)
440
413
 
441
- @asynccontextmanager
442
- async def proxy_mcp(self, model_secret: str, url: str) -> AsyncIterator[str]:
443
- """Expose one fixed host backend with its own capability, revoked before reuse.
444
-
445
- All harnesses accept URLs, including ACP consumers. A fresh URL capability
446
- grants only this MCP endpoint, never the private task/state or model channels.
447
- Only the launcher can register destinations; request paths cannot select one.
448
- """
449
- session = self.sessions[model_secret]
450
- capability = secrets.token_urlsafe(32)
451
- # Long-lived MCP streams use the consumer's timeout and rollout cancellation.
452
- # No redirects, environment proxies, cookies from other routes, or retries.
453
- async with httpx.AsyncClient(
454
- timeout=httpx.Timeout(None, connect=5.0),
455
- limits=httpx.Limits(max_connections=None, max_keepalive_connections=8),
456
- trust_env=False,
457
- ) as client:
458
- route = _MCPRoute(session, url, client)
459
- self.mcp_routes[capability] = route
460
- try:
461
- yield f"{self.base_url.rstrip('/')}/mcp/{capability}"
462
- finally:
463
- self.mcp_routes.pop(capability, None)
464
- handlers = list(route.handlers)
465
- for handler in handlers:
466
- handler.cancel()
467
- await run_shielded(asyncio.gather(*handlers, return_exceptions=True))
468
-
469
- async def handle_mcp(self, request: web.Request) -> web.StreamResponse:
470
- route = self.mcp_routes.get(request.match_info["capability"])
471
- if route is None or route.session.released:
472
- return web.json_response({"error": "unauthorized"}, status=401)
473
- handler = asyncio.current_task()
474
- assert handler is not None
475
- route.session.adopt(handler)
476
- route.handlers.add(handler)
477
- pending = asyncio.create_task(self._forward_mcp(request, route))
478
- try:
479
- # Model handlers intentionally survive disconnects for coalesced retries.
480
- # MCP handlers must instead close even an idle SSE stream on disconnect.
481
- while not pending.done():
482
- await asyncio.wait({pending}, timeout=0.25)
483
- if request.transport is None or request.transport.is_closing():
484
- raise asyncio.CancelledError
485
- return await pending
486
- finally:
487
- pending.cancel()
488
- await run_shielded(asyncio.gather(pending, return_exceptions=True))
489
- route.handlers.discard(handler)
490
-
491
- async def _forward_mcp(
492
- self, request: web.Request, route: _MCPRoute
493
- ) -> web.StreamResponse:
494
- headers = httpx.Headers(request.headers.items())
495
- blocked = _HOP_HEADERS | set(
496
- map(str.strip, headers.get("connection", "").lower().split(","))
497
- )
498
- # aiohttp decodes incoming bodies; HTTPX supplies backend Host and framing.
499
- for name in blocked | {"host", "content-length", "content-encoding"}:
500
- headers.pop(name, None)
501
- upstream = httpx.Request(
502
- request.method,
503
- httpx.URL(route.url).copy_with(
504
- query=request.rel_url.raw_query_string.encode()
505
- ),
506
- headers=headers,
507
- content=request.content.iter_any() if request.can_read_body else b"",
508
- )
509
- stream = web.StreamResponse()
510
- response = None
511
- try:
512
- # send(Request) forwards only this request's headers, without stored cookies.
513
- response = await route.client.send(upstream, stream=True)
514
- stream.set_status(response.status_code)
515
- blocked = _HOP_HEADERS | set(
516
- map(
517
- str.strip, response.headers.get("connection", "").lower().split(",")
518
- )
519
- )
520
- for name, value in response.headers.multi_items():
521
- if name.lower() not in blocked:
522
- stream.headers.add(name, value)
523
- await stream.prepare(request)
524
- async for chunk in response.aiter_raw():
525
- await stream.write(chunk)
526
- await stream.write_eof()
527
- return stream
528
- except httpx.TransportError as error:
529
- if stream.prepared:
530
- # A truncated response is a failed call, never a successful partial result.
531
- if request.transport is not None:
532
- request.transport.close()
533
- return stream
534
- return web.json_response(
535
- {"error": "MCP backend unavailable"},
536
- status=504 if isinstance(error, httpx.TimeoutException) else 502,
537
- )
538
- finally:
539
- if response is not None:
540
- await run_shielded(response.aclose())
541
-
542
414
  def _handler_for(self, dialect: Dialect):
543
415
  """Bind a route's dialect to the request handler — the route the SDK posts to is what
544
416
  selects the wire format (see `dialects.DIALECTS`)."""
@@ -588,8 +460,6 @@ class InterceptionServer(Interception):
588
460
  # A launched tool server fetches its rollout's task here to run `setup_task` — the task
589
461
  # is never passed via env, only over this channel, keyed by the state bearer.
590
462
  app.router.add_get("/task", self.handle_task_get)
591
- app.router.add_route("*", "/mcp/{capability}", self.handle_mcp)
592
- # MCP paths are bearer capabilities, so do not write them to access logs.
593
463
  self.runner = web.AppRunner(app, access_log=None)
594
464
  await self.runner.setup()
595
465
  self.stack.push_async_callback(self.runner.cleanup)
@@ -7,7 +7,7 @@ import secrets
7
7
  import shlex
8
8
  import sys
9
9
  import uuid
10
- from collections.abc import AsyncIterator, Mapping
10
+ from collections.abc import Mapping
11
11
  from dataclasses import dataclass, field
12
12
  from functools import cache
13
13
  from importlib.metadata import distribution, packages_distributions
@@ -15,9 +15,10 @@ from pathlib import Path, PurePosixPath
15
15
  from typing import TYPE_CHECKING
16
16
  from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
17
17
 
18
- from verifiers.v1.configs.runtime import NetworkPolicyConfig
18
+ from pydantic import TypeAdapter
19
+
20
+ from verifiers.v1.configs.runtime import CustomRuntimeConfig, NetworkPolicyConfig
19
21
  from verifiers.v1.errors import ToolsetError
20
- from verifiers.v1.interception.tunnel import PrimeTunnel
21
22
  from verifiers.v1.mcp.packages import install_package
22
23
  from verifiers.v1.mcp.server import (
23
24
  STATE_ROUTE_PARAM,
@@ -29,7 +30,9 @@ from verifiers.v1.mcp.server import (
29
30
  from verifiers.v1.mcp.toolset import BaseToolsetConfig, ToolsetTimeoutConfig
30
31
  from verifiers.v1.runtimes import (
31
32
  Runtime,
33
+ RuntimeConfig,
32
34
  provision_backend,
35
+ runtime_is_local,
33
36
  )
34
37
  from verifiers.v1.runtimes.base import _ENSURE_UV, SERVICE_PORT
35
38
  from verifiers.v1.state import State
@@ -38,7 +41,6 @@ from verifiers.v1.utils.logging import get_logger
38
41
 
39
42
  if TYPE_CHECKING:
40
43
  from verifiers.v1.mcp.toolset import Toolset
41
- from verifiers.v1.session import MCPProxy
42
44
 
43
45
  logger = get_logger(__name__)
44
46
 
@@ -252,22 +254,6 @@ async def serve_in_runtime(
252
254
  return port
253
255
 
254
256
 
255
- @contextlib.asynccontextmanager
256
- async def reachable_url(
257
- service_runtime: Runtime,
258
- port: int,
259
- *,
260
- consumer_is_local: bool,
261
- ) -> AsyncIterator[str]:
262
- """Publish a service port, tunneling host-local URLs for remote consumers."""
263
- url = await service_runtime.expose(port)
264
- if service_runtime.is_local and not consumer_is_local:
265
- async with PrimeTunnel().expose(urlsplit(url).port or 80) as public:
266
- yield public
267
- else:
268
- yield url
269
-
270
-
271
257
  @dataclass(frozen=True)
272
258
  class _ServedServer:
273
259
  url: str
@@ -277,16 +263,18 @@ class _ServedServer:
277
263
  @contextlib.asynccontextmanager
278
264
  async def _serve(
279
265
  server: ServerBase,
266
+ provider: RuntimeConfig,
280
267
  harness_runtime: Runtime | None = None,
281
- harness_is_local: bool = True,
282
268
  *,
283
269
  state_secret: str = "",
284
270
  state_base: str | None = None,
285
- proxy_mcp: MCPProxy | None = None,
286
271
  services: Mapping[str, Runtime] | None = None,
287
272
  hosts: Mapping[str, str] | None = None,
288
273
  placements: Mapping[str, Runtime] | None = None,
289
274
  ):
275
+ """Serve `server` in a service, a VM on the rollout's private network, or a runtime
276
+ of its own (`tool_runtime` over the harness's `provider`), and yield its URL as the
277
+ harness reaches it."""
290
278
  cfg = server.config
291
279
  service = getattr(cfg, "service", None)
292
280
  own_vm = (placements or {}).get(server.server_name)
@@ -310,17 +298,17 @@ async def _serve(
310
298
  "which needs a native Prime service VM"
311
299
  )
312
300
  else:
313
- if (
314
- isinstance(cfg.runtime, NetworkPolicyConfig)
315
- and cfg.runtime.network_restricted
316
- ):
301
+ config = tool_runtime(cfg, provider)
302
+ if isinstance(config, NetworkPolicyConfig) and config.network_restricted:
317
303
  raise ToolsetError(
318
304
  f"server {server.server_name!r} restricts its runtime's network, "
319
305
  "which needs a Prime runtime of its own beside a Prime workspace "
320
306
  "without a task service spec (it then joins the rollout's "
321
307
  "private network)"
322
308
  )
323
- backend = await stack.enter_async_context(provision_backend(cfg.runtime))
309
+ if harness_runtime is not None:
310
+ check_reachable(server.server_name, config, harness_runtime.is_local)
311
+ backend = await stack.enter_async_context(provision_backend(config))
324
312
  runtime = backend.bind()
325
313
 
326
314
  port = await serve_in_runtime(
@@ -338,37 +326,42 @@ async def _serve(
338
326
  if host is not None:
339
327
  yield _ServedServer(f"http://{host}:{port}/mcp", runtime)
340
328
  return
341
-
342
- consumer_is_local = (
343
- harness_runtime.is_local
344
- if harness_runtime is not None
345
- else harness_is_local
346
- )
347
- if proxy_mcp is not None and runtime.is_local and not consumer_is_local:
348
- backend_url = await runtime.expose(port)
349
- # Revoke and drain the proxy before releasing the runtime.
350
- url = await stack.enter_async_context(
351
- proxy_mcp(f"{backend_url.rstrip('/')}/mcp")
352
- )
353
- yield _ServedServer(url, runtime)
354
- return
355
- base = await stack.enter_async_context(
356
- reachable_url(runtime, port, consumer_is_local=consumer_is_local)
357
- )
329
+ base = await runtime.expose(port)
358
330
  if harness_runtime is not None:
359
331
  base = harness_runtime.host_url(base)
360
332
  yield _ServedServer(f"{base.rstrip('/')}/mcp", runtime)
361
333
 
362
334
 
335
+ def tool_runtime(config: BaseToolsetConfig, provider: RuntimeConfig) -> RuntimeConfig:
336
+ """The runtime a launched server runs in: its configured one, or by default a
337
+ sandbox of its own from the harness's `provider` (a Docker container beside a Docker
338
+ harness, a Prime VM beside a Prime one)."""
339
+ if config.runtime is not None:
340
+ return config.runtime
341
+ data: dict = {"type": provider.type}
342
+ if isinstance(provider, CustomRuntimeConfig):
343
+ data["import_path"] = provider.import_path
344
+ return TypeAdapter(RuntimeConfig).validate_python(data)
345
+
346
+
347
+ def check_reachable(name: str, config: RuntimeConfig, harness_is_local: bool) -> None:
348
+ """Refuse a server on a local runtime for a remote harness: a Prime sandbox cannot
349
+ reach a server on this machine."""
350
+ if runtime_is_local(config) and not harness_is_local:
351
+ raise ToolsetError(
352
+ f"tool server {name!r} runs on the local {config.type} runtime, which a "
353
+ "remote harness cannot reach; leave its runtime unset to run it on the "
354
+ "harness's provider"
355
+ )
356
+
357
+
363
358
  @contextlib.asynccontextmanager
364
359
  async def serve(
365
360
  server: ServerBase,
366
- harness_runtime: Runtime | None = None,
367
- harness_is_local: bool = True,
361
+ harness_runtime: Runtime,
368
362
  *,
369
363
  state_secret: str = "",
370
364
  state_base: str | None = None,
371
- proxy_mcp: MCPProxy | None = None,
372
365
  services: Mapping[str, Runtime] | None = None,
373
366
  hosts: Mapping[str, str] | None = None,
374
367
  placements: Mapping[str, Runtime] | None = None,
@@ -376,11 +369,10 @@ async def serve(
376
369
  """Serve one MCP server and yield the URL visible to its consumer."""
377
370
  async with _serve(
378
371
  server,
372
+ harness_runtime.config,
379
373
  harness_runtime,
380
- harness_is_local,
381
374
  state_secret=state_secret,
382
375
  state_base=state_base,
383
- proxy_mcp=proxy_mcp,
384
376
  services=services,
385
377
  hosts=hosts,
386
378
  placements=placements,
@@ -391,32 +383,28 @@ async def serve(
391
383
  @dataclass(frozen=True)
392
384
  class SharedToolServer:
393
385
  """One live taskset-scoped (shared) server, as the rollouts see it: its eval-level
394
- `url` plus whether its runtime is `local` (host-reachable) — a remote one is an
395
- interception consumer, so the interception must be exposed for it to reach the
396
- `/state` channel (see `Env._requires_tunnel`). `runtime` is retained for translating
397
- that channel into the server's network. An `external` server (a
398
- config-`url` endpoint) was not launched by the framework and sits outside its state
399
- machinery entirely: rollouts get its URL bare — no state tag (and no per-rollout
400
- secret sent to a third party)."""
386
+ `url`, and the `runtime` it runs in. A remote runtime is an interception consumer,
387
+ so the interception must be exposed for it to reach the `/state` channel (see
388
+ `Env._requires_tunnel`); the runtime also translates that channel into the
389
+ server's network. An `external` server (a config-`url` endpoint) was not launched
390
+ by the framework and sits outside its state machinery entirely: rollouts get its
391
+ URL bare — no state tag (and no per-rollout secret sent to a third party)."""
401
392
 
402
393
  url: str
403
- local: bool
404
394
  external: bool = False
405
395
  runtime: Runtime | None = field(default=None, repr=False)
406
396
  state_secret: str = field(default="", repr=False)
407
397
 
408
398
 
409
399
  @contextlib.asynccontextmanager
410
- async def serve_shared(toolsets: list[Toolset], harness_is_local: bool = True):
400
+ async def serve_shared(toolsets: list[Toolset], provider: RuntimeConfig):
411
401
  """Start the taskset-scoped (shared) tool servers ONCE for a whole eval, each in its OWN
412
- `runtime`, and yield `{name: SharedToolServer}` reachable by every rollout's harness.
413
- Reachability mirrors a per-rollout tool, but there's no single harness runtime to read
414
- locality off — the caller (`Env.shared_tools`) passes the harness runtime's
415
- `harness_is_local`, so a host tool gets one host bridge (tunnel) when the harness runs
416
- remotely, and a remote tool runtime publishes its own URL. Torn down when the eval ends.
417
- A shared server is task-agnostic — the taskset carries no per-row data — so its `setup`
418
- gets no task (its `setup_task` is never called; the per-rollout servers fetch
419
- theirs over the `/task` channel)."""
402
+ runtime (`tool_runtime` over the harnesses' `provider`), and yield
403
+ `{name: SharedToolServer}` reachable by every rollout's harness. The caller
404
+ (`Env.shared_tools`) checks that every harness can reach them. Torn down when the
405
+ eval ends. A shared server is task-agnostic — the taskset carries no per-row data —
406
+ so its `setup` gets no task (its `setup_task` is never called; the per-rollout
407
+ servers fetch theirs over the `/task` channel)."""
420
408
  servers: dict[str, SharedToolServer] = {}
421
409
  async with contextlib.AsyncExitStack() as stack:
422
410
  for toolset in toolsets:
@@ -435,24 +423,17 @@ async def serve_shared(toolsets: list[Toolset], harness_is_local: bool = True):
435
423
  "or construct it in `Task.toolsets` to run it per-rollout.",
436
424
  name,
437
425
  )
438
- if cfg.url: # already running remotely; nothing launched, nothing to bridge
439
- servers[name] = SharedToolServer(
440
- url=cfg.url, local=False, external=True
441
- )
426
+ if cfg.url: # already running remotely; nothing launched
427
+ servers[name] = SharedToolServer(url=cfg.url, external=True)
442
428
  else:
443
429
  state_secret = (
444
430
  secrets.token_urlsafe(24) if toolset._state_cls is not State else ""
445
431
  )
446
432
  served = await stack.enter_async_context(
447
- _serve(
448
- toolset,
449
- harness_is_local=harness_is_local,
450
- state_secret=state_secret,
451
- )
433
+ _serve(toolset, provider, state_secret=state_secret)
452
434
  )
453
435
  servers[name] = SharedToolServer(
454
436
  url=served.url,
455
- local=served.runtime.is_local,
456
437
  runtime=served.runtime,
457
438
  state_secret=state_secret,
458
439
  )
@@ -491,7 +472,6 @@ async def serve_tools(
491
472
  state_secret: str = "",
492
473
  state_route: str = "",
493
474
  state_base: str | None = None,
494
- proxy_mcp: MCPProxy | None = None,
495
475
  services: Mapping[str, Runtime] | None = None,
496
476
  hosts: Mapping[str, str] | None = None,
497
477
  placements: Mapping[str, Runtime] | None = None,
@@ -506,14 +486,15 @@ async def serve_tools(
506
486
  urls: dict[str, str] = {}
507
487
  async with contextlib.AsyncExitStack() as stack:
508
488
  for name, server in (shared or {}).items():
489
+ # `host_url` translates a server on this machine; any other URL passes as is.
490
+ url = harness_runtime.host_url(server.url)
509
491
  if server.external:
510
492
  # Not ours: a pre-existing endpoint with no vf state channel. Pass the URL
511
493
  # through bare — a state tag would be useless, and the per-rollout secret
512
494
  # must not ride the query string to a third-party host.
513
- urls[name] = harness_runtime.host_url(server.url)
495
+ urls[name] = url
514
496
  logger.debug("Using external tool server %s url=%s", name, server.url)
515
497
  continue
516
- url = harness_runtime.host_url(server.url) if server.local else server.url
517
498
  urls[name] = _shared_url_for_rollout(server, url, state_base, state_route)
518
499
  logger.debug("Using shared tool server %s url=%s", name, server.url)
519
500
  for toolset in toolsets:
@@ -528,7 +509,6 @@ async def serve_tools(
528
509
  harness_runtime,
529
510
  state_secret=state_secret,
530
511
  state_base=state_base,
531
- proxy_mcp=proxy_mcp,
532
512
  services=services,
533
513
  hosts=hosts,
534
514
  placements=placements,
@@ -8,7 +8,7 @@ from pydantic import Field, model_validator
8
8
  from pydantic_config import BaseConfig
9
9
 
10
10
  from verifiers.v1.mcp.server import ConfigT, ServerBase
11
- from verifiers.v1.runtimes import PrimeConfig, RuntimeConfig
11
+ from verifiers.v1.runtimes import RuntimeConfig
12
12
  from verifiers.v1.state import StateT
13
13
  from verifiers.v1.utils.decorators import discover_decorated
14
14
 
@@ -28,16 +28,18 @@ class ToolsetTimeoutConfig(BaseConfig):
28
28
  class BaseToolsetConfig(BaseConfig):
29
29
  """Runtime and connection settings for per-task and shared tool servers."""
30
30
 
31
- runtime: RuntimeConfig = PrimeConfig()
32
- """Where the server runs: a Prime sandbox by default."""
31
+ runtime: RuntimeConfig | None = None
32
+ """Where the server runs. None runs it in a sandbox of its own from the harness's
33
+ provider: a Docker container beside a Docker harness, a Prime VM beside a Prime
34
+ one. A server on a local runtime cannot serve a remote harness."""
33
35
  url: str | None = None
34
36
  timeout: ToolsetTimeoutConfig = ToolsetTimeoutConfig()
35
37
 
36
38
 
37
39
  class ToolsetConfig(BaseToolsetConfig):
38
- """A per-task tool server. A Prime `runtime` beside a Prime workspace without a task
39
- service spec is a VM of the server's own that joins the workspace over the rollout's
40
- private network, under its own egress policy."""
40
+ """A per-task tool server. On Prime beside a Prime workspace without a task service
41
+ spec, its VM joins the workspace over the rollout's private network, under its own
42
+ egress policy."""
41
43
 
42
44
  service: str | None = None
43
45
  """Run the server in a named native Prime service VM. The harness reaches it
@@ -52,7 +54,7 @@ class ToolsetConfig(BaseToolsetConfig):
52
54
  "a tool server placed in a service cannot use a remote URL"
53
55
  )
54
56
  # The service is the server's runtime; another one, or its policy, would go unused.
55
- if self.runtime != PrimeConfig():
57
+ if self.runtime is not None:
56
58
  raise ValueError(
57
59
  "a tool server placed in a service runs in that service and "
58
60
  f"takes no runtime of its own (got {self.runtime.type})"
verifiers/v1/rollout.py CHANGED
@@ -412,7 +412,6 @@ class Rollout:
412
412
  self._agent_runtime,
413
413
  shared=self._shared_tools,
414
414
  state_secret=state_secret,
415
- proxy_mcp=self._session.proxy_mcp,
416
415
  state_route=self.trace.id,
417
416
  state_base=base_url,
418
417
  services=services,
@@ -37,17 +37,18 @@ def tool_vms(
37
37
  network, by server name: those on Prime runtimes of their own beside a Prime
38
38
  workspace of the rollout's own, without a task service spec. Any other server keeps its
39
39
  runtime's published port, which takes no network policy."""
40
+ from verifiers.v1.mcp.launch import tool_runtime
40
41
  from verifiers.v1.mcp.toolset import ToolsetConfig
41
42
 
42
43
  if composed or borrowed or not isinstance(workspace, PrimeConfig):
43
44
  return {}
44
45
  vms = {
45
- toolset.server_name: toolset.config.runtime
46
+ toolset.server_name: runtime
46
47
  for toolset in toolsets
47
48
  if isinstance(toolset.config, ToolsetConfig)
48
- and isinstance(toolset.config.runtime, PrimeConfig)
49
49
  and not toolset.config.url
50
50
  and toolset.config.service is None
51
+ and isinstance(runtime := tool_runtime(toolset.config, workspace), PrimeConfig)
51
52
  }
52
53
  if "main" in vms:
53
54
  raise ValueError("a tool server on a VM of its own cannot be named 'main'")
verifiers/v1/session.py CHANGED
@@ -20,7 +20,6 @@ import inspect
20
20
  import json
21
21
  from collections import Counter
22
22
  from collections.abc import Awaitable, Callable
23
- from contextlib import AbstractAsyncContextManager
24
23
  from dataclasses import dataclass, field, replace
25
24
  from functools import cached_property
26
25
  from typing import get_origin, get_type_hints
@@ -53,8 +52,6 @@ from verifiers.v1.utils.logging import (
53
52
 
54
53
  logger = get_logger(__name__)
55
54
 
56
- MCPProxy = Callable[[str], AbstractAsyncContextManager[str]]
57
-
58
55
 
59
56
  def hook_boundary(handler: Callable, *, allow_trace: bool) -> type:
60
57
  """Select a hook boundary solely from its annotated parameters."""
@@ -186,8 +183,6 @@ class RolloutSession:
186
183
  server-owned client for its route's endpoint config (one per distinct config) at
187
184
  `register` and again when the route changes, so every rollout it multiplexes shares one
188
185
  keepalive connection pool instead of opening its own."""
189
- proxy_mcp: MCPProxy | None = field(default=None, repr=False)
190
- """Register a host MCP backend on this session's interception server while serving."""
191
186
  error: "RolloutError | None" = None
192
187
  """The latest unresolved model-call failure. The harness only sees it as an HTTP error, so
193
188
  when its program dies on it the rollout records this original error instead of a secondary
@@ -8,14 +8,16 @@ from collections.abc import Iterator
8
8
  from contextlib import AsyncExitStack
9
9
  from pathlib import Path
10
10
  from typing import Any, ClassVar, cast
11
+ from urllib.parse import urlsplit
11
12
 
12
13
  import httpx
13
14
  from pydantic import Field
14
15
 
15
16
  from verifiers.v1.dialects.responses import ResponsesDialect
16
17
  from verifiers.v1.envs.single_agent import SingleAgentEnv
18
+ from verifiers.v1.interception.tunnel import PrimeTunnel
17
19
  from verifiers.v1.mcp import SharedToolsetConfig, Toolset
18
- from verifiers.v1.mcp.launch import _read_back_port, log_tail, reachable_url
20
+ from verifiers.v1.mcp.launch import _read_back_port, log_tail, tool_runtime
19
21
  from verifiers.v1.runtimes import Runtime, provision_backend
20
22
  from verifiers.v1.runtimes.base import SERVICE_PORT
21
23
  from verifiers.v1.task import Task, TaskConfig, TaskData
@@ -43,7 +45,8 @@ class NeMoGymConfig(TasksetConfig):
43
45
  """JSONL rows containing ``responses_create_params`` and verifier metadata."""
44
46
 
45
47
  tools: SharedToolsetConfig = SharedToolsetConfig()
46
- """Placement of the shared tool and managed resource servers; Prime by default."""
48
+ """Placement of the shared tool and managed resource servers; the harness's
49
+ provider by default."""
47
50
  task: NeMoGymTaskConfig = NeMoGymTaskConfig()
48
51
 
49
52
 
@@ -138,7 +141,7 @@ class NeMoGymEnv(SingleAgentEnv):
138
141
  entrypoint = taskset.resource_server
139
142
  if entrypoint is None:
140
143
  raise ValueError("set --env.taskset.task.resources-url")
141
- runtime_config = taskset.config.tools.runtime
144
+ runtime_config = tool_runtime(taskset.config.tools, self.tool_provider())
142
145
  if getattr(runtime_config, "network_restricted", False):
143
146
  raise ValueError(
144
147
  "managed NeMo Gym resource servers need an unrestricted runtime"
@@ -164,9 +167,13 @@ class NeMoGymEnv(SingleAgentEnv):
164
167
  loop = asyncio.get_running_loop()
165
168
  deadline = loop.time() + (math.inf if timeout is None else timeout)
166
169
  port = await _read_back_port(runtime, port_file, deadline)
167
- resources_url = await stack.enter_async_context(
168
- reachable_url(runtime, port, consumer_is_local=False)
169
- )
170
+ resources_url = await runtime.expose(port)
171
+ if runtime.is_local:
172
+ # The shared NeMo tool server reaches this from a container of its own,
173
+ # where host loopback is not this machine: publish it.
174
+ resources_url = await stack.enter_async_context(
175
+ PrimeTunnel().expose(urlsplit(resources_url).port or 80)
176
+ )
170
177
  async with httpx.AsyncClient(
171
178
  timeout=1, headers={"X-Verifiers-Nemo-Token": token}
172
179
  ) as client:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: verifiers
3
- Version: 0.4.2.dev59
3
+ Version: 0.4.2.dev60
4
4
  Summary: Verifiers: Environments for LLM Reinforcement Learning
5
5
  Project-URL: Homepage, https://github.com/primeintellect-ai/verifiers
6
6
  Project-URL: Documentation, https://github.com/primeintellect-ai/verifiers
@@ -2,16 +2,16 @@ verifiers/__init__.py,sha256=F5IVMw6mhGaPBMCw7QKk0la_r5mMwydP2hdTTdQucik,352
2
2
  verifiers/v1/__init__.py,sha256=rBibZ3Gss1bmW5tdm6i-TkloXLTX2TGOjFmHU3G8FCk,18861
3
3
  verifiers/v1/agent.py,sha256=x4jWG8rVxFgLbCVPEmsuzJuFDGtandLCWlvojyTvMcM,48462
4
4
  verifiers/v1/delta.py,sha256=23USfU7G5L3TBnV3apyuOa0M_uQAgvTo6a4Ke4msRV0,12205
5
- verifiers/v1/env.py,sha256=0VQerxERqzkEUa5VF7hMXHD8gbojYCaioqrY3mEFz4U,19627
5
+ verifiers/v1/env.py,sha256=qQchIleah2WUZy2AtvkOZgGbFFqv7_3ajS8gc_tXgIs,20399
6
6
  verifiers/v1/episode.py,sha256=ExeTkNEBsDuG40m6VogV6Gd4IHdO4SMPIzQSpt_V96U,6984
7
7
  verifiers/v1/errors.py,sha256=OieUBIOZ6FW7oKygbXIRoag6RrPxKYpMPfEYPcCnVVE,5863
8
8
  verifiers/v1/grading.py,sha256=HMSvFQVYWZw0IjRWNfkYRRmU4wa4ZLIKrzYfyteKmG8,9795
9
9
  verifiers/v1/graph.py,sha256=ifZoODILT1Ek7vM55VZrxHiJErrTvvz-Ihg7oolMTig,48271
10
10
  verifiers/v1/harness.py,sha256=nXDkkGfYn4KyWn0IqnUg-FFqXXFWI33-IFLzz4x4BCo,16756
11
11
  verifiers/v1/judge.py,sha256=T-TyYVcLGIoyUADYKy_pCBj2CTLhERlct5pmmWqPpTA,10507
12
- verifiers/v1/rollout.py,sha256=4dBl8wue2S49w0dbGk9b4-WMUaE86Izn4fagMRq3cz4,49994
12
+ verifiers/v1/rollout.py,sha256=4uM7RDO-qgzNAb-Lhch6BeGl-gk5wMjEL82O-HMs-t0,49935
13
13
  verifiers/v1/semantic.py,sha256=nqKPPUoPL5Oh8Es_XjtcbDiQiIMKTYayXEm-EPB-jAE,5129
14
- verifiers/v1/session.py,sha256=rxAiQpRtUqveKKyVPTVHPNOzAv4dZcEKzQutRbEkHKo,30873
14
+ verifiers/v1/session.py,sha256=T9xZY-POtfUBWvLP-lsHctKW4-PA3FNG4p2Mz-P7euY,30604
15
15
  verifiers/v1/state.py,sha256=EckF2bWp-vV4b1jYJ9sLI5xrfGuI5spIgYYwW926toI,595
16
16
  verifiers/v1/submission.py,sha256=K4WJ7twNQHhgeRVtZuJhdUxXSIxKyQlgWbpjaB_znfE,7630
17
17
  verifiers/v1/task.py,sha256=BpE2OC_8chTC5nZmDFxK3hJEwACZ_lGCSVIcuW9zz7c,15775
@@ -120,10 +120,10 @@ verifiers/v1/harnesses/utils/install.py,sha256=EESYSh_e9L4gj6N4GvAbQY2kb4ckven7t
120
120
  verifiers/v1/harnesses/utils/launch.py,sha256=2KuLnNruUqH6vcW2Ru661P86ffRzaqslNs-kDMn7B6U,5670
121
121
  verifiers/v1/harnesses/utils/mcp.py,sha256=EtDraHEqgsOB6xKvcF2z9C6HlQyKoST0ZDvmy47NWgM,7450
122
122
  verifiers/v1/harnesses/utils/replay.py,sha256=RJMzD-3K0oz_Q0zhjSH4nhwxn95R8e9Q_CCN5sZp9RA,1720
123
- verifiers/v1/interception/__init__.py,sha256=jQ9ZbUr4Nx9JFhdcx0rNcR_jkMFcdzBrTpeSFK84YF0,4020
123
+ verifiers/v1/interception/__init__.py,sha256=awL9SnoJxoi5RcloaA3BSX_75qLGRzW7yW2r6b9F9dk,4127
124
124
  verifiers/v1/interception/base.py,sha256=KlXpWgcpAs_vzJxXRTVArZ9ilSV_vNfsX6vlZ35Y7kc,2249
125
125
  verifiers/v1/interception/pool.py,sha256=Ao3iFTOcPZDfTfPH_sApVzA23u-FIaX6-FPIKOWo3c8,6701
126
- verifiers/v1/interception/server.py,sha256=m4NQTpx--TX35AWX7gR1kLOxNZiUpTCUyEVrGeBX5Ck,53496
126
+ verifiers/v1/interception/server.py,sha256=droHp39CHp4-OZiTBtdLOKU-MiPquR63OC4gRiyLPKA,47817
127
127
  verifiers/v1/interception/tunnel/__init__.py,sha256=4ZqR9F7cmLUg17qvk4sXtLpWAN4epdiMgA2l9jetMbU,721
128
128
  verifiers/v1/interception/tunnel/base.py,sha256=UrHXwbpB_qdh4WHWZHpi2D-wEHcHgg06_0U66XFqm3M,2370
129
129
  verifiers/v1/interception/tunnel/custom.py,sha256=SJ3F592zwmrLKrbNktWgkB_84Xfozf6tUWoGmWCitLk,817
@@ -135,10 +135,10 @@ verifiers/v1/judges/reference.txt,sha256=Ej35kGXiT2uJ0LcHIeez49rCS_9uHmCQKoVdn93
135
135
  verifiers/v1/judges/rubric.py,sha256=yRaOnc6S6cqrLuySkMsgxsBFCRUA2bBjYSa5qOT-inQ,16158
136
136
  verifiers/v1/judges/rubric.txt,sha256=3KA2ZeYYdcDweJhUGopxu9EFgARhu2aWft5S5cj8Bc8,323
137
137
  verifiers/v1/mcp/__init__.py,sha256=zJw_R6n-rDqB80_Zs1VGCrYVCZGi8nS7qGaSUKFsB50,479
138
- verifiers/v1/mcp/launch.py,sha256=rVslVE_aELUlgEHFMXbpsQplcr_5HLOoUxCIw8TDqr4,21736
138
+ verifiers/v1/mcp/launch.py,sha256=TLIThCxMY8pnqXAdXL0ikQ0-PmvXk5oJKOq7hUjljj8,21289
139
139
  verifiers/v1/mcp/packages.py,sha256=YIhW5wv10QrbUM1x7R3IEmEBcJu6z3547y-Ew6yJuek,10558
140
140
  verifiers/v1/mcp/server.py,sha256=9hH7rJm8yPYVitcKYMZmSt6_JQyysKAr3e6Xav6IsIk,14154
141
- verifiers/v1/mcp/toolset.py,sha256=ihU2eMkFy4ZPc0f7eG2L3-Y2UJOPo9C67moc1vK1tBc,3044
141
+ verifiers/v1/mcp/toolset.py,sha256=bkN6ZkD7K-ZzG9khh1TqayYcRKdbrVr3lJk583WxScY,3170
142
142
  verifiers/v1/runtimes/__init__.py,sha256=jyw4kuvhXCm6w4w5lNeF6eEutMe5cteRGyxG-rXHJOo,3153
143
143
  verifiers/v1/runtimes/base.py,sha256=solj-ICY6Bh2nxJobqdrINZerR8KeG-m8oKCgK9hYpg,15832
144
144
  verifiers/v1/runtimes/compose.py,sha256=Q_0auxhXaGhIOrlisFXI8QRYV9DmewVuXG4ZZtfnrKA,15974
@@ -146,7 +146,7 @@ verifiers/v1/runtimes/deployment.py,sha256=De6N15Vfe7JKn5VOqFwG22SU_lh0f09bJ57hq
146
146
  verifiers/v1/runtimes/egress.py,sha256=4zsNS3Z2A2HyoCcbgaLizA30uJabYrbgYAYUfvyzeBk,23703
147
147
  verifiers/v1/runtimes/limiters.py,sha256=RWR4HdYoa72yeWF_lM7YRLflm10euE3_gPfNG0BuaOc,2742
148
148
  verifiers/v1/runtimes/native_compose.py,sha256=8WBqWqyYWtohcrE_iq8SuuxsDFgK4Ncos8DxQS7FL_A,42335
149
- verifiers/v1/runtimes/private_network.py,sha256=69ad7-FuGOK9irTO0Iut4JQ23YQMiVzQVYbCVRmF1IM,6717
149
+ verifiers/v1/runtimes/private_network.py,sha256=DCDgg9pGaYvUoXrStLg_7PNvTZDmZ_Zxv8Mf_IAepDg,6783
150
150
  verifiers/v1/runtimes/runtime.py,sha256=1_xg9YL8BYB29L4MAJGfC9A6cXcZZ4bFBJKIuGVKyns,10309
151
151
  verifiers/v1/runtimes/strategies.py,sha256=bleJrlOnF-dOiEtdyIHHZkyGolG25DXdwCQ76s1CnCk,8790
152
152
  verifiers/v1/runtimes/backends/cli.py,sha256=f20Q4owaVVb7Z2XA60ZbvkLXP9nmcTsWWiorAx0_3U0,1585
@@ -160,7 +160,7 @@ verifiers/v1/tasksets/harbor/toolset.py,sha256=l-h1GATE9HLnEjb844CzBAiVLkPmE-Xar
160
160
  verifiers/v1/tasksets/nemo_gym/__init__.py,sha256=654gAvG3Wd_Z_nh6mypeKn4s_IIQ0Ge6vcZvxTHC2_E,306
161
161
  verifiers/v1/tasksets/nemo_gym/response.py,sha256=EhrsquEP8g0bjzAThGfE6Ypgy86_nVX235NiFYtVDVM,4463
162
162
  verifiers/v1/tasksets/nemo_gym/server.py,sha256=h7l6yWjMxGAcpYYHrxGEDuD3IpQZMygRRIFN1EMdJb8,2708
163
- verifiers/v1/tasksets/nemo_gym/taskset.py,sha256=QKRT5IPUKY7QTitZ0Q3_GaJ6TjW6nDzz5-yZ5XzrQt0,8340
163
+ verifiers/v1/tasksets/nemo_gym/taskset.py,sha256=bstrd7CNMZ7OvtET3E_wHpzM3AcqRmHlxxnjmToA4uM,8741
164
164
  verifiers/v1/tasksets/nemo_gym/toolset.py,sha256=7iaRooFIfCN16wdSJbYFAOsc9q-haTivINO4S65UY6U,3715
165
165
  verifiers/v1/tasksets/openenv/__init__.py,sha256=G726meYYDplC3QE3AyjdSShq7FUcb4NkVqowuwPPuJk,303
166
166
  verifiers/v1/tasksets/openenv/taskset.py,sha256=PzoKgoaN5DpwY1LoWoS6p1yZdC08BP2q60Cqqbl6QSs,6046
@@ -189,8 +189,8 @@ verifiers/v1/utils/scope.py,sha256=zbs4pj6AVk4jywlAJ3AX0Q0_kzB9dBB02nY-9H4ELdQ,8
189
189
  verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
190
190
  verifiers/v1/utils/trace_store.py,sha256=Qo9qvsJAl8PoRUavjQAfUB2VNxmUtYQtU2ejLKPzY9c,3382
191
191
  verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
192
- verifiers-0.4.2.dev59.dist-info/METADATA,sha256=bKbU6c9Co_ZDo9dBEALeX7wg8r4SFrAlsnrvrNB3b64,5116
193
- verifiers-0.4.2.dev59.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
194
- verifiers-0.4.2.dev59.dist-info/entry_points.txt,sha256=qdMg7ajiFpDsHf7tuPMRclJXizu1J6LTWawS5YS0B0I,137
195
- verifiers-0.4.2.dev59.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
196
- verifiers-0.4.2.dev59.dist-info/RECORD,,
192
+ verifiers-0.4.2.dev60.dist-info/METADATA,sha256=PkzNtKbolX9IZchiHaNjOGT2-2k2BiOq_AmWzjFkPwc,5116
193
+ verifiers-0.4.2.dev60.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
194
+ verifiers-0.4.2.dev60.dist-info/entry_points.txt,sha256=qdMg7ajiFpDsHf7tuPMRclJXizu1J6LTWawS5YS0B0I,137
195
+ verifiers-0.4.2.dev60.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
196
+ verifiers-0.4.2.dev60.dist-info/RECORD,,