Skip to content

Commit b99a151

Browse files
Merge branch 'main' into yashraj/cache-shell-flag-scope-analysis
2 parents 590c464 + 77c4a88 commit b99a151

5 files changed

Lines changed: 458 additions & 30 deletions

File tree

‎src/skillspector/allowed_tools.py‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
"""Split and validate Agent Skills ``allowed-tools`` grants.
17+
18+
A string ``allowed-tools`` value lists grants separated by commas or by
19+
whitespace. Each grant is a bare tool name (``Read``) or a scoped grant in the
20+
``Tool(specifier)`` form (``Bash(git status:*)``, ``Read(./docs, notes.md)``).
21+
As in Claude Code's permission rule syntax, parentheses inside the specifier
22+
are literal characters, not nested structure: ``Bash(echo '(')`` is a complete
23+
grant. A separator inside a specifier belongs to the specifier, so a scoped
24+
grant is kept whole and its specifier text is never read as another grant.
25+
"""
26+
27+
from __future__ import annotations
28+
29+
import re
30+
from collections.abc import Iterator
31+
32+
# Tool names longer than this are not looked up.
33+
MAX_ALLOWED_TOOL_NAME_CHARS = 64
34+
35+
_TOKENS = re.compile(r"[(),]|\s+")
36+
_NON_WHITESPACE = re.compile(r"\S")
37+
# Same tool-name alphabet as the settings permission-rule check in
38+
# ``nodes/analyzers/bundled_execution_surface.py`` (``_permission_rule_is_valid``).
39+
# Unlike that check, the specifier's parentheses do not have to balance.
40+
_TOOL_NAME = re.compile(r"[A-Za-z0-9_*.-]+")
41+
42+
43+
def _ends_specifier(value: str, end: int) -> bool:
44+
"""Return whether a ``)`` ending at ``end`` is followed by a separator or the end."""
45+
return end == len(value) or value[end] == "," or value[end].isspace()
46+
47+
48+
def _separators(value: str) -> Iterator[re.Match[str]]:
49+
"""Yield the commas and whitespace runs of ``value`` that lie outside a specifier.
50+
51+
A ``(`` outside a specifier opens one. Inside it, ``(`` and ``)`` are
52+
literal, except that a ``)`` followed by a comma, whitespace or the end of
53+
the value closes it.
54+
"""
55+
in_specifier = False
56+
for match in _TOKENS.finditer(value):
57+
token = match.group()
58+
if in_specifier:
59+
if token == ")" and _ends_specifier(value, match.end()):
60+
in_specifier = False
61+
elif token == "(":
62+
in_specifier = True
63+
elif token != ")":
64+
yield match
65+
66+
67+
def iter_allowed_tools_entries(value: str) -> Iterator[str]:
68+
"""Yield the stripped entries of a string ``allowed-tools`` value.
69+
70+
A comma outside any specifier selects the comma-separated form; otherwise
71+
entries are separated by whitespace. Only separators outside a specifier
72+
split. A specifier runs from a ``(`` to the first ``)`` that is followed by
73+
a comma, whitespace or the end of the value, and any ``(`` or ``)`` in
74+
between is literal. So ``"Bash(git status:*) Read"`` and
75+
``"Bash(echo '(') Read"`` each yield two entries, and
76+
``"Read(./docs Bash(notes).md)"`` and ``"Read(./a, b)"`` each stay one
77+
entry. A specifier whose own text has a ``)`` followed by a separator
78+
cannot be written in a string value; the list form keeps it whole. An
79+
unclosed ``(`` keeps the rest of the value in its entry, which
80+
:func:`allowed_tool_grant_name` rejects.
81+
82+
Entries are produced lazily. As with ``str.split``, the comma form yields
83+
an empty entry between adjacent commas and the whitespace form yields no
84+
empty entries; callers skip empty entries.
85+
"""
86+
comma_form = any(match.group() == "," for match in _separators(value))
87+
start = 0
88+
for match in _separators(value):
89+
if comma_form and match.group() != ",":
90+
continue
91+
entry = value[start : match.start()].strip()
92+
if entry or comma_form:
93+
yield entry
94+
start = match.end()
95+
entry = value[start:].strip()
96+
if entry or comma_form:
97+
yield entry
98+
99+
100+
def allowed_tool_grant_name(entry: str) -> str | None:
101+
"""Return the tool name of a complete ``allowed-tools`` grant, else ``None``.
102+
103+
A complete grant is either a bare tool name or ``Tool(specifier)``, where
104+
the specifier is everything between the first ``(`` and the final ``)``,
105+
which must be the last character, and is not blank. Parentheses inside the
106+
specifier are literal, so ``Bash(echo '(')`` and ``Bash(echo ')')`` are
107+
complete. Incomplete grants such as ``Bash(``, ``Bash(notes`` or
108+
``Bash(echo '('`` and blank ones such as ``Bash()`` return ``None``, so
109+
they name no tool. Names longer than :data:`MAX_ALLOWED_TOOL_NAME_CHARS`
110+
also return ``None``.
111+
"""
112+
entry = entry.strip()
113+
# Bound the search so a long specifier is not scanned for the name.
114+
paren = entry.find("(", 0, MAX_ALLOWED_TOOL_NAME_CHARS + 1)
115+
if paren == -1 and len(entry) > MAX_ALLOWED_TOOL_NAME_CHARS:
116+
return None
117+
name = entry if paren == -1 else entry[:paren]
118+
if _TOOL_NAME.fullmatch(name) is None:
119+
return None
120+
if paren == -1:
121+
return name
122+
if not entry.endswith(")") or _NON_WHITESPACE.search(entry, paren + 1, len(entry) - 1) is None:
123+
return None
124+
return name

