Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/reference/mcp-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@ async with streamablehttp_client(
| `council_set_council_enabled` | Enable or disable a dynamic council | `management_token`, `council_id`, `enabled` |
| `council_validate_catalog` | Validate the catalog and referenced profiles | optional `management_token` |

Shell authorization accepts optional `target_host`, `target_environment`,
`target_cluster`, `target_namespace`, `target_container`, and
`rollback_plan` fields. Target strings can be up to 255 characters and the
validated rollback plan can serialize to at most 8192 UTF-8 JSON bytes.
An automatic rollback plan requires at least one step.

Council review receives the target fields and the rollback strategy and steps
as requester assertions. OPA receives the target fields and a
`has_rollback_plan` flag. The flag is true whenever the requester supplies a
plan object, including one with `strategy: none`. Rollback feasibility remains
unverified. These fields follow normal Intent and audit retention, so keep
secrets out of the values. Executor routing and signed writs retain their
existing contracts. Structured tool calls cannot carry these shell fields.

Application-owned tools use a structured request instead of pretending the
tool call is a shell command. Nomos validates and snapshots `arguments`, derives
their `nomos-json-v1` SHA-256 digest, and returns a signed v2 writ bound to that
Expand Down
28 changes: 16 additions & 12 deletions nomos/llm/council_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,16 +371,20 @@ def _format_intent_for_review(intent: Intent) -> str:
wd = intent.working_directory or "*(not specified)*"
parts.append(f"**Working Directory:** {wd}")

if intent.target_host:
parts.append(f"\n**Target Host:** {intent.target_host}")
if intent.target_environment:
parts.append(f"**Target Environment:** {intent.target_environment}")
if intent.target_cluster:
parts.append(f"**Target Cluster:** {intent.target_cluster}")
if intent.target_namespace:
parts.append(f"**Target Namespace:** {intent.target_namespace}")
if intent.target_container:
parts.append(f"**Target Container:** {intent.target_container}")
deployment_target = {
"Target Host": intent.target_host,
"Target Environment": intent.target_environment,
"Target Cluster": intent.target_cluster,
"Target Namespace": intent.target_namespace,
"Target Container": intent.target_container,
}
if any(deployment_target.values()):
parts.append("\n## Deployment Target (requester assertions)")
parts.extend(
f"**{label}:** {json.dumps(_defang_agent_text(value))}"
for label, value in deployment_target.items()
if value
)

if intent.packaged_files:
parts.append("\n## Packaged Files")
Expand Down Expand Up @@ -437,11 +441,11 @@ def _format_intent_for_review(intent: Intent) -> str:
parts.append(f" - `{cmd}`")

if intent.rollback_plan:
parts.append("\n## Rollback Plan")
parts.append("\n## Rollback Plan (requester assertion)")
parts.append(f"**Strategy:** {intent.rollback_plan.strategy}")
if intent.rollback_plan.steps:
for step in intent.rollback_plan.steps:
parts.append(f" - {step}")
parts.append(f" - {json.dumps(_defang_agent_text(step))}")

# Trust comes from which channel the evidence arrived on, never from its text.
# certified_evidence_rendered is populated only by the council's verification
Expand Down
61 changes: 59 additions & 2 deletions nomos/nat/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
ConfigDict,
Field,
SerializerFunctionWrapHandler,
field_validator,
model_serializer,
model_validator,
)
Expand All @@ -51,6 +52,9 @@
INTENT_CONTEXT_MAX_LENGTH,
INTENT_DESCRIPTION_MAX_LENGTH,
INTENT_JUSTIFICATION_MAX_LENGTH,
RollbackPlan,
RollbackStrategy,
TargetEnvironment,
)
from nomos.level_0.types.packaged_file import PackagedFile
from nomos.level_0.types.writ import VoteSummary
Expand Down Expand Up @@ -517,6 +521,12 @@ class AuthorizeInput(DuplicateSafeJsonModel):
"working_directory": {"const": ""},
"env": {"maxProperties": 0},
"packaged_files": {"maxItems": 0},
"target_host": {"const": ""},
"target_environment": {"type": "null"},
"target_cluster": {"const": ""},
"target_namespace": {"const": ""},
"target_container": {"const": ""},
"rollback_plan": {"type": "null"},
},
},
]
Expand Down Expand Up @@ -550,6 +560,24 @@ class AuthorizeInput(DuplicateSafeJsonModel):
)
description: str = Field(default="", description="What the agent wants to do")
target_resource: str = Field(default="", description="The resource to act upon")
target_host: str = Field(
default="", max_length=255, description="Requester-declared shell host"
)
target_environment: TargetEnvironment | None = Field(
default=None, description="Requester-declared shell environment tier"
)
target_cluster: str = Field(
default="", max_length=255, description="Requester-declared shell cluster"
)
target_namespace: str = Field(
default="", max_length=255, description="Requester-declared shell namespace"
)
target_container: str = Field(
default="", max_length=255, description="Requester-declared shell container"
)
rollback_plan: RollbackPlan | None = Field(
default=None, description="Requester-declared shell rollback plan (up to 8192 JSON bytes)"
)
justification: str = Field(default="", description="Why this action is needed")
blast_radius: str = Field(default="", description="Scope of potential impact")
context: str = Field(default="", description="What the agent was doing before this request")
Expand All @@ -573,6 +601,18 @@ class AuthorizeInput(DuplicateSafeJsonModel):
description="Files to review and package into the execution writ",
)

@field_validator("rollback_plan")
@classmethod
def validate_rollback_plan(cls, plan: RollbackPlan | None) -> RollbackPlan | None:
if plan is None:
return None
# RollbackPlan's step validator does not run when steps are omitted.
if plan.strategy == RollbackStrategy.AUTOMATIC and not plan.steps:
raise ValueError("Automatic rollback requires at least one step")
if len(plan.model_dump_json().encode("utf-8")) > 8192:
raise ValueError("rollback_plan must serialize to at most 8192 bytes")
return plan

@model_validator(mode="before")
@classmethod
def infer_structured_api_version(cls, value: object) -> object:
Expand All @@ -594,10 +634,21 @@ def validate_operation_shape(self) -> "AuthorizeInput":
return self
if self.api_version != API_VERSION_V2:
raise ValueError("structured tool-call authorization uses api_version v2")
if self.command or self.working_directory or self.env or self.packaged_files:
if (
self.command
or self.working_directory
or self.env
or self.packaged_files
or self.target_host
or self.target_environment is not None
or self.target_cluster
or self.target_namespace
or self.target_container
or self.rollback_plan is not None
):
raise ValueError(
"structured tool-call authorization cannot include shell execution "
"or packaged-file fields"
"or packaged-file fields, including deployment context"
)
return self

Expand Down Expand Up @@ -1520,6 +1571,12 @@ def _build_authorize_intent_kwargs(input_data: AuthorizeInput, agent_id: str) ->
or input_data.working_directory
or "localhost",
"command": input_data.command,
"target_host": input_data.target_host,
"target_environment": input_data.target_environment,
"target_cluster": input_data.target_cluster,
"target_namespace": input_data.target_namespace,
"target_container": input_data.target_container,
"rollback_plan": input_data.rollback_plan,
"justification": input_data.justification,
"blast_radius": input_data.blast_radius,
"context": input_data.context,
Expand Down
115 changes: 115 additions & 0 deletions tests/test_nat_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@
import base64
import hashlib
import json
from unittest.mock import AsyncMock

import pytest

from executors.common import certify_execution_result, load_or_create_executor_identity
from nomos.auth.authenticator import AgentIdentity
from nomos.auth.writ_factory import _compute_intent_hash
from nomos.config.settings import (
CouncilMemberConfig,
CouncilSettings,
Expand All @@ -39,6 +41,7 @@
ProposeIntentInput,
WritStatusInput,
)
from nomos.opa import OPAPolicyDecision
from trusted_executor_contract import ExecutionResult, WritOfExecution

# ── Mock Backend ───────────────────────────────────────────────────────
Expand Down Expand Up @@ -146,6 +149,8 @@ def _make_settings_no_backends() -> CouncilSettings:

def _make_service_with_mock_agents(
decisions: list[str],
*,
council_key_path: str | None = None,
) -> CouncilService:
"""
Create a CouncilService with mock LLM agents.
Expand All @@ -155,6 +160,8 @@ def _make_service_with_mock_agents(
we build the service with no backends and manually inject agents.
"""
settings = _make_settings_no_backends()
if council_key_path is not None:
settings = settings.model_copy(update={"council_key_path": council_key_path})
service = CouncilService(settings)

for i, decision in enumerate(decisions):
Expand Down Expand Up @@ -994,6 +1001,114 @@ async def test_check_writ_status_rejects_non_owner(self):
class TestCouncilServiceWithAgents:
"""Tests for CouncilService with mock LLM agents."""

@pytest.mark.asyncio
@pytest.mark.parametrize(
"target",
[
{},
{"target_host": "staging-host", "target_environment": "staging"},
{
"target_environment": "development",
"target_cluster": "development-cluster",
"target_namespace": "example",
"target_container": "service",
},
],
)
async def test_shell_authorization_preserves_requester_deployment_context(
self, tmp_path, target
):
service = _make_service_with_mock_agents(["approve"], council_key_path=str(tmp_path))
reviewer = RecordingLLMBackend()
service._agents[0]._backend = reviewer
service._opa_client = AsyncMock()
service._opa_client.evaluate.return_value = OPAPolicyDecision(allow=True)
rollback = (
{"strategy": "manual", "steps": ["Reapply the previous configuration"]}
if target
else None
)

result = await service.authorize(
AuthorizeInput(
agent_id="agent-1",
command="/bin/echo deploy",
working_directory="/tmp",
justification="Test shell authorization with requester deployment context",
rollback_plan=rollback,
**target,
)
)

assert result.status == "approved", result.error
opa_intent = service._opa_client.evaluate.await_args.args[0]["intent"]
assert opa_intent["command_type"] == "shell"
assert opa_intent["shell_command_words"] == ["/bin/echo"]
assert opa_intent["has_rollback_plan"] is bool(target)
assert "rollback_plan" not in opa_intent
for name in (
"target_host",
"target_environment",
"target_cluster",
"target_namespace",
"target_container",
):
assert opa_intent[name] == target.get(name, "")
prompt = reviewer.calls[0][1].content
if target:
assert "Deployment Target (requester assertions)" in prompt
assert "Rollback Plan (requester assertion)" in prompt
for value in target.values():
assert value in prompt
assert "Reapply the previous configuration" in prompt
else:
assert "Deployment Target" not in prompt
assert "Rollback Plan" not in prompt

@pytest.mark.asyncio
@pytest.mark.parametrize(
("target", "error"),
[
({"target_host": "host-a", "target_cluster": "cluster-a"}, "both target_host"),
({"target_namespace": "example"}, "requires target_cluster"),
({"target_container": "service"}, "requires target_namespace"),
(
{"target_environment": "production", "justification": ""},
"Production actions require justification",
),
({"target_environment": "production"}, "Production actions require blast_radius"),
],
)
async def test_shell_authorization_preserves_existing_intent_target_validation(
self, tmp_path, target, error
):
service = _make_service_with_mock_agents(["approve"], council_key_path=str(tmp_path))
service._opa_client = AsyncMock()
result = await service.authorize(
AuthorizeInput(
agent_id="agent-1",
command="/bin/echo deploy",
working_directory="/tmp",
**{"justification": "Test target validation", **target},
)
)
assert result.status == "error"
assert error in result.error
service._opa_client.evaluate.assert_not_awaited()

def test_old_shell_request_preserves_writ_digest(self):
request = AuthorizeInput(
agent_id="agent-1",
command="/bin/echo deploy",
working_directory="/tmp",
)
intent = Intent(
intent_id="intent-0123456789abcdef",
**CouncilService._build_authorize_intent_kwargs(request, "agent-1"),
)
baseline_digest = "4afe1b333e619d0b1e621d935aa6053722b4bfb55dfbc6c3128cc14552b2b66d" # pragma: allowlist secret # noqa: E501
assert _compute_intent_hash(intent) == baseline_digest

@pytest.mark.asyncio
async def test_structured_tool_authorization_reviews_args_and_mints_typed_writ(self):
from nomos.auth.writ_factory import WritFactory
Expand Down
Loading
Loading