From 14d52e047074dee31cd5b58a0a5963672610c054 Mon Sep 17 00:00:00 2001 From: krisztianfekete Date: Fri, 20 Nov 2026 12:11:01 +0100 Subject: [PATCH] feat(serve): add --api-grpc-only to expose only the gRPC API --- docs/grpc-api.md | 11 +++++++++ src/agentevals/cli.py | 50 ++++++++++++++++++++++++++++----------- tests/test_cli.py | 55 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 14 deletions(-) diff --git a/docs/grpc-api.md b/docs/grpc-api.md index 1d79269d..82266d8f 100644 --- a/docs/grpc-api.md +++ b/docs/grpc-api.md @@ -50,6 +50,7 @@ Errors use standard gRPC status codes with a `google.rpc.ErrorInfo` detail whose | Setting | Purpose | |---------|---------| | `--api-grpc-port` or `AGENTEVALS_API_GRPC_PORT` | Port, default `8002`; `0` turns the API off | +| `--api-grpc-only` or `AGENTEVALS_API_GRPC_ONLY=true` | Serve only the gRPC API on `--host`, see below | | `AGENTEVALS_GRPC_REFLECTION=true` | Turn on server reflection | | `AGENTEVALS_API_TRACES=true` | Export traces of the API server itself (see below) | @@ -57,6 +58,16 @@ Messages can be up to 16 MiB. Uploaded trace documents are limited to 10 MiB eac The Helm chart has the same switches under `grpcApi`: `enabled`, `reflection`, and `grpcReadinessProbe` to check readiness with the gRPC health service. The Service exposes the port as `grpc-api`. +### Serving only the gRPC API + +When one program is the only caller, run the server with `--api-grpc-only`. The gRPC API listens on `--host`. The web UI and REST API, both OTLP receivers and MCP listen on `127.0.0.1` only, so nothing else is reachable from the network: + +```bash +uv run agentevals serve --api-grpc-only +``` + +Check health with `grpc.health.v1` on the gRPC API port; `/api/health` is only reachable from inside the host or pod. `kubectl port-forward` still reaches the web UI, because it connects to the pod's loopback address. + ## Tracing the API server agentevals receives telemetry, so it exports none of its own by default. With `AGENTEVALS_API_TRACES=true` it traces every API call with the OpenTelemetry gRPC instrumentation, using the standard exporter variables: diff --git a/src/agentevals/cli.py b/src/agentevals/cli.py index a9a6e570..1c345ec2 100644 --- a/src/agentevals/cli.py +++ b/src/agentevals/cli.py @@ -21,6 +21,8 @@ from . import __version__ from .api.otlp_grpc import create_otlp_grpc_server, stop_otlp_grpc_server +LOOPBACK_HOST = "127.0.0.1" + def _relative_time(iso_str: str | None) -> str: """Format an ISO 8601 timestamp as a human-readable relative time string.""" @@ -541,10 +543,13 @@ async def _run_servers( otlp_grpc_port: int, *, api_grpc_port: int = 0, + api_grpc_only: bool = False, mcp_port: int | None = None, log_level: str = "warning", ) -> None: - """Start the REST API and UI, the gRPC API, the OTLP HTTP and gRPC receivers, and optional MCP.""" + """Start the REST API and UI, the gRPC API, the OTLP HTTP and gRPC receivers, and optional MCP. + + With ``api_grpc_only`` only the gRPC API binds ``host``; every other listener binds loopback.""" import uvicorn from .api.app import create_app @@ -554,8 +559,9 @@ async def _run_servers( from .api.rpc.services import Ports from .streaming.manager import LiveManager + side_host = LOOPBACK_HOST if api_grpc_only else host shared_kwargs: dict = { - "host": host, + "host": side_host, "log_level": log_level, } @@ -586,7 +592,7 @@ async def _run_servers( backend = (os.environ.get("AGENTEVALS_SERVER_URL") or f"http://127.0.0.1:{port}").rstrip("/") mcp_instance = create_mcp_server( server_url=backend, - host=host, + host=side_host, port=mcp_port, ) mcp_app = mcp_instance.streamable_http_app() @@ -594,7 +600,7 @@ async def _run_servers( mcp_uvicorn = uvicorn.Server(uvicorn.Config(mcp_app, **mcp_kwargs)) uvicorn_servers.append(mcp_uvicorn) - otlp_grpc_server = create_otlp_grpc_server(host=host, port=otlp_grpc_port, manager=mgr) + otlp_grpc_server = create_otlp_grpc_server(host=side_host, port=otlp_grpc_port, manager=mgr) await otlp_grpc_server.start() _install_shared_exit_handler( @@ -647,6 +653,16 @@ async def _run_servers( show_envvar=True, help="Port for the gRPC API (default: 8002; 0 turns it off). Expose it only to trusted callers.", ) +@click.option( + "--api-grpc-only", + is_flag=True, + envvar="AGENTEVALS_API_GRPC_ONLY", + show_envvar=True, + help=( + "Serve only the gRPC API on --host. The web UI and REST API, the OTLP receivers and MCP listen " + "on 127.0.0.1. Check health with grpc.health.v1 on the gRPC API port." + ), +) @click.option( "--mcp-port", default=None, @@ -686,6 +702,7 @@ def serve( otlp_http_port: int, otlp_grpc_port: int, api_grpc_port: int, + api_grpc_only: bool, mcp_port: int | None, eval_sets: str | None, headless: bool, @@ -698,6 +715,9 @@ def serve( """ from pathlib import Path + if api_grpc_only and not api_grpc_port: + raise click.UsageError("--api-grpc-only needs the gRPC API; set --api-grpc-port to a port other than 0") + level = logging.WARNING if verbose == 1: level = logging.INFO @@ -731,23 +751,24 @@ def serve( click.echo('MCP HTTP requires the live extras: pip install "agentevals[live]"', err=True) raise SystemExit(1) from None + side_host = LOOPBACK_HOST if api_grpc_only else host if dev: click.echo("agentevals dev server starting...") - click.echo(f" OTLP HTTP: http://{host}:{otlp_http_port} (OTEL_EXPORTER_OTLP_ENDPOINT default)") - click.echo(f" OTLP gRPC: {host}:{otlp_grpc_port} (OTEL_EXPORTER_OTLP_PROTOCOL=grpc)") - click.echo(f" API: http://{host}:{port}/api") + click.echo(f" OTLP HTTP: http://{side_host}:{otlp_http_port} (OTEL_EXPORTER_OTLP_ENDPOINT default)") + click.echo(f" OTLP gRPC: {side_host}:{otlp_grpc_port} (OTEL_EXPORTER_OTLP_PROTOCOL=grpc)") + click.echo(f" API: http://{side_host}:{port}/api") elif has_ui and not headless: - click.echo(f"agentevals: http://{host}:{port}") - click.echo(f" OTLP HTTP: http://{host}:{otlp_http_port}") - click.echo(f" OTLP gRPC: {host}:{otlp_grpc_port}") + click.echo(f"agentevals: http://{side_host}:{port}") + click.echo(f" OTLP HTTP: http://{side_host}:{otlp_http_port}") + click.echo(f" OTLP gRPC: {side_host}:{otlp_grpc_port}") else: - click.echo(f"agentevals API: http://{host}:{port}/api") - click.echo(f" OTLP HTTP: http://{host}:{otlp_http_port}") - click.echo(f" OTLP gRPC: {host}:{otlp_grpc_port}") + click.echo(f"agentevals API: http://{side_host}:{port}/api") + click.echo(f" OTLP HTTP: http://{side_host}:{otlp_http_port}") + click.echo(f" OTLP gRPC: {side_host}:{otlp_grpc_port}") if api_grpc_port: click.echo(f" gRPC API: {host}:{api_grpc_port}") if mcp_port is not None: - click.echo(f" MCP: http://{host}:{mcp_port}/mcp") + click.echo(f" MCP: http://{side_host}:{mcp_port}/mcp") if dev: click.echo(" Web UI: http://localhost:5173") if eval_sets: @@ -764,6 +785,7 @@ def serve( otlp_http_port, otlp_grpc_port, api_grpc_port=api_grpc_port, + api_grpc_only=api_grpc_only, mcp_port=mcp_port, log_level="info" if dev else "warning", ) diff --git a/tests/test_cli.py b/tests/test_cli.py index 62cf132f..8f469397 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -114,6 +114,61 @@ def fake_server_factory(config): fake_stop_grpc.assert_awaited_once_with(fake_grpc_server) +@pytest.mark.asyncio +async def test_run_servers_api_grpc_only_binds_everything_else_to_loopback(monkeypatch): + created_servers: list[_FakeUvicornServer] = [] + otlp_grpc_hosts: list[str] = [] + + def fake_create_otlp_grpc_server(*, host, port, manager): + otlp_grpc_hosts.append(host) + return _FakeGrpcServer() + + def fake_server_factory(config): + server = _FakeUvicornServer(config) + created_servers.append(server) + return server + + fake_uvicorn = ModuleType("uvicorn") + fake_uvicorn.Config = _FakeUvicornConfig + fake_uvicorn.Server = fake_server_factory + + monkeypatch.setitem(sys.modules, "uvicorn", fake_uvicorn) + monkeypatch.setattr(cli, "create_otlp_grpc_server", fake_create_otlp_grpc_server) + monkeypatch.setattr(cli, "stop_otlp_grpc_server", AsyncMock()) + + await cli._run_servers("0.0.0.0", 8001, 4318, 4317, api_grpc_port=8002, api_grpc_only=True) + + assert [s.config.kwargs["host"] for s in created_servers] == ["127.0.0.1", "127.0.0.1"] + assert otlp_grpc_hosts == ["127.0.0.1"] + api_grpc = created_servers[0].config.app.state.api_grpc + assert (api_grpc.host, api_grpc.port) == ("0.0.0.0", 8002) + + +def test_serve_api_grpc_only_needs_the_grpc_api(monkeypatch): + run_servers = AsyncMock() + monkeypatch.setattr(cli, "_run_servers", run_servers) + + result = CliRunner().invoke(cli.main, ["serve", "--api-grpc-only", "--api-grpc-port", "0"]) + + assert result.exit_code == 2 + assert "--api-grpc-only needs the gRPC API" in result.output + run_servers.assert_not_called() + + +def test_serve_api_grpc_only_from_env(monkeypatch): + for name in ("AGENTEVALS_HEADLESS", "AGENTEVALS_LIVE"): + monkeypatch.setenv(name, "") + run_servers = AsyncMock() + monkeypatch.setattr(cli, "_run_servers", run_servers) + + result = CliRunner().invoke(cli.main, ["serve", "--headless"], env={"AGENTEVALS_API_GRPC_ONLY": "true"}) + + assert result.exit_code == 0, result.output + assert run_servers.call_args.kwargs["api_grpc_only"] is True + assert "agentevals API: http://127.0.0.1:8001/api" in result.output + assert "gRPC API: 0.0.0.0:8002" in result.output + + def test_run_preserves_config_file_settings_when_flags_omitted(monkeypatch, tmp_path): trace_file = tmp_path / "trace.json" trace_file.write_text("{}", encoding="utf-8")