Skip to content

Commit 71e950d

Browse files
Altruistusclaude
andcommitted
CM-73403: Shorten comments
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 5f847cf commit 71e950d

9 files changed

Lines changed: 25 additions & 73 deletions

File tree

‎cycode/cli/apps/ai_guardrails/ides/cursor.py‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,6 @@ def _load_cursor_mcp_config(config_path: Optional[Path] = None) -> Optional[dict
6565

6666

6767
def _cursor_mcp_config_paths(workspace_roots: object) -> list[Path]:
68-
"""The MCP configs a Cursor session may load servers from: each project's, then the user's."""
6968
roots = workspace_roots if isinstance(workspace_roots, list) else []
7069
paths = [Path(root) / _REPO_SUBDIR / _MCP_CONFIG_FILENAME for root in roots if isinstance(root, str) and root]
7170
paths.append(_cursor_mcp_config_path())
@@ -81,13 +80,7 @@ def _server_command_line(server: dict) -> Optional[str]:
8180

8281

8382
def _resolve_mcp_server_name(raw_payload: dict) -> Optional[str]:
84-
"""The ``mcp.json`` entry name of the server a beforeMCPExecution payload called.
85-
86-
Cursor identifies the server by its ``url`` (remote servers) or ``command`` (stdio servers)
87-
rather than by the entry name the platform stores servers under, so look the entry up in the
88-
MCP configs: a url matches exactly; a command matches the entry's command line (command + args),
89-
or the entry name itself. Falls back to the raw ``command`` when no entry matches.
90-
"""
83+
"""Cursor sends the server's url or command, but the platform knows it by its mcp.json entry name."""
9184
url = raw_payload.get('url')
9285
command = raw_payload.get('command')
9386
if not url and not command:

‎cycode/cli/apps/ai_guardrails/scan/guardrail_config.py‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,7 @@
3838
)
3939
)
4040

41-
# Guardrails that are Off unless the platform switches them on for an agent. The rest default to
42-
# Report; these would otherwise start enforcing on a tenant that never looked at them.
41+
# Off by default (not Report), so they never start enforcing on a tenant that hasn't configured them.
4342
_DEFAULT_OFF_GUARDRAIL_KEYS = frozenset((BlockReason.UNAUTHORIZED_MCP_SERVER.value,))
4443

4544

@@ -48,7 +47,6 @@ def get_config_cache_path() -> Path:
4847

4948

5049
def default_mode_for(guardrail_key: str) -> str:
51-
"""A guardrail's mode for an agent the platform sent no cell for (or with no cache at all)."""
5250
if guardrail_key in _DEFAULT_OFF_GUARDRAIL_KEYS:
5351
return GuardrailCellMode.OFF.value
5452
return GuardrailCellMode.REPORT.value
@@ -78,7 +76,6 @@ def mode_for(self, guardrail_key: str, ide_name: Optional[str]) -> str:
7876
return str(agents.get((ide_name or '').lower(), default_mode_for(guardrail_key))).lower()
7977

8078
def is_off_for_every_agent(self, guardrail_key: str) -> bool:
81-
"""No agent has this guardrail on - nothing it needs has to be fetched."""
8279
agents = (self._guardrails.get(guardrail_key) or {}).get('agents') or {}
8380
return all(str(mode).lower() == GuardrailCellMode.OFF for mode in agents.values())
8481

