Files
ss-tools/backend/tests/api/test_mcp_parity_baseline_037.py

298 lines
13 KiB
Python

# #region Test.McpParityBaseline037 [C:5] [TYPE Module] [SEMANTICS test,mcp,parity,rest,baseline,verification,superset,shared-fixture]
# @BRIEF Contract parity tests (050 T016/SC-002): MCP tool outputs and the REST/legacy wrappers
# are driven from one shared 037 fixture set and must agree field-by-field.
# @RELATION VERIFIES -> [McpServer.OperationsTools]
# @RELATION VERIFIES -> [Api.DashboardTesting.Candidates]
# @RELATION BINDS_TO -> [Api.DashboardTesting.CreateVerificationRun]
# @RELATION BINDS_TO -> [AgentSuperset.SqlFormat]
# @TEST_INVARIANT gate_shape_parity -> MCP gate dict validates as the REST ApprovalGateResponse model.
# @TEST_INVARIANT decision_parity -> decide outputs agree including the actor identity.
# @TEST_INVARIANT verification_parity -> same category statuses and evidence projection on both surfaces.
# @TEST_EDGE format_sql_parity -> legacy REST surface and the MCP tool return the identical string.
from __future__ import annotations
import secrets
from types import SimpleNamespace
from uuid import uuid4
import pytest
from fastapi.testclient import TestClient
from src.app import app
from src.core.auth.security import get_password_hash
from src.core.database import SessionLocal
from src.dependencies import get_current_user
from src.models.agent_run import AgentRun
from src.models.auth import McpToolInvocationRecord, Role, User
from src.schemas.dashboard_testing import ApprovalGateResponse
from .conftest import (
create_dashboard_testing_agent_run as _create_agent_run,
create_dashboard_testing_capture_artifact as _create_capture_artifact,
make_dashboard_testing_candidate_payload as _make_candidate_payload,
)
_GATE_BODY = {
"release_version": "v1.0.0",
"release_commit_hash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b",
}
# #region Test.McpParityBaseline037.Fixture [C:3] [TYPE Function]
# @ingroup Test.McpParityBaseline037
# @BRIEF One persisted admin principal shared by the REST override and the MCP token principal.
@pytest.fixture
def parity_principal():
suffix = secrets.token_hex(4)
username = f"parity-tester-{suffix}"
role_name = f"ParityAdmin-{suffix}"
role = Role(name=role_name, is_admin=True, permissions=[])
user = User(username=username, password_hash=get_password_hash("pw"), is_active=True, roles=[role])
with SessionLocal() as db:
db.add_all([user])
db.commit()
user_id = str(user.id)
override_user = SimpleNamespace(
id=user_id,
username=username,
role_name=role_name,
roles=[SimpleNamespace(is_admin=True, permissions=[])],
)
yield override_user
with SessionLocal() as db:
db.query(McpToolInvocationRecord).filter(McpToolInvocationRecord.subject == username).delete()
fresh = db.query(User).filter(User.username == username).first()
if fresh is not None:
db.delete(fresh)
db.flush()
role_row = db.query(Role).filter(Role.name == role_name).first()
if role_row is not None:
db.delete(role_row)
db.commit()
@pytest.fixture
def parity_rest_client(parity_principal, dashboard_testing_native_storage):
app.dependency_overrides[get_current_user] = lambda: parity_principal
try:
yield TestClient(app)
finally:
app.dependency_overrides.pop(get_current_user, None)
def _mcp_server_as(parity_principal):
from src.mcp_server import server as mcp_server
from src.mcp_server.server import _access_token_context
server = mcp_server._build_probe_server()
token = _access_token_context.set(mcp_server.AccessToken(
token="parity-token", client_id="parity-client", scopes=["mcp"],
subject=parity_principal.username, claims={"principal_type": "user"},
))
return server, token
def _unwrap(result):
return result[1] if isinstance(result, tuple) else result
# #endregion Test.McpParityBaseline037.Fixture
# #region Test.McpParityBaseline037.ApprovalFlow [C:5] [TYPE Function]
# @ingroup Test.McpParityBaseline037
# @BRIEF The same 037 fixture produces identical gate/decision payloads over REST and MCP.
# @TEST_EDGE one_gate_per_run -> each candidate rides its own AgentRun so both surfaces open a live gate.
def test_approval_gate_and_decision_outputs_are_parity(parity_principal, parity_rest_client) -> None:
setup_session = SessionLocal()
try:
run_a = _create_agent_run(setup_session, user_id=parity_principal.id)
run_b = _create_agent_run(setup_session, user_id=parity_principal.id, environment_id=run_a.environment_id)
run_a_id = run_a.id
run_b_id = run_b.id
artifact_a_id, sha_a = _create_capture_artifact(setup_session, run_a_id)
from src.models.agent_run import DraftArtifact
from src.models.dashboard_release import DashboardRelease
from src.schemas.dashboard_testing.catalog_revision import ExactCatalogRevision
binding_a = setup_session.get(DraftArtifact, artifact_a_id).capture_meta["catalog_binding"]
release_id = setup_session.get(DraftArtifact, artifact_a_id).capture_meta["release_id"]
release = setup_session.get(DashboardRelease, release_id)
selector = ExactCatalogRevision(kind="revision", catalog_id=binding_a["catalog_id"],
catalog_revision_id=binding_a["catalog_revision_id"])
artifact_b_id, sha_b = _create_capture_artifact(setup_session, run_b_id,
release=release, catalog_selection=selector)
binding_b = setup_session.get(DraftArtifact, artifact_b_id).capture_meta["catalog_binding"]
setup_session.commit()
finally:
setup_session.close()
payload_a = _make_candidate_payload(run_a_id, capture_artifact_ref=artifact_a_id, source_response_hash=sha_a)
payload_b = _make_candidate_payload(run_b_id, capture_artifact_ref=artifact_b_id, source_response_hash=sha_b)
candidate_a = parity_rest_client.post("/api/dashboard-testing/baseline-candidates", json=payload_a)
candidate_b = parity_rest_client.post("/api/dashboard-testing/baseline-candidates", json=payload_b)
assert candidate_a.status_code == candidate_b.status_code == 201
candidate_a_id = candidate_a.json()["candidate_id"]
candidate_b_id = candidate_b.json()["candidate_id"]
gate_body_a = {**_GATE_BODY, "agent_run_id": run_a_id}
gate_body_b = {**_GATE_BODY, "agent_run_id": run_b_id}
rest_gate_response = parity_rest_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_a_id}/approval-gate",
json=gate_body_a,
)
assert rest_gate_response.status_code == 201, rest_gate_response.text
rest_gate = rest_gate_response.json()
server, token = _mcp_server_as(parity_principal)
from src.mcp_server.server import _access_token_context
try:
mcp_gate_result = _unwrap(_mcp_call(server, "request_baseline_approval", {
"candidate_id": candidate_b_id,
"body": gate_body_b,
}))
finally:
_access_token_context.reset(token)
assert mcp_gate_result["status"] == "ok", mcp_gate_result
mcp_gate = mcp_gate_result["gate"]
assert rest_gate["catalog_binding"] == binding_a
assert mcp_gate["catalog_binding"] == binding_b
parity_fields = ("operation", "risk_level", "required_permission", "status", "reason_required", "target_paths")
for field in parity_fields:
assert mcp_gate[field] == rest_gate[field], f"gate field {field} diverges between MCP and REST"
ApprovalGateResponse(**{field: mcp_gate[field] for field in (
"gate_id", "candidate_id", "operation", "target_paths", "catalog_binding", "risk_level",
"required_permission", "status", "reason_required", "created_at",
)})
rest_decision = parity_rest_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_a_id}/approval-gate/{rest_gate['gate_id']}/decide",
json={"decision": "confirm", "reason": "Reviewed capture and provenance"},
)
assert rest_decision.status_code == 200, rest_decision.text
rest_decision_body = rest_decision.json()
server, token = _mcp_server_as(parity_principal)
try:
mcp_decision = _unwrap(_mcp_call(server, "decide_baseline_approval", {
"candidate_id": candidate_b_id,
"gate_id": mcp_gate["gate_id"],
"body": {"decision": "confirm", "reason": "Reviewed capture and provenance"},
}))
finally:
_access_token_context.reset(token)
assert mcp_decision["status"] == "ok"
assert mcp_decision["decision"]["status"] == rest_decision_body["status"] == "confirmed"
assert mcp_decision["decision"]["actor_id"] == rest_decision_body["actor_id"] == parity_principal.id
def _mcp_call(server, tool_name: str, arguments: dict) -> object:
import asyncio
return asyncio.new_event_loop().run_until_complete(server.call_tool(tool_name, arguments))
# #endregion Test.McpParityBaseline037.ApprovalFlow
# #region Test.McpParityBaseline037.VerificationFlow [C:4] [TYPE Function]
# @ingroup Test.McpParityBaseline037
# @BRIEF One verification body yields the same projection on the REST and MCP surfaces.
def test_verification_run_outputs_are_parity(
parity_principal,
parity_rest_client,
dashboard_testing_verification_repository_id: str,
) -> None:
setup_session = SessionLocal()
try:
run = _create_agent_run(setup_session, user_id=parity_principal.id, environment_id="dev")
setup_session.commit()
run_id = run.id
finally:
setup_session.close()
verification_body = {
"repository_id": dashboard_testing_verification_repository_id,
"catalog_selection": None,
"trigger": "manual",
"environment_id": "dev",
"categories": ["structure"],
"evidence_refs": {"structure": ["ev://s/diff-parity"]},
"agent_run_id": run_id,
}
rest_response = parity_rest_client.post("/api/dashboard-testing/verification-runs", json=verification_body)
assert rest_response.status_code == 201, rest_response.text
rest_run = rest_response.json()
server, token = _mcp_server_as(parity_principal)
from src.mcp_server.server import _access_token_context
try:
mcp_run = _unwrap(_mcp_call(server, "create_verification_run", {"body": verification_body}))
finally:
_access_token_context.reset(token)
assert mcp_run["status"] == "ok"
assert mcp_run["overall_status"] == rest_run["overall_status"] == "inconclusive"
assert mcp_run["created_by"] == rest_run["created_by"] == parity_principal.username
assert mcp_run["categories_run"] == rest_run["categories_run"] == ["structure"]
rest_outcome = rest_run["category_outcomes"][0]
mcp_outcome = mcp_run["category_outcomes"][0]
assert mcp_outcome["category"] == rest_outcome["category"] == "structure"
assert mcp_outcome["status"] == rest_outcome["status"] == "inconclusive"
assert mcp_outcome["evidence_refs"] == rest_outcome["evidence_refs"] == ["ev://s/diff-parity"]
# #endregion Test.McpParityBaseline037.VerificationFlow
# #region Test.McpParityBaseline037.SupersetFormat [C:4] [TYPE Function]
# @ingroup Test.McpParityBaseline037
# @BRIEF The legacy REST format path and the MCP tool project the identical formatted SQL.
# @TEST_EDGE mock_boundary -> only the [EXT:Superset] client is a double; both surfaces are real.
def test_superset_format_sql_matches_legacy_rest_surface(monkeypatch, parity_principal, parity_rest_client) -> None:
formatted_sql = "SELECT\n 1"
class _FakeSuperset:
async def format_sql(self, sql: str) -> str:
assert sql == "select 1"
return formatted_sql
async def aclose(self):
pass
async def _fake_client_factory(target) -> _FakeSuperset:
# REST route helper receives an environment id; the MCP tool passes the environment object.
environment_id = getattr(target, "id", target)
assert environment_id == "dev"
return _FakeSuperset()
from src.api.routes import agent_superset as agent_superset_routes
import src.mcp_server.ops_tools as ops_tools_module
monkeypatch.setattr(agent_superset_routes, "_get_superset_client", _fake_client_factory)
monkeypatch.setattr(ops_tools_module, "get_superset_client", _fake_client_factory)
monkeypatch.setattr(
ops_tools_module,
"get_config_manager",
lambda: SimpleNamespace(get_environment=lambda env_id: SimpleNamespace(id="dev") if env_id == "dev" else None),
)
rest_response = parity_rest_client.post(
"/api/agent/superset/sqllab/format",
params={"environment_id": "dev", "sql": "select 1"},
)
assert rest_response.status_code == 200, rest_response.text
rest_payload = rest_response.json()
assert rest_payload == {"result": formatted_sql}
server, token = _mcp_server_as(parity_principal)
from src.mcp_server.server import _access_token_context
try:
mcp_payload = _unwrap(_mcp_call(server, "superset_format_sql", {
"request": {"environment_id": "dev", "sql": "select 1"},
}))
finally:
_access_token_context.reset(token)
assert mcp_payload["status"] == "ok"
assert mcp_payload["formatted_sql"] == rest_payload["result"] == formatted_sql
# #endregion Test.McpParityBaseline037.SupersetFormat
# #endregion Test.McpParityBaseline037