shellui-django 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Shared Django libraries for Shellui services."""
2
+
3
+ __version__ = '0.1.0'
@@ -0,0 +1,27 @@
1
+ """MCP server layer for Shellui Django services."""
2
+
3
+ from shellui_django.mcp.decorators import mcp_expose_tool
4
+ from shellui_django.mcp.internal import (
5
+ APPROVAL_AUDIENCE,
6
+ APPROVAL_SCOPE,
7
+ REVOCATION_CACHE_SECONDS,
8
+ REVOCATION_LIST_SCOPE,
9
+ build_mcp_approval_assertion,
10
+ build_mcp_revocation_list_response_assertion,
11
+ parse_trusted_revocation_poll_response,
12
+ verify_mcp_internal_assertion,
13
+ verify_mcp_revocation_list_response,
14
+ )
15
+
16
+ __all__ = [
17
+ 'mcp_expose_tool',
18
+ 'APPROVAL_AUDIENCE',
19
+ 'APPROVAL_SCOPE',
20
+ 'REVOCATION_CACHE_SECONDS',
21
+ 'REVOCATION_LIST_SCOPE',
22
+ 'build_mcp_approval_assertion',
23
+ 'build_mcp_revocation_list_response_assertion',
24
+ 'parse_trusted_revocation_poll_response',
25
+ 'verify_mcp_internal_assertion',
26
+ 'verify_mcp_revocation_list_response',
27
+ ]
@@ -0,0 +1,35 @@
1
+ """Mark DRF views whose OpenAPI operations become MCP tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from functools import wraps
7
+ from typing import Any, TypeVar
8
+
9
+ MCP_TOOL_TAG = 'mcp-tools'
10
+
11
+ F = TypeVar('F', bound=Callable[..., Any])
12
+
13
+
14
+ def mcp_expose_tool(_fn: F | None = None, *, name: str | None = None, description: str | None = None) -> F | Callable[[F], F]:
15
+ """Only tagged operations are exported as MCP tools. Never tag internal or staff-only endpoints."""
16
+
17
+ def decorator(fn: F) -> F:
18
+ meta = getattr(fn, '_mcp_tool_meta', None) or {}
19
+ if name:
20
+ meta['name'] = name
21
+ if description:
22
+ meta['description'] = description
23
+ fn._mcp_tool_meta = meta # type: ignore[attr-defined]
24
+
25
+ @wraps(fn)
26
+ def wrapped(*args, **kwargs):
27
+ return fn(*args, **kwargs)
28
+
29
+ wrapped._mcp_tool_meta = meta # type: ignore[attr-defined]
30
+ wrapped._mcp_expose_tool = True # type: ignore[attr-defined]
31
+ return wrapped # type: ignore[return-value]
32
+
33
+ if _fn is not None:
34
+ return decorator(_fn)
35
+ return decorator
@@ -0,0 +1,109 @@
1
+ """Thread-safe Identity JWKS fetch and RS256 JWT verification (no SimpleJWT)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import threading
7
+ import time
8
+ import urllib.error
9
+ import urllib.request
10
+ from typing import Any
11
+
12
+ import jwt
13
+ from jwt.algorithms import RSAAlgorithm
14
+
15
+ _CACHE_TTL_SECONDS = 300
16
+ _cache_lock = threading.Lock()
17
+ _jwks_cache: dict[str, tuple[float, dict[str, Any]]] = {}
18
+
19
+
20
+ class IdentityJwksError(Exception):
21
+ pass
22
+
23
+
24
+ def identity_jwks_url_for_issuer(issuer: str) -> str:
25
+ base = (issuer or '').strip().rstrip('/')
26
+ if not base:
27
+ raise IdentityJwksError('Identity issuer is required.')
28
+ return f'{base}/.well-known/jwks.json'
29
+
30
+
31
+ def _fetch_jwks_document(url: str, *, timeout: float) -> dict[str, Any]:
32
+ request = urllib.request.Request(url, headers={'Accept': 'application/json'})
33
+ try:
34
+ with urllib.request.urlopen(request, timeout=timeout) as response:
35
+ raw = response.read()
36
+ except (urllib.error.URLError, TimeoutError) as exc:
37
+ raise IdentityJwksError('Failed to fetch Identity JWKS.') from exc
38
+ try:
39
+ document = json.loads(raw.decode('utf-8'))
40
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
41
+ raise IdentityJwksError('Identity JWKS response was not JSON.') from exc
42
+ if not isinstance(document, dict) or not isinstance(document.get('keys'), list):
43
+ raise IdentityJwksError('Identity JWKS document is invalid.')
44
+ return document
45
+
46
+
47
+ def get_jwks_document(*, jwks_url: str | None = None, jwks: dict[str, Any] | None = None, timeout: float = 10.0) -> dict[str, Any]:
48
+ if jwks is not None:
49
+ if not isinstance(jwks.get('keys'), list):
50
+ raise IdentityJwksError('Inline JWKS document is invalid.')
51
+ return jwks
52
+ if not jwks_url:
53
+ raise IdentityJwksError('identity_jwks_url or jwks is required.')
54
+ now = time.monotonic()
55
+ with _cache_lock:
56
+ cached = _jwks_cache.get(jwks_url)
57
+ if cached and now - cached[0] < _CACHE_TTL_SECONDS:
58
+ return cached[1]
59
+ document = _fetch_jwks_document(jwks_url, timeout=timeout)
60
+ with _cache_lock:
61
+ _jwks_cache[jwks_url] = (now, document)
62
+ return document
63
+
64
+
65
+ def _public_key_from_jwk(jwk: dict[str, Any]):
66
+ if jwk.get('kty') != 'RSA':
67
+ raise IdentityJwksError('Unsupported JWK type.')
68
+ return RSAAlgorithm.from_jwk(json.dumps(jwk))
69
+
70
+
71
+ def resolve_verification_key(token: str, jwks_document: dict[str, Any]):
72
+ header = jwt.get_unverified_header(token)
73
+ kid = header.get('kid')
74
+ keys = jwks_document.get('keys') or []
75
+ candidates = [item for item in keys if isinstance(item, dict)]
76
+ if kid:
77
+ for jwk in candidates:
78
+ if jwk.get('kid') == kid:
79
+ return _public_key_from_jwk(jwk)
80
+ if len(candidates) == 1:
81
+ return _public_key_from_jwk(candidates[0])
82
+ raise IdentityJwksError('No matching JWKS key for revocation assertion.')
83
+
84
+
85
+ def decode_identity_rs256_jwt(
86
+ token: str,
87
+ *,
88
+ audience: str,
89
+ issuer: str,
90
+ jwks_url: str | None = None,
91
+ jwks: dict[str, Any] | None = None,
92
+ timeout: float = 10.0,
93
+ ) -> dict[str, Any]:
94
+ header = jwt.get_unverified_header(token)
95
+ if header.get('alg') != 'RS256':
96
+ raise IdentityJwksError('Identity JWT must use RS256.')
97
+ document = get_jwks_document(jwks_url=jwks_url, jwks=jwks, timeout=timeout)
98
+ key = resolve_verification_key(token, document)
99
+ try:
100
+ return jwt.decode(
101
+ token,
102
+ key=key,
103
+ algorithms=['RS256'],
104
+ audience=audience,
105
+ issuer=issuer,
106
+ options={'require': ['exp', 'iat', 'sub', 'scope']},
107
+ )
108
+ except jwt.PyJWTError as exc:
109
+ raise IdentityJwksError('Invalid Identity JWT.') from exc
@@ -0,0 +1,264 @@
1
+ """Signed internal calls between Shellui services (approval requests, call logs)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ import uuid
7
+ from typing import Any
8
+
9
+ import jwt
10
+ from django.conf import settings
11
+ from rest_framework_simplejwt.settings import api_settings
12
+
13
+
14
+ def _identity_issuer() -> str:
15
+ return (api_settings.ISSUER or getattr(settings, 'JWT_ISSUER', None) or '').strip()
16
+
17
+ APPROVAL_AUDIENCE = 'shellui-mcp-approval'
18
+ APPROVAL_SCOPE = 'mcp.approval.create'
19
+ CALL_LOG_AUDIENCE = 'shellui-mcp-call-log'
20
+ CALL_LOG_SCOPE = 'mcp.call_log.create'
21
+ REVOCATION_AUDIENCE = 'shellui-mcp-revocation'
22
+ REVOCATION_SCOPE = 'mcp.revocation.read'
23
+ REVOCATION_LIST_SCOPE = 'mcp.revocation.list'
24
+ REVOCATION_CACHE_SECONDS = 30
25
+ REVOCATION_LIST_ASSERTION_LIFETIME_SECONDS = REVOCATION_CACHE_SECONDS
26
+
27
+
28
+ class InternalAssertionError(Exception):
29
+ def __init__(self, message: str, *, status: int = 401):
30
+ super().__init__(message)
31
+ self.message = message
32
+ self.status = status
33
+
34
+
35
+ def _encode_assertion(claims: dict[str, Any]) -> str:
36
+ headers = {}
37
+ kid = getattr(settings, 'JWT_ACTIVE_KEY_ID', '')
38
+ if kid:
39
+ headers['kid'] = kid
40
+ token = jwt.encode(claims, api_settings.SIGNING_KEY, algorithm=api_settings.ALGORITHM, headers=headers or None)
41
+ return token.decode('utf-8') if isinstance(token, bytes) else token
42
+
43
+
44
+ def build_mcp_approval_assertion(
45
+ *,
46
+ company_id: int,
47
+ agent_id: str,
48
+ service: str,
49
+ action: str,
50
+ arguments_hash: str,
51
+ audience_url: str,
52
+ lifetime_seconds: int = 60,
53
+ ) -> str:
54
+ now = int(time.time())
55
+ claims = {
56
+ 'iss': api_settings.ISSUER or '',
57
+ 'aud': APPROVAL_AUDIENCE,
58
+ 'sub': f'agent:{agent_id}',
59
+ 'scope': APPROVAL_SCOPE,
60
+ 'company_id': company_id,
61
+ 'agent_id': agent_id,
62
+ 'service': service,
63
+ 'action': action,
64
+ 'arguments_hash': arguments_hash,
65
+ 'target': audience_url,
66
+ 'iat': now,
67
+ 'exp': now + lifetime_seconds,
68
+ 'jti': uuid.uuid4().hex,
69
+ }
70
+ return _encode_assertion(claims)
71
+
72
+
73
+ def _encode_identity_issued_rs256(claims: dict[str, Any]) -> str | None:
74
+ signing = getattr(settings, 'JWT_SIGNING_KEY', None)
75
+ if signing is None:
76
+ return None
77
+ private_pem = getattr(signing, 'private_pem', None)
78
+ if not private_pem:
79
+ return None
80
+ kid = getattr(signing, 'kid', None) or getattr(settings, 'JWT_ACTIVE_KEY_ID', '') or ''
81
+ headers = {'kid': kid} if kid else None
82
+ token = jwt.encode(claims, private_pem, algorithm='RS256', headers=headers)
83
+ return token.decode('utf-8') if isinstance(token, bytes) else token
84
+
85
+
86
+ def build_mcp_revocation_list_response_assertion(
87
+ *,
88
+ revoked_agent_ids: list[str],
89
+ agents: list[dict[str, Any]] | None = None,
90
+ cache_seconds: int = REVOCATION_CACHE_SECONDS,
91
+ lifetime_seconds: int = REVOCATION_LIST_ASSERTION_LIFETIME_SECONDS,
92
+ ) -> str:
93
+ """Identity signs revocation poll responses so services can fail closed on tampering."""
94
+ now = int(time.time())
95
+ agent_rows = agents or []
96
+ claims = {
97
+ 'iss': _identity_issuer(),
98
+ 'aud': REVOCATION_AUDIENCE,
99
+ 'sub': 'identity',
100
+ 'scope': REVOCATION_LIST_SCOPE,
101
+ 'revoked_agent_ids': [str(item) for item in revoked_agent_ids],
102
+ 'agents': agent_rows,
103
+ 'cache_seconds': int(cache_seconds),
104
+ 'iat': now,
105
+ 'exp': now + lifetime_seconds,
106
+ 'jti': uuid.uuid4().hex,
107
+ }
108
+ rs256 = _encode_identity_issued_rs256(claims)
109
+ if not rs256:
110
+ raise InternalAssertionError(
111
+ 'Revocation list signing is not configured.',
112
+ status=503,
113
+ )
114
+ return rs256
115
+
116
+
117
+ def build_mcp_revocation_assertion(*, audience_url: str, lifetime_seconds: int = 60) -> str:
118
+ now = int(time.time())
119
+ claims = {
120
+ 'iss': api_settings.ISSUER or '',
121
+ 'aud': REVOCATION_AUDIENCE,
122
+ 'sub': 'service',
123
+ 'scope': REVOCATION_SCOPE,
124
+ 'target': audience_url,
125
+ 'iat': now,
126
+ 'exp': now + lifetime_seconds,
127
+ 'jti': uuid.uuid4().hex,
128
+ }
129
+ return _encode_assertion(claims)
130
+
131
+
132
+ def build_mcp_call_log_assertion(*, audience_url: str, lifetime_seconds: int = 60) -> str:
133
+ now = int(time.time())
134
+ claims = {
135
+ 'iss': api_settings.ISSUER or '',
136
+ 'aud': CALL_LOG_AUDIENCE,
137
+ 'sub': 'service',
138
+ 'scope': CALL_LOG_SCOPE,
139
+ 'target': audience_url,
140
+ 'iat': now,
141
+ 'exp': now + lifetime_seconds,
142
+ 'jti': uuid.uuid4().hex,
143
+ }
144
+ return _encode_assertion(claims)
145
+
146
+
147
+ def verify_mcp_internal_assertion(
148
+ raw_token: str,
149
+ *,
150
+ expected_audience: str,
151
+ expected_scope: str,
152
+ expected_target: str | None = None,
153
+ ) -> dict[str, Any]:
154
+ if not raw_token or not raw_token.strip():
155
+ raise InternalAssertionError('Missing assertion.')
156
+ token = raw_token.strip()
157
+ if token.lower().startswith('bearer '):
158
+ token = token[7:].strip()
159
+ try:
160
+ payload = jwt.decode(
161
+ token,
162
+ api_settings.SIGNING_KEY,
163
+ algorithms=[api_settings.ALGORITHM],
164
+ audience=expected_audience,
165
+ issuer=api_settings.ISSUER or None,
166
+ options={'require': ['exp', 'iat', 'sub', 'scope']},
167
+ )
168
+ except jwt.PyJWTError as exc:
169
+ raise InternalAssertionError('Invalid assertion.') from exc
170
+ scope = str(payload.get('scope') or '')
171
+ if scope != expected_scope:
172
+ raise InternalAssertionError('Assertion scope mismatch.')
173
+ if expected_target:
174
+ target = str(payload.get('target') or '').rstrip('/')
175
+ if target and target != expected_target.rstrip('/'):
176
+ raise InternalAssertionError('Assertion target mismatch.')
177
+ if payload.get('agent_id') or payload.get('pat_id') or payload.get('user_id'):
178
+ pass
179
+ return payload
180
+
181
+
182
+ def _revocation_list_assertion_token(payload: dict[str, Any]) -> str:
183
+ token = payload.get('revocation_assertion') or payload.get('assertion')
184
+ if not token or not str(token).strip():
185
+ raise InternalAssertionError('Missing revocation list assertion.')
186
+ return str(token).strip()
187
+
188
+
189
+ def verify_mcp_revocation_list_response(
190
+ payload: dict[str, Any],
191
+ *,
192
+ expected_issuer: str,
193
+ identity_jwks_url: str | None = None,
194
+ jwks: dict[str, Any] | None = None,
195
+ jwks_timeout: float = 10.0,
196
+ ) -> dict[str, Any]:
197
+ """Verify Identity's signed revocation poll response via RS256 JWKS; raises when untrusted."""
198
+ from shellui_django.mcp.identity_jwks import (
199
+ IdentityJwksError,
200
+ decode_identity_rs256_jwt,
201
+ identity_jwks_url_for_issuer,
202
+ )
203
+
204
+ token = _revocation_list_assertion_token(payload)
205
+ issuer = (expected_issuer or '').strip().rstrip('/')
206
+ if not issuer:
207
+ raise InternalAssertionError('expected_issuer is required.')
208
+ jwks_url = identity_jwks_url or identity_jwks_url_for_issuer(issuer)
209
+ try:
210
+ claims = decode_identity_rs256_jwt(
211
+ token,
212
+ audience=REVOCATION_AUDIENCE,
213
+ issuer=issuer,
214
+ jwks_url=jwks_url,
215
+ jwks=jwks,
216
+ timeout=jwks_timeout,
217
+ )
218
+ except IdentityJwksError as exc:
219
+ raise InternalAssertionError(str(exc)) from exc
220
+ if str(claims.get('scope') or '') != REVOCATION_LIST_SCOPE:
221
+ raise InternalAssertionError('Revocation list scope mismatch.')
222
+ if str(claims.get('sub') or '') != 'identity':
223
+ raise InternalAssertionError('Revocation list issuer subject mismatch.')
224
+ claimed_ids = [str(item) for item in (claims.get('revoked_agent_ids') or [])]
225
+ claimed_cache = int(claims.get('cache_seconds') or 0)
226
+ body_ids = payload.get('revoked_agent_ids')
227
+ if body_ids is not None:
228
+ normalized_body = [str(item) for item in body_ids]
229
+ if normalized_body != claimed_ids:
230
+ raise InternalAssertionError('Revocation list body mismatch.')
231
+ body_cache = payload.get('cache_seconds')
232
+ if body_cache is not None and int(body_cache) != claimed_cache:
233
+ raise InternalAssertionError('Revocation list cache mismatch.')
234
+ claimed_agents = claims.get('agents') or []
235
+ body_agents = payload.get('agents')
236
+ if body_agents is not None and body_agents != claimed_agents:
237
+ raise InternalAssertionError('Revocation list agents mismatch.')
238
+ return {
239
+ 'revoked_agent_ids': claimed_ids,
240
+ 'agents': claimed_agents,
241
+ 'cache_seconds': claimed_cache,
242
+ }
243
+
244
+
245
+ def parse_trusted_revocation_poll_response(
246
+ payload: dict[str, Any],
247
+ *,
248
+ expected_issuer: str,
249
+ identity_jwks_url: str | None = None,
250
+ jwks: dict[str, Any] | None = None,
251
+ jwks_timeout: float = 10.0,
252
+ ) -> tuple[frozenset[str], int, list[dict[str, Any]]]:
253
+ """Return trusted revoked ids, cache TTL, and agent rows; fail closed on any problem."""
254
+ trusted = verify_mcp_revocation_list_response(
255
+ payload,
256
+ expected_issuer=expected_issuer,
257
+ identity_jwks_url=identity_jwks_url,
258
+ jwks=jwks,
259
+ jwks_timeout=jwks_timeout,
260
+ )
261
+ ids = frozenset(trusted['revoked_agent_ids'])
262
+ cache_seconds = int(trusted['cache_seconds'] or REVOCATION_CACHE_SECONDS)
263
+ agents = list(trusted.get('agents') or [])
264
+ return ids, cache_seconds, agents
@@ -0,0 +1,78 @@
1
+ """Redact secrets and personal data from MCP tool arguments and responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+
8
+ _SECRET_KEY_RE = re.compile(
9
+ r'(password|secret|token|authorization|api[_-]?key|private[_-]?key|credential|magic[_-]?link)',
10
+ re.I,
11
+ )
12
+ _EMAIL_RE = re.compile(r'[^@]+@[^@]+\.[^@]+')
13
+ _REDACTED = '[redacted]'
14
+
15
+
16
+ def _node_for_key(markers: dict[str, Any], key: str) -> dict[str, Any]:
17
+ node = markers.get(key)
18
+ if isinstance(node, dict):
19
+ return node
20
+ return {'secret': False, 'sensitive': False, 'children': {}}
21
+
22
+
23
+ def _should_redact_key(
24
+ key: str,
25
+ *,
26
+ read_sensitive: bool,
27
+ node: dict[str, Any],
28
+ ) -> bool:
29
+ if str(key).endswith('_hint'):
30
+ return True
31
+ if node.get('secret'):
32
+ return True
33
+ if _SECRET_KEY_RE.search(str(key)):
34
+ return True
35
+ if not read_sensitive and node.get('sensitive'):
36
+ return True
37
+ return False
38
+
39
+
40
+ def _redact_scalar(key: str, value: Any, *, read_sensitive: bool, node: dict[str, Any]) -> Any:
41
+ if _should_redact_key(key, read_sensitive=read_sensitive, node=node):
42
+ return _REDACTED
43
+ if not read_sensitive and isinstance(value, str) and _EMAIL_RE.search(value):
44
+ return _REDACTED
45
+ return value
46
+
47
+
48
+ def _redact_value(
49
+ key: str,
50
+ value: Any,
51
+ *,
52
+ read_sensitive: bool,
53
+ markers: dict[str, Any],
54
+ ) -> Any:
55
+ node = _node_for_key(markers, key)
56
+ if isinstance(value, dict):
57
+ return redact_mapping(value, read_sensitive=read_sensitive, markers=node.get('children') or {})
58
+ if isinstance(value, list):
59
+ child_markers = node.get('children') or {}
60
+ return [
61
+ _redact_value(key, item, read_sensitive=read_sensitive, markers=child_markers) for item in value
62
+ ]
63
+ return _redact_scalar(key, value, read_sensitive=read_sensitive, node=node)
64
+
65
+
66
+ def redact_mapping(
67
+ data: dict[str, Any] | None,
68
+ *,
69
+ read_sensitive: bool,
70
+ markers: dict[str, Any] | None = None,
71
+ ) -> dict[str, Any]:
72
+ if not data:
73
+ return {}
74
+ field_markers = markers or {}
75
+ out: dict[str, Any] = {}
76
+ for key, value in data.items():
77
+ out[key] = _redact_value(str(key), value, read_sensitive=read_sensitive, markers=field_markers)
78
+ return out
@@ -0,0 +1,135 @@
1
+ """OpenAPI ``x-mcp`` tool metadata shared across Shellui services."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from shellui_django.mcp.write_gate import is_destructive_operation
8
+
9
+
10
+ class McpSchemaValidationError(ValueError):
11
+ pass
12
+
13
+
14
+ def mcp_extension(operation: dict[str, Any]) -> dict[str, Any] | None:
15
+ raw = operation.get('x-mcp')
16
+ if isinstance(raw, dict):
17
+ return raw
18
+ extensions = operation.get('extensions') or {}
19
+ nested = extensions.get('x-mcp')
20
+ return nested if isinstance(nested, dict) else None
21
+
22
+
23
+ def tool_access_flags(operation: dict[str, Any] | None) -> dict[str, bool]:
24
+ if not operation:
25
+ return {'read_only': False, 'destructive': False, 'tagged': False}
26
+ ext = mcp_extension(operation)
27
+ if ext is None:
28
+ return {
29
+ 'read_only': False,
30
+ 'destructive': is_destructive_operation(operation),
31
+ 'tagged': False,
32
+ }
33
+ return {
34
+ 'read_only': bool(ext.get('read_only')),
35
+ 'destructive': bool(ext.get('destructive')) or is_destructive_operation(operation),
36
+ 'tagged': True,
37
+ }
38
+
39
+
40
+ def validate_read_only_post_tools(schema: dict[str, Any], *, allowlist: frozenset[str]) -> None:
41
+ """POST operations tagged ``x-mcp.read_only`` must appear on the service allowlist."""
42
+ paths = schema.get('paths') or {}
43
+ violations: list[str] = []
44
+ for path_item in paths.values():
45
+ if not isinstance(path_item, dict):
46
+ continue
47
+ for method, operation in path_item.items():
48
+ if str(method).upper() != 'POST' or not isinstance(operation, dict):
49
+ continue
50
+ ext = mcp_extension(operation)
51
+ if not ext or not ext.get('read_only'):
52
+ continue
53
+ op_id = str(operation.get('operationId') or '')
54
+ if not op_id or op_id not in allowlist:
55
+ violations.append(op_id or f'<missing operationId> @ {method}')
56
+ if violations:
57
+ raise McpSchemaValidationError(
58
+ 'POST tools tagged x-mcp.read_only must be listed in the read-only POST allowlist: '
59
+ + ', '.join(sorted(violations))
60
+ )
61
+
62
+
63
+ def _resolve_schema(schema: dict[str, Any] | None, components: dict[str, Any]) -> dict[str, Any]:
64
+ if not schema or not isinstance(schema, dict):
65
+ return {}
66
+ ref = schema.get('$ref')
67
+ if ref and ref.startswith('#/components/schemas/'):
68
+ name = ref.rsplit('/', 1)[-1]
69
+ target = (components.get('schemas') or {}).get(name)
70
+ if isinstance(target, dict):
71
+ return _resolve_schema(target, components)
72
+ return schema
73
+
74
+
75
+ def _merge_property_markers(
76
+ props: dict[str, Any],
77
+ components: dict[str, Any],
78
+ into: dict[str, Any],
79
+ ) -> None:
80
+ for key, field in props.items():
81
+ if not isinstance(field, dict):
82
+ continue
83
+ field = _resolve_schema(field, components)
84
+ node = into.setdefault(str(key), {'secret': False, 'sensitive': False, 'children': {}})
85
+ if field.get('x-mcp-secret') is True:
86
+ node['secret'] = True
87
+ if field.get('x-mcp-sensitive') is True:
88
+ node['sensitive'] = True
89
+ nested = field.get('properties')
90
+ if isinstance(nested, dict):
91
+ _merge_property_markers(nested, components, node['children'])
92
+ items = field.get('items')
93
+ if isinstance(items, dict):
94
+ item_schema = _resolve_schema(items, components)
95
+ item_props = item_schema.get('properties')
96
+ if isinstance(item_props, dict):
97
+ _merge_property_markers(item_props, components, node['children'])
98
+
99
+
100
+ def marker_tree_for_schema(schema: dict[str, Any] | None, root_schema: dict[str, Any]) -> dict[str, Any]:
101
+ components = (root_schema.get('components') or {}).get('schemas') or {}
102
+ resolved = _resolve_schema(schema, {'schemas': components})
103
+ tree: dict[str, Any] = {}
104
+ props = resolved.get('properties')
105
+ if isinstance(props, dict):
106
+ _merge_property_markers(props, {'schemas': components}, tree)
107
+ return tree
108
+
109
+
110
+ def marker_tree_for_operation_request(operation: dict[str, Any] | None, root_schema: dict[str, Any]) -> dict[str, Any]:
111
+ if not operation:
112
+ return {}
113
+ body = operation.get('requestBody') or {}
114
+ content = body.get('content') or {} if isinstance(body, dict) else {}
115
+ json_schema = content.get('application/json', {}).get('schema') if isinstance(content, dict) else None
116
+ return marker_tree_for_schema(json_schema if isinstance(json_schema, dict) else None, root_schema)
117
+
118
+
119
+ def marker_tree_for_operation_response(operation: dict[str, Any] | None, root_schema: dict[str, Any]) -> dict[str, Any]:
120
+ if not operation:
121
+ return {}
122
+ responses = operation.get('responses') or {}
123
+ if not isinstance(responses, dict):
124
+ return {}
125
+ for status_code in ('200', '201', '202', '204'):
126
+ response = responses.get(status_code)
127
+ if not isinstance(response, dict):
128
+ continue
129
+ content = response.get('content') or {}
130
+ if not isinstance(content, dict):
131
+ continue
132
+ json_schema = content.get('application/json', {}).get('schema')
133
+ if isinstance(json_schema, dict):
134
+ return marker_tree_for_schema(json_schema, root_schema)
135
+ return {}