@@ -116,10 +113,9 @@ def apply_platform_config(policy: dict, config: Optional[GuardrailConfig], ide_n
116113
"""Overlay the platform-owned enforcement config onto the local knobs-only policy.
117114
118115
The platform is the only mode source: no cache (cold start) means the built-in defaults -
119-
Report everywhere with the default globs, the unauthorized MCP server guardrail Off - which
120-
equal an unconfigured tenant's platform config, so behaviour is uniform either way. Each matrix
121-
cell lands on its own per-feature action, so the guardrails sharing an event (FileRead: content
122-
scan vs. sensitive path; McpExecution: argument scan vs. server authorization) keep independent modes.
116+
Report everywhere (unauthorized MCP server Off) with the default globs - which equal an unconfigured
117+
tenant's platform config, so behaviour is uniform either way. Each matrix cell lands on its own
118+
per-feature action, so guardrails sharing an event (e.g. the two FileRead ones) keep independent modes.
123119
An all-Off event never reaches here at all: scan_command skips it.
124120
"""
125121

‎cycode/cli/apps/ai_guardrails/scan/handlers.py‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ class _ArgScanFeature:
223223

224224

225225
class _PreScanFinding(NamedTuple):
226-
"""A guardrail that fired on the call itself, before its text is scanned (e.g. an unauthorized MCP server)."""
226+
"""A finding on the call itself (e.g. an unauthorized MCP server), made before the text scan."""
227227

228228
block_reason: BlockReason
229229
mode: GuardrailsMode
@@ -241,9 +241,7 @@ def _handle_arg_scan(
241241
) -> HookDecision:
242242
"""Shared scan + decision flow for MCP_EXECUTION and COMMAND_EXEC events.
243243
244-
A pre-scan finding in Block mode denies without scanning. In Report mode it marks the event
245-
warned and the scan still runs; a secret the scan then finds takes over the response and the
246-
event's block reason and outcome, since that is what the user is shown.
244+
A Report-mode pre-scan finding still scans, and a secret found then takes over the response.
247245
"""
248246
ai_client = ctx.obj['ai_security_client']
249247

@@ -313,10 +311,7 @@ def _handle_arg_scan(
313311

314312

315313
def _check_mcp_server_authorization(payload: AIHookPayload, policy: dict) -> Optional[_PreScanFinding]:
316-
"""The unauthorized MCP server guardrail: a finding when the called server is enforced, else None.
317-
318-
Fails open - no server name, or no cached statuses, means the server is let through.
319-
"""
314+
"""Fails open: no server name or no cached statuses lets the call through."""
320315
mcp_config = get_policy_value(policy, 'mcp', default={})
321316
if not get_policy_value(mcp_config, 'check_server', default=False):
322317
return None
@@ -333,7 +328,7 @@ def _check_mcp_server_authorization(payload: AIHookPayload, policy: dict) -> Opt
333328

334329
server = statuses.match(alias)
335330
if server is not None and server.alias.lower() != alias.lower():
336-
# A normalized or plugin-namespaced name: report the alias the platform resolves servers by.
331+
# Report the alias the platform stores, not the normalized or plugin-namespaced one.
337332
payload.mcp_server_name = server.alias
338333

339334
status = server.status if server is not None else None
@@ -361,7 +356,7 @@ def _check_mcp_server_authorization(payload: AIHookPayload, policy: dict) -> Opt
361356

362357

363358
def handle_before_mcp_execution(ctx: typer.Context, payload: AIHookPayload, policy: dict) -> HookDecision:
364-
"""Check the MCP server is authorized, then scan the tool arguments for secrets before execution."""
359+
"""Check the MCP server is authorized, then scan the tool arguments for secrets."""
365360
tool = payload.mcp_tool_name or 'unknown'
366361
args = payload.mcp_arguments or {}
367362
args_text = args if isinstance(args, str) else json.dumps(args)

‎cycode/cli/apps/ai_guardrails/scan/mcp_server_status.py‎

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
1-
"""MCP server authorization status cache, for the unauthorized MCP server guardrail.
1+
"""MCP server authorization status cache: session-start writes it, the pre-MCP-execution hook reads it.
22
3-
session-start fetches the authorization status of every MCP server the platform ingested from
4-
this user's devices (Inventory -> AI Governance) and writes it here; the pre-MCP-execution hook
5-
only reads it. An absent or corrupt cache means no status is known, so the guardrail fails open.
6-
The cache also keeps the "Unauthorized AI Entity" policy's strict-mode flag the platform returns
7-
with the statuses (whether unreviewed servers count as unauthorized).
3+
An absent or corrupt cache means no status is known, so the guardrail fails open.
84
"""
95

106
import json
@@ -24,11 +20,9 @@
2420

2521
MCP_SERVER_STATUSES_FILE_NAME = 'ai-guardrails-mcp-servers.json'
2622

27-
# The platform's response field for the strict mode, kept under the same name in the cache.
2823
TREAT_UNREVIEWED_AS_UNAUTHORIZED_KEY = 'should_treat_unreviewed_as_unauthorized'
2924

30-
# Claude Code namespaces a plugin's servers in tool names as `plugin_<plugin>_<server>`, while the
31-
# platform stores the server under its config key - the name the session sweep reported.
25+
# Claude Code names plugin servers `plugin_<plugin>_<server>` in tool names; the platform stores `<server>`.
3226
_PLUGIN_ALIAS_PREFIX = 'plugin_'
3327

3428

@@ -38,8 +32,7 @@ class McpServerAuthorizationStatus(str, Enum):
3832
UNAUTHORIZED = 'Unauthorized'
3933

4034

41-
# When one alias maps to several servers (e.g. the same name configured differently on two
42-
# devices), the most restrictive status wins.
35+
# An alias shared by several servers (e.g. configured differently per device) gets the most restrictive status.
4336
_RESTRICTIVENESS = {
4437
McpServerAuthorizationStatus.AUTHORIZED: 0,
4538
McpServerAuthorizationStatus.UNREVIEWED: 1,
@@ -52,7 +45,7 @@ def get_mcp_server_statuses_cache_path() -> Path:
5245

5346

5447
def parse_status(raw_status: object) -> McpServerAuthorizationStatus:
55-
"""Case-insensitive; an unknown status reads as Unreviewed (no decision was made on the server)."""
48+
"""An unknown status reads as Unreviewed: no decision was made on the server."""
5649
lowered = str(raw_status or '').lower()
5750
for status in McpServerAuthorizationStatus:
5851
if status.value.lower() == lowered:
@@ -61,16 +54,12 @@ def parse_status(raw_status: object) -> McpServerAuthorizationStatus:
6154

6255

6356
def _normalize_alias(alias: str) -> str:
64-
"""The form an IDE may turn a config name into inside a tool name (Claude Code keeps [A-Za-z0-9_-])."""
57+
"""Mirrors how Claude Code sanitizes a config name inside a tool name."""
6558
return re.sub(r'[^a-z0-9_-]', '_', alias.lower())
6659

6760

6861
def is_enforced(status: Optional[McpServerAuthorizationStatus], treat_unreviewed: bool) -> bool:
69-
"""Whether a server with this status (None: the platform never saw it) is enforced.
70-
71-
Unauthorized always is; Unreviewed or unknown only when the policy treats unreviewed servers as
72-
unauthorized (``treat_unreviewed``); Authorized never is.
73-
"""
62+
"""``status`` is None when the platform never saw the server."""
7463
if status == McpServerAuthorizationStatus.UNAUTHORIZED:
7564
return True
7665
return treat_unreviewed and status != McpServerAuthorizationStatus.AUTHORIZED
@@ -91,8 +80,7 @@ class McpServerStatuses:
9180
_by_alias: dict = field(init=False, repr=False)
9281

9382
def __post_init__(self) -> None:
94-
# Lowered alias -> (stored alias, most restrictive status). The platform matches aliases
95-
# case-insensitively, so the CLI does too.
83+
# The platform matches aliases case-insensitively, so the CLI does too.
9684
self._by_alias = {}
9785
for server in self.servers:
9886
if not isinstance(server, dict) or not server.get('alias'):
@@ -104,7 +92,6 @@ def __post_init__(self) -> None:
10492
self._by_alias[alias.lower()] = McpServerMatch(alias, status)
10593

10694
def match(self, alias: str) -> Optional[McpServerMatch]:
107-
"""The platform's entry for the alias a hook reported, or None when the platform has none."""
10895
exact = self._by_alias.get(alias.lower())
10996
if exact is not None:
11097
return exact
@@ -127,7 +114,6 @@ def is_expired(self) -> bool:
127114
return time.time() - self.fetched_at > self.ttl_seconds
128115

129116
def needs_refresh(self, tenant_id: Optional[str]) -> bool:
130-
"""Expired, or fetched for another tenant (the user switched tenants since)."""
131117
return self.is_expired() or self.tenant_id != tenant_id
132118

133119

@@ -137,7 +123,6 @@ def save_mcp_server_statuses(
137123
ttl_seconds: float = DEFAULT_TTL_SECONDS,
138124
treat_unreviewed_as_unauthorized: bool = False,
139125
) -> None:
140-
"""Persist fetched statuses; a failed write just leaves the previous cache in place."""
141126
path = get_mcp_server_statuses_cache_path()
142127
content = {
143128
'fetched_at': time.time(),
@@ -154,7 +139,6 @@ def save_mcp_server_statuses(
154139

155140

156141
def load_mcp_server_statuses() -> Optional[McpServerStatuses]:
157-
"""The cached statuses, or None when the cache is absent or corrupt (quarantined)."""
158142
path = get_mcp_server_statuses_cache_path()
159143
if not path.exists():
160144
return None
@@ -170,7 +154,6 @@ def load_mcp_server_statuses() -> Optional[McpServerStatuses]:
170154
fetched_at=float(content['fetched_at']),
171155
tenant_id=content.get('tenant_id'),
172156
ttl_seconds=float(content.get('ttl_seconds') or DEFAULT_TTL_SECONDS),
173-
# Missing in caches written before the flag existed: not strict.
174157
treat_unreviewed_as_unauthorized=content.get(TREAT_UNREVIEWED_AS_UNAUTHORIZED_KEY) is True,
175158
)
176159
except Exception as e:

‎cycode/cli/apps/ai_guardrails/session_start_command.py‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def _report_session_context(
9292
9393
The device context is always reported. MCP configs and skills are collected from every
9494
registered IDE, not just the triggering one. Unchanged payloads are skipped via a hash cache
95-
until the TTL expires. Returns whether a report was accepted in this call.
95+
until the TTL expires.
9696
"""
9797
try:
9898
config_files_by_ide, enabled_plugins = collect_all_session_contexts()
@@ -205,13 +205,7 @@ def _sync_guardrail_config(ai_client: 'AISecurityManagerClient', tenant_id: Opti
205205

206206

207207
def _sync_mcp_server_statuses(ai_client: 'AISecurityManagerClient', tenant_id: Optional[str], force: bool) -> None:
208-
"""Refresh the MCP server authorization statuses the unauthorized MCP server guardrail reads.
209-
210-
Fetched only while the guardrail is on for some agent. Refreshed when the cache is expired or
211-
belongs to another tenant, and whenever a changed session context was just reported (``force``):
212-
that report may have brought servers the cached statuses don't cover yet. A failed fetch keeps
213-
the previous cache.
214-
"""
208+
"""``force``: a just-reported session context may have brought servers the cache doesn't cover."""
215209
config = load_guardrail_config()
216210
if config is None or config.is_off_for_every_agent(BlockReason.UNAUTHORIZED_MCP_SERVER):
217211
logger.debug('Unauthorized MCP server guardrail is off, skipping MCP server statuses fetch')

‎cycode/cyclient/ai_security_manager_client.py‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
class McpServerStatusesResponse(NamedTuple):
1717
servers: list # [{alias, normalized_id, status}]
18-
# The "Unauthorized AI Entity" policy's strict mode: Unreviewed servers count as Unauthorized.
18+
# Strict mode: Unreviewed servers count as Unauthorized.
1919
should_treat_unreviewed_as_unauthorized: bool
2020

2121

@@ -94,8 +94,7 @@ def create_event(
9494
'mcp_tool_name': payload.mcp_tool_name,
9595
'error_message': error_message,
9696
'file_path': file_path,
97-
# The device the hook ran on, so a guardrail violation lands on it rather than on any of
98-
# the user's devices. None where no serial can be resolved (e.g. Linux).
97+
# Attributes a violation to this device; None where no serial resolves (e.g. Linux).
9998
'device_id': get_serial_number(),
10099
}
101100

@@ -115,11 +114,6 @@ def get_resolved_guardrails(self) -> Optional[dict]:
115114
return None
116115

117116
def get_mcp_server_statuses(self) -> Optional[McpServerStatusesResponse]:
118-
"""Fetch the authorization status of every MCP server on the caller's devices.
119-
120-
Returns the server rows with the policy's strict-mode flag (missing or non-boolean reads as
121-
False), or None when the fetch failed.
122-
"""
123117
try:
124118
response = self.client.get(self._build_endpoint_path(self._MCP_SERVER_STATUSES_PATH))
125119
body = response.json()

‎tests/cli/commands/ai_guardrails/scan/conftest.py‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,7 @@ def resolved_guardrails_payload(
1212
globs: Optional[list] = None,
1313
mcp_server: Optional[str] = None,
1414
) -> dict:
15-
"""A platform resolved-config payload with the given per-guardrail modes for the cursor agent.
16-
17-
The unauthorized MCP server guardrail is only in the payload when ``mcp_server`` is given.
18-
"""
15+
"""A platform resolved-config payload with the given per-guardrail modes for the cursor agent."""
1916
payload = {
2017
'ttl_seconds': 900,
2118
'guardrails': [

‎tests/cli/commands/ai_guardrails/test_session_start_command.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -785,7 +785,7 @@ def test_fresh_mcp_server_statuses_skip_the_fetch_unless_forced(
785785
_session_start_mod._sync_mcp_server_statuses(ai_client, 'tenant-b', force=False)
786786
assert ai_client.get_mcp_server_statuses.call_count == 1
787787

788-
# A just-reported session context may have brought new servers: refetch even when fresh.
788+
# A just-reported session context forces a refetch.
789789
_session_start_mod._sync_mcp_server_statuses(ai_client, 'tenant-a', force=True)
790790
assert ai_client.get_mcp_server_statuses.call_count == 2
791791

‎tests/cyclient/test_ai_security_manager_client.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def _build_client() -> tuple[AISecurityManagerClient, MagicMock]:
2020

2121
@pytest.fixture(autouse=True)
2222
def serial_number(mocker: MockerFixture) -> MagicMock:
23-
"""Resolving the real serial shells out and caches under the home directory."""
23+
"""Don't shell out for the real serial."""
2424
return mocker.patch('cycode.cyclient.ai_security_manager_client.get_serial_number', return_value='SERIAL-1')
2525

2626

0 commit comments

Comments
 (0)