‎src/skillspector/nodes/analyzers/mcp_least_privilege.py‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from dataclasses import dataclass, field
2323
from pathlib import Path
2424

25+
from skillspector.allowed_tools import allowed_tool_grant_name, iter_allowed_tools_entries
2526
from skillspector.inspection_ledger import (
2627
InspectionLedgerEvent,
2728
LedgerOutcome,
@@ -250,18 +251,17 @@ def _normalize_allowed_tools(
250251
251252
Accepts the list form (``[Bash, Read]``), the comma-separated string
252253
form (``"Bash, Read"``), and the space-separated string form
253-
(``"Bash Read"``). Anything else yields an empty list.
254+
(``"Bash Read"``). Separators inside a ``Tool(specifier)`` scope do not
255+
split, so ``"Bash(git status:*) Read"`` and ``"Bash(echo '(') Read"`` each
256+
yield two entries. Anything else yields an empty list.
254257
"""
255258
tools: list[str] = []
256259
if isinstance(value, list):
257260
candidates = iter(value)
258261
elif isinstance(value, str):
259-
if "," in value:
260-
# A bounded split prevents a comma-dense declaration from creating an
261-
# arbitrarily large temporary list before the analyzer can stop it.
262-
candidates = iter(value.split(",", _MAX_DECLARATION_VALUES))
263-
else:
264-
candidates = iter(value.split(None, _MAX_DECLARATION_VALUES))
262+
# Entries are produced lazily, so a comma-dense declaration stops at the
263+
# limit below without building an arbitrarily large temporary list.
264+
candidates = iter_allowed_tools_entries(value)
265265
else:
266266
return tools
267267

@@ -350,7 +350,8 @@ def _map_permissions_to_categories(
350350
return categories
351351

352352

353-
# Tool name → capability category (Claude / Agent Skills tool names, case-insensitive exact match)
353+
# Tool name → capability category (Claude / Agent Skills tool names, case-insensitive exact match
354+
# on the name of a well-formed bare or ``Tool(specifier)`` grant)
354355
_TOOL_TO_CAPABILITY: dict[str, str] = {
355356
"bash": "shell",
356357
"execute": "shell",
@@ -373,14 +374,23 @@ def _map_allowed_tools_to_categories(
373374
tools: list[str],
374375
budget: _LeastPrivilegeBudget | None = None,
375376
) -> set[str]:
376-
"""Map Agent Skills ``allowed-tools`` tool names to capability category names."""
377+
"""Map Agent Skills ``allowed-tools`` tool names to capability category names.
378+
379+
Scoped grants in the ``Tool(specifier)`` form, such as ``Bash(git:*)`` or
380+
``WebFetch(domain:example.com)``, map by their tool name, so a narrower
381+
grant covers the same category as the bare tool. Parentheses inside the
382+
specifier are literal, so ``Bash(echo '(')`` maps to ``shell``. Incomplete
383+
or blank grants such as ``Bash(``, ``Bash(notes`` or ``Bash()`` map to no
384+
category.
385+
"""
377386
categories: set[str] = set()
378387
for tool in tools:
379388
if budget is not None:
380389
budget.check_runtime("SKILL.md")
381-
if len(tool) > 64:
390+
name = allowed_tool_grant_name(tool)
391+
if name is None:
382392
continue
383-
cat = _TOOL_TO_CAPABILITY.get(tool.lower().strip())
393+
cat = _TOOL_TO_CAPABILITY.get(name.lower())
384394
if cat:
385395
categories.add(cat)
386396
return categories

‎src/skillspector/nodes/build_context.py‎

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737

3838
import yaml
3939

40+
from skillspector.allowed_tools import iter_allowed_tools_entries
4041
from skillspector.artifacts import (
4142
ArtifactDisposition,
4243
ArtifactRecord,
@@ -2429,27 +2430,16 @@ def _string_list(value: object) -> list[str]:
24292430
manifest["triggers"] = _string_list(data.get("triggers", []))
24302431
manifest["permissions"] = _string_list(data.get("permissions", []))
24312432
# `allowed-tools` (Agent Skills standard) — accept list, comma string, or space-separated string.
2433+
# Separators inside a `Tool(specifier)` scope belong to the scope, so
2434+
# `Bash(git status:*) Read` stays two grants.
24322435
allowed_tools = data.get("allowed-tools", [])
24332436
if isinstance(allowed_tools, str):
2434-
if "," in allowed_tools:
2435-
tools: list[str] = []
2436-
cursor = 0
2437-
while cursor <= len(allowed_tools):
2438-
_check()
2439-
separator = allowed_tools.find(",", cursor)
2440-
if separator < 0:
2441-
separator = len(allowed_tools)
2442-
item = allowed_tools[cursor:separator].strip()
2443-
if item:
2444-
tools.append(_scalar_text(item))
2445-
if separator == len(allowed_tools):
2446-
break
2447-
cursor = separator + 1
2448-
manifest["allowed-tools"] = tools
2449-
else:
2450-
manifest["allowed-tools"] = [
2451-
_scalar_text(t) for t in allowed_tools.split() if t.strip()
2452-
]
2437+
tools: list[str] = []
2438+
for item in iter_allowed_tools_entries(allowed_tools):
2439+
_check()
2440+
if item:
2441+
tools.append(_scalar_text(item))
2442+
manifest["allowed-tools"] = tools
24532443
elif isinstance(allowed_tools, list):
24542444
manifest["allowed-tools"] = [
24552445
item.strip() for item in _string_list(allowed_tools) if item.strip()

‎tests/nodes/test_build_context.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1250,6 +1250,65 @@ def test_build_context_parses_allowed_tools_single_space_string(tmp_path: Path)
12501250
assert result["manifest"]["allowed-tools"] == ["Bash"]
12511251

12521252

1253+
@pytest.mark.parametrize(
1254+
("declaration", "expected"),
1255+
[
1256+
pytest.param(
1257+
"Bash(git status:*) Read",
1258+
["Bash(git status:*)", "Read"],
1259+
id="space_inside_scope",
1260+
),
1261+
pytest.param(
1262+
"Bash(git status:*), Read",
1263+
["Bash(git status:*)", "Read"],
1264+
id="comma_string",
1265+
),
1266+
pytest.param(
1267+
"Read(./docs Bash(notes).md)",
1268+
["Read(./docs Bash(notes).md)"],
1269+
id="nested_parens_inside_scope",
1270+
),
1271+
pytest.param(
1272+
"Read(./docs, Bash(notes).md)",
1273+
["Read(./docs, Bash(notes).md)"],
1274+
id="comma_inside_scope",
1275+
),
1276+
pytest.param(
1277+
"Bash(git status:*) Read(./a, b)",
1278+
["Bash(git status:*)", "Read(./a, b)"],
1279+
id="comma_only_inside_scope_keeps_space_form",
1280+
),
1281+
pytest.param(
1282+
"Bash(echo '(') Read", ["Bash(echo '(')", "Read"], id="literal_open_paren_in_scope"
1283+
),
1284+
pytest.param(
1285+
"Bash(echo ')') Read", ["Bash(echo ')')", "Read"], id="literal_close_paren_in_scope"
1286+
),
1287+
pytest.param(
1288+
"Bash(echo '('), Read",
1289+
["Bash(echo '(')", "Read"],
1290+
id="comma_string_literal_open_paren_in_scope",
1291+
),
1292+
pytest.param(
1293+
"Bash(echo ')'), Read",
1294+
["Bash(echo ')')", "Read"],
1295+
id="comma_string_literal_close_paren_in_scope",
1296+
),
1297+
],
1298+
)
1299+
def test_build_context_keeps_scoped_allowed_tools_whole(
1300+
tmp_path: Path, declaration: str, expected: list[str]
1301+
) -> None:
1302+
"""Separators inside a `Tool(specifier)` scope belong to the scope."""
1303+
(tmp_path / "SKILL.md").write_text(
1304+
f"---\nname: deployer\ndescription: deploys services\nallowed-tools: {declaration}\n---\n",
1305+
encoding="utf-8",
1306+
)
1307+
state: SkillspectorState = {"skill_path": str(tmp_path)}
1308+
result = build_context(state)
1309+
assert result["manifest"]["allowed-tools"] == expected
1310+
1311+
12531312
def test_build_context_inventories_excluded_executable_descendants(tmp_path: Path) -> None:
12541313
"""Excluded trees retain bounded inventory and executable coverage evidence."""
12551314
(tmp_path / "SKILL.md").write_text("# Skill\n", encoding="utf-8")

0 commit comments

Comments
 (0)