shellui-django 0.5.1__tar.gz → 0.6.0__tar.gz
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.
- {shellui_django-0.5.1 → shellui_django-0.6.0}/CHANGELOG.md +36 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/PKG-INFO +1 -1
- {shellui_django-0.5.1 → shellui_django-0.6.0}/pyproject.toml +1 -1
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/__init__.py +1 -1
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/gateway.py +22 -22
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/identity_jwks.py +74 -5
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/internal.py +2 -1
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/routing.py +57 -1
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/server.py +176 -24
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/mcp_routing_urlconf.py +11 -2
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/rs256_helpers.py +27 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_gateway.py +74 -43
- shellui_django-0.6.0/src/shellui_django/mcp/tests/test_identity_jwks_fetch.py +110 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_internal_assertions.py +20 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_routing.py +28 -1
- shellui_django-0.6.0/src/shellui_django/mcp/tests/test_server_hardening.py +257 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_server_routing.py +31 -7
- {shellui_django-0.5.1 → shellui_django-0.6.0}/.gitignore +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/LICENSE +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/README.md +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/SECURITY.md +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/__init__.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/decorators.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/delegation.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/masking.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/openapi_mcp.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/openapi_tools.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/rate_limit.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/resources.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/__init__.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_approval_authority.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_delegation.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_identity_jwks_decode.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_internal_revocation.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_masking.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_openapi_tools.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_package.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_resources.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/test_write_gate_mcp.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/write_gate.py +0 -0
- {shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/testing/__init__.py +0 -0
|
@@ -23,6 +23,42 @@ Breaking changes bump the major version (minor while below 1.0.0), so services c
|
|
|
23
23
|
See for sample https://raw.githubusercontent.com/favoloso/conventional-changelog-emoji/master/CHANGELOG.md
|
|
24
24
|
-->
|
|
25
25
|
|
|
26
|
+
## [0.6.0] - 2026-11-21
|
|
27
|
+
|
|
28
|
+
Breaking: services must pass the new `McpServer` settings listed under Changed before upgrading.
|
|
29
|
+
|
|
30
|
+
### 🛠 Improvements
|
|
31
|
+
|
|
32
|
+
- MCP `tools/call` checks tenant fields (`company_id`, `companyId`, `company-id`) in tool arguments, including nested objects, against the verified token `company_id`. The aggregating gateway applies the same check before it forwards a call. `0` is a real company id.
|
|
33
|
+
- `McpServer.handle` verifies the bearer token (RS256, `identity_issuer`, `mcp_audience`, JWKS) and authenticates the inner view with those claims.
|
|
34
|
+
- `identity_revocation_check` runs on every request. A missing hook, or a hook that raises, is rejected with HTTP 403 `revocation_unavailable`.
|
|
35
|
+
- Identity JWKS fetch uses the configured URL only: redirects are not followed, `https` is required unless Django `DEBUG` is true, other schemes are rejected, the body is capped at 256 KiB, and the timeout must be positive (default 10 seconds).
|
|
36
|
+
- Internal assertion verification requires `target` to equal `expected_target`. An empty or missing `target` does not match.
|
|
37
|
+
- `mcp_gateway_delegated` skips a second approval only for the tool named in `action` while `exp` is still in the future.
|
|
38
|
+
|
|
39
|
+
### 🚨 Changed
|
|
40
|
+
|
|
41
|
+
- `McpServer` needs `identity_issuer`, `mcp_audience`, and `identity_jwks` or `identity_jwks_url`, plus `identity_revocation_check`. `handle` does not authorize from the `agent_claims` argument. Inner `request.user` is the verified agent principal, and `request.auth` is the verified claims.
|
|
42
|
+
- `mcp_gateway_delegated` must be an object `{"action": "<tool name>", "exp": <unix seconds>}`. A boolean value does not skip approval.
|
|
43
|
+
- JWKS clients that used plain `http` while `DEBUG` is false, or that followed a redirect, now get an error from `get_jwks_document`.
|
|
44
|
+
|
|
45
|
+
### 🏗 Chore
|
|
46
|
+
|
|
47
|
+
- PyPI publishing checks that the release tag matches the package version before upload.
|
|
48
|
+
|
|
49
|
+
## [0.5.3] - 2026-11-11
|
|
50
|
+
|
|
51
|
+
### 🐛 Bug Fixes
|
|
52
|
+
|
|
53
|
+
- MCP `tools/call`: honor `mcp_gateway_delegated` on agent tokens so downstream services do not open a second human approval after the AI company gateway already approved and consumed the grant.
|
|
54
|
+
|
|
55
|
+
## [0.5.2] - 2026-11-11
|
|
56
|
+
|
|
57
|
+
### 🐛 Bug Fixes
|
|
58
|
+
|
|
59
|
+
- MCP `tools/list`: keep registry `_meta` (path, method, read_only, destructive) on the wire. Services publish flat agent schemas without transport arguments; the AI gateway needs `_meta` to route `tools/call`. Other private `_` keys are still stripped.
|
|
60
|
+
- MCP argument validation: ignore DRF `format` query noise so legacy nested `tools/call` envelopes from older MCP clients do not fail with `Unexpected query fields: format`.
|
|
61
|
+
|
|
26
62
|
## [0.5.1] - 2026-11-09
|
|
27
63
|
|
|
28
64
|
### 🐛 Bug Fixes
|
|
@@ -13,7 +13,7 @@ from django.core.cache import cache as django_cache
|
|
|
13
13
|
from django.http import HttpRequest, JsonResponse
|
|
14
14
|
|
|
15
15
|
from shellui_django.mcp.openapi_tools import tools_from_schema
|
|
16
|
-
from shellui_django.mcp.
|
|
16
|
+
from shellui_django.mcp.routing import tool_arguments_match_company
|
|
17
17
|
from shellui_django.mcp.server import McpServer
|
|
18
18
|
|
|
19
19
|
logger = logging.getLogger(__name__)
|
|
@@ -42,11 +42,20 @@ def service_allowed(agent_services: list[str] | None, service_id: str) -> bool:
|
|
|
42
42
|
|
|
43
43
|
|
|
44
44
|
def public_mcp_tools(raw: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
45
|
+
"""Strip private ``_`` keys from tools/list rows, but keep registry ``_meta``.
|
|
46
|
+
|
|
47
|
+
Downstream services publish flat agent schemas without ``method``/``path``
|
|
48
|
+
arguments. Gateways need ``_meta.path`` / ``_meta.method`` to route calls.
|
|
49
|
+
"""
|
|
45
50
|
out: list[dict[str, Any]] = []
|
|
46
51
|
for tool in raw:
|
|
47
52
|
if not isinstance(tool, dict):
|
|
48
53
|
continue
|
|
49
|
-
|
|
54
|
+
row = {k: v for k, v in tool.items() if not str(k).startswith('_')}
|
|
55
|
+
meta = tool.get('_meta')
|
|
56
|
+
if isinstance(meta, dict):
|
|
57
|
+
row['_meta'] = meta
|
|
58
|
+
out.append(row)
|
|
50
59
|
return out
|
|
51
60
|
|
|
52
61
|
|
|
@@ -178,25 +187,12 @@ class AggregatingMcpServer(McpServer):
|
|
|
178
187
|
self._cache().set(cache_key, public, self._gateway.tools_cache_ttl_seconds)
|
|
179
188
|
return public
|
|
180
189
|
|
|
181
|
-
def handle(self, request: HttpRequest, *, agent_claims: dict[str, Any] | None) -> JsonResponse:
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
if
|
|
185
|
-
return
|
|
186
|
-
|
|
187
|
-
if not agent_id:
|
|
188
|
-
return JsonResponse({'error': 'unauthorized'}, status=401)
|
|
189
|
-
if check_agent_rate_limit(agent_id):
|
|
190
|
-
return JsonResponse({'error': 'rate_limited'}, status=429)
|
|
191
|
-
company_id = agent_claims.get('company_id')
|
|
192
|
-
try:
|
|
193
|
-
company_id_int = int(company_id) if company_id is not None else None
|
|
194
|
-
except (TypeError, ValueError):
|
|
195
|
-
company_id_int = None
|
|
196
|
-
if self.identity_revocation_check and self.identity_revocation_check(agent_id, company_id_int):
|
|
197
|
-
return JsonResponse({'error': 'agent_revoked'}, status=403)
|
|
198
|
-
if not self._service_allowed(agent_claims, self.service_name):
|
|
199
|
-
return JsonResponse({'error': 'forbidden'}, status=403)
|
|
190
|
+
def handle(self, request: HttpRequest, *, agent_claims: dict[str, Any] | None = None) -> JsonResponse:
|
|
191
|
+
del agent_claims
|
|
192
|
+
prepared = self._prepare(request)
|
|
193
|
+
if isinstance(prepared, JsonResponse):
|
|
194
|
+
return prepared
|
|
195
|
+
agent_claims = prepared
|
|
200
196
|
try:
|
|
201
197
|
payload = json.loads(request.body.decode('utf-8') or '{}')
|
|
202
198
|
except json.JSONDecodeError:
|
|
@@ -228,7 +224,7 @@ class AggregatingMcpServer(McpServer):
|
|
|
228
224
|
forwarded = self._maybe_forward_tool_call(request, req_id, params, agent_claims)
|
|
229
225
|
if forwarded is not None:
|
|
230
226
|
return forwarded
|
|
231
|
-
return
|
|
227
|
+
return self._handle_prepared(request, agent_claims)
|
|
232
228
|
|
|
233
229
|
def _aggregated_tools_list(self, req_id: Any, agent_claims: dict[str, Any]) -> JsonResponse:
|
|
234
230
|
agent = self._gateway.resolve_agent(agent_claims)
|
|
@@ -272,6 +268,10 @@ class AggregatingMcpServer(McpServer):
|
|
|
272
268
|
tool_name = str(params.get('name') or '')
|
|
273
269
|
if not tool_name:
|
|
274
270
|
return None
|
|
271
|
+
company_raw = agent_claims.get('company_id')
|
|
272
|
+
company_id = company_raw if isinstance(company_raw, int) and not isinstance(company_raw, bool) else None
|
|
273
|
+
if not tool_arguments_match_company(params.get('arguments'), company_id):
|
|
274
|
+
return JsonResponse(self._error(req_id, -32602, 'company_id does not match the authenticated company'))
|
|
275
275
|
route = self._lookup_route(tool_name)
|
|
276
276
|
local_id = self._gateway.local_service_id
|
|
277
277
|
if route is None:
|
|
@@ -8,6 +8,7 @@ import time
|
|
|
8
8
|
import urllib.error
|
|
9
9
|
import urllib.request
|
|
10
10
|
from typing import Any
|
|
11
|
+
from urllib.parse import urlsplit
|
|
11
12
|
|
|
12
13
|
import jwt
|
|
13
14
|
from jwt.algorithms import RSAAlgorithm
|
|
@@ -15,6 +16,8 @@ from jwt.algorithms import RSAAlgorithm
|
|
|
15
16
|
_CACHE_TTL_SECONDS = 300
|
|
16
17
|
# Match ``INTERNAL_ASSERTION_LEEWAY_SECONDS`` in ``internal`` for Identity JWT verification.
|
|
17
18
|
IDENTITY_RS256_LEEWAY_SECONDS = 5
|
|
19
|
+
JWKS_MAX_RESPONSE_BYTES = 256 * 1024
|
|
20
|
+
_DEFAULT_JWKS_TIMEOUT_SECONDS = 10.0
|
|
18
21
|
_cache_lock = threading.Lock()
|
|
19
22
|
_jwks_cache: dict[str, tuple[float, dict[str, Any]]] = {}
|
|
20
23
|
|
|
@@ -51,13 +54,79 @@ def identity_jwks_url_for_issuer(issuer: str) -> str:
|
|
|
51
54
|
return f'{base}/.well-known/jwks.json'
|
|
52
55
|
|
|
53
56
|
|
|
57
|
+
def _allow_insecure_jwks_url() -> bool:
|
|
58
|
+
"""``http`` JWKS URLs are accepted only when Django ``DEBUG`` is on."""
|
|
59
|
+
try:
|
|
60
|
+
from django.conf import settings
|
|
61
|
+
|
|
62
|
+
return bool(settings.DEBUG)
|
|
63
|
+
except Exception:
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _validated_jwks_url(url: str) -> str:
|
|
68
|
+
"""Return ``url`` when it is the exact document to fetch."""
|
|
69
|
+
raw = (url or '').strip()
|
|
70
|
+
if not raw or any(char in raw for char in ('\r', '\n', '\t', ' ')):
|
|
71
|
+
raise IdentityJwksError('Identity JWKS URL is invalid.')
|
|
72
|
+
parsed = urlsplit(raw)
|
|
73
|
+
if parsed.username or parsed.password or parsed.fragment:
|
|
74
|
+
raise IdentityJwksError('Identity JWKS URL is invalid.')
|
|
75
|
+
if not parsed.hostname or not parsed.netloc:
|
|
76
|
+
raise IdentityJwksError('Identity JWKS URL is invalid.')
|
|
77
|
+
if parsed.scheme == 'https':
|
|
78
|
+
return raw
|
|
79
|
+
if parsed.scheme == 'http' and _allow_insecure_jwks_url():
|
|
80
|
+
return raw
|
|
81
|
+
if parsed.scheme == 'http':
|
|
82
|
+
raise IdentityJwksError('Identity JWKS URL must use https.')
|
|
83
|
+
raise IdentityJwksError('Identity JWKS URL is invalid.')
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _positive_timeout(timeout: float) -> float:
|
|
87
|
+
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
|
|
88
|
+
raise IdentityJwksError('Identity JWKS timeout is required.')
|
|
89
|
+
if timeout <= 0:
|
|
90
|
+
raise IdentityJwksError('Identity JWKS timeout is required.')
|
|
91
|
+
return float(timeout)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _jwks_opener() -> urllib.request.OpenerDirector:
|
|
95
|
+
"""HTTP(S) opener that does not follow redirects or local URL schemes."""
|
|
96
|
+
opener = urllib.request.OpenerDirector()
|
|
97
|
+
opener.add_handler(urllib.request.HTTPHandler())
|
|
98
|
+
opener.add_handler(urllib.request.HTTPSHandler())
|
|
99
|
+
opener.add_handler(urllib.request.HTTPErrorProcessor())
|
|
100
|
+
opener.add_handler(urllib.request.HTTPDefaultErrorHandler())
|
|
101
|
+
return opener
|
|
102
|
+
|
|
103
|
+
|
|
54
104
|
def _fetch_jwks_document(url: str, *, timeout: float) -> dict[str, Any]:
|
|
55
|
-
|
|
105
|
+
fetch_url = _validated_jwks_url(url)
|
|
106
|
+
timeout_s = _positive_timeout(timeout)
|
|
107
|
+
request = urllib.request.Request(fetch_url, headers={'Accept': 'application/json'})
|
|
56
108
|
try:
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
109
|
+
response = _jwks_opener().open(request, timeout=timeout_s)
|
|
110
|
+
except urllib.error.HTTPError as exc:
|
|
111
|
+
if 300 <= int(getattr(exc, 'code', 0) or 0) < 400:
|
|
112
|
+
raise IdentityJwksError('Identity JWKS redirects are not allowed.') from exc
|
|
113
|
+
raise IdentityJwksError('Failed to fetch Identity JWKS.') from exc
|
|
114
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
60
115
|
raise IdentityJwksError('Failed to fetch Identity JWKS.') from exc
|
|
116
|
+
with response:
|
|
117
|
+
final_url = response.geturl()
|
|
118
|
+
if urlsplit(final_url) != urlsplit(fetch_url):
|
|
119
|
+
raise IdentityJwksError('Identity JWKS redirects are not allowed.')
|
|
120
|
+
declared = response.headers.get('Content-Length')
|
|
121
|
+
if declared is not None:
|
|
122
|
+
try:
|
|
123
|
+
if int(declared) > JWKS_MAX_RESPONSE_BYTES:
|
|
124
|
+
raise IdentityJwksError('Identity JWKS response is too large.')
|
|
125
|
+
except ValueError as exc:
|
|
126
|
+
raise IdentityJwksError('Identity JWKS response is too large.') from exc
|
|
127
|
+
raw = response.read(JWKS_MAX_RESPONSE_BYTES + 1)
|
|
128
|
+
if len(raw) > JWKS_MAX_RESPONSE_BYTES:
|
|
129
|
+
raise IdentityJwksError('Identity JWKS response is too large.')
|
|
61
130
|
try:
|
|
62
131
|
document = json.loads(raw.decode('utf-8'))
|
|
63
132
|
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
@@ -67,7 +136,7 @@ def _fetch_jwks_document(url: str, *, timeout: float) -> dict[str, Any]:
|
|
|
67
136
|
return document
|
|
68
137
|
|
|
69
138
|
|
|
70
|
-
def get_jwks_document(*, jwks_url: str | None = None, jwks: dict[str, Any] | None = None, timeout: float =
|
|
139
|
+
def get_jwks_document(*, jwks_url: str | None = None, jwks: dict[str, Any] | None = None, timeout: float = _DEFAULT_JWKS_TIMEOUT_SECONDS) -> dict[str, Any]:
|
|
71
140
|
if jwks is not None:
|
|
72
141
|
if not isinstance(jwks.get('keys'), list):
|
|
73
142
|
raise IdentityJwksError('Inline JWKS document is invalid.')
|
|
@@ -515,8 +515,9 @@ def verify_rs256_mcp_assertion(
|
|
|
515
515
|
elif str(aud or '') != expected_audience:
|
|
516
516
|
raise InternalAssertionError('Assertion audience mismatch.')
|
|
517
517
|
if expected_target:
|
|
518
|
+
expected = str(expected_target).rstrip('/')
|
|
518
519
|
target = str(payload.get('target') or '').rstrip('/')
|
|
519
|
-
if target
|
|
520
|
+
if not target or target != expected:
|
|
520
521
|
raise InternalAssertionError('Assertion target mismatch.')
|
|
521
522
|
_assert_lifetime_within_limit(payload, max_lifetime_seconds=max_lifetime_seconds)
|
|
522
523
|
jti = str(payload.get('jti') or '').strip()
|
|
@@ -3,10 +3,13 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import re
|
|
6
|
+
from collections.abc import Iterator
|
|
6
7
|
from typing import Any
|
|
7
8
|
from urllib.parse import quote
|
|
8
9
|
|
|
9
10
|
_PATH_PARAM_RE = re.compile(r'\{([^}]+)\}')
|
|
11
|
+
# DRF browsable-API content negotiation; never an MCP tool argument.
|
|
12
|
+
_IGNORED_QUERY_FIELDS = frozenset({'format'})
|
|
10
13
|
|
|
11
14
|
|
|
12
15
|
class McpToolArgumentError(ValueError):
|
|
@@ -71,14 +74,67 @@ def _validate_param_object(
|
|
|
71
74
|
raise McpToolArgumentError(f'Missing required {label} fields: {", ".join(missing)}')
|
|
72
75
|
|
|
73
76
|
|
|
77
|
+
def _is_tenant_key(key: str) -> bool:
|
|
78
|
+
normalized = str(key).replace('-', '_').lower()
|
|
79
|
+
return normalized in {'company_id', 'companyid'}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _iter_tenant_values(node: Any) -> Iterator[Any]:
|
|
83
|
+
if isinstance(node, dict):
|
|
84
|
+
for key, value in node.items():
|
|
85
|
+
if _is_tenant_key(str(key)):
|
|
86
|
+
yield value
|
|
87
|
+
else:
|
|
88
|
+
yield from _iter_tenant_values(value)
|
|
89
|
+
elif isinstance(node, list):
|
|
90
|
+
for item in node:
|
|
91
|
+
yield from _iter_tenant_values(item)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _company_value_matches(value: Any, company_id: int) -> bool:
|
|
95
|
+
if isinstance(value, bool):
|
|
96
|
+
return False
|
|
97
|
+
if isinstance(value, int):
|
|
98
|
+
return value == company_id
|
|
99
|
+
if isinstance(value, str):
|
|
100
|
+
text = value.strip()
|
|
101
|
+
if not text.isdigit():
|
|
102
|
+
return False
|
|
103
|
+
return int(text) == company_id
|
|
104
|
+
return False
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def tool_arguments_match_company(arguments: Any, company_id: int | None) -> bool:
|
|
108
|
+
"""True when every tenant id in tool arguments matches ``company_id``.
|
|
109
|
+
|
|
110
|
+
Tenant keys are ``company_id``, ``companyId``, and ``company-id``, at any
|
|
111
|
+
depth in the arguments object. A missing authenticated company does not
|
|
112
|
+
match a tenant field. ``0`` is a real company id.
|
|
113
|
+
"""
|
|
114
|
+
if arguments is None:
|
|
115
|
+
return True
|
|
116
|
+
if not isinstance(arguments, dict):
|
|
117
|
+
return False
|
|
118
|
+
for value in _iter_tenant_values(arguments):
|
|
119
|
+
if company_id is None or isinstance(company_id, bool) or not isinstance(company_id, int):
|
|
120
|
+
return False
|
|
121
|
+
if not _company_value_matches(value, company_id):
|
|
122
|
+
return False
|
|
123
|
+
return True
|
|
124
|
+
|
|
125
|
+
|
|
74
126
|
def validate_mcp_tool_arguments(arguments: dict[str, Any], meta: dict[str, Any]) -> None:
|
|
75
127
|
path_params = arguments.get('path_params')
|
|
76
128
|
if path_params is None:
|
|
77
129
|
path_params = {}
|
|
78
130
|
materialize_openapi_path(str(meta.get('path') or ''), path_params)
|
|
131
|
+
query = arguments.get('query')
|
|
132
|
+
if isinstance(query, dict) and _IGNORED_QUERY_FIELDS & set(query):
|
|
133
|
+
query = {key: value for key, value in query.items() if key not in _IGNORED_QUERY_FIELDS}
|
|
134
|
+
arguments['query'] = query
|
|
79
135
|
_validate_param_object(
|
|
80
136
|
'query',
|
|
81
|
-
|
|
137
|
+
query,
|
|
82
138
|
meta.get('query_fields'),
|
|
83
139
|
required=meta.get('query_required') or None,
|
|
84
140
|
)
|
|
@@ -5,24 +5,101 @@ from __future__ import annotations
|
|
|
5
5
|
import hashlib
|
|
6
6
|
import json
|
|
7
7
|
import logging
|
|
8
|
+
import time
|
|
8
9
|
from collections.abc import Callable
|
|
9
10
|
from typing import Any
|
|
10
11
|
|
|
11
12
|
from django.http import HttpRequest, JsonResponse
|
|
12
13
|
from rest_framework.test import APIRequestFactory, force_authenticate
|
|
13
14
|
|
|
15
|
+
from shellui_django.mcp.identity_jwks import (
|
|
16
|
+
IdentityJwksError,
|
|
17
|
+
decode_identity_rs256_jwt,
|
|
18
|
+
jwt_unix_timestamp_claim_strict,
|
|
19
|
+
)
|
|
14
20
|
from shellui_django.mcp.masking import redact_mapping
|
|
15
21
|
from shellui_django.mcp.openapi_mcp import marker_tree_for_operation_request, marker_tree_for_operation_response
|
|
16
22
|
from shellui_django.mcp.openapi_tools import tools_from_schema
|
|
17
23
|
from shellui_django.mcp.rate_limit import check_agent_rate_limit
|
|
18
|
-
from shellui_django.mcp.
|
|
19
|
-
from shellui_django.mcp.
|
|
24
|
+
from shellui_django.mcp.resources import access_token_audience_matches
|
|
25
|
+
from shellui_django.mcp.routing import (
|
|
26
|
+
McpToolArgumentError,
|
|
27
|
+
materialize_openapi_path,
|
|
28
|
+
tool_arguments_match_company,
|
|
29
|
+
validate_mcp_tool_arguments,
|
|
30
|
+
)
|
|
31
|
+
from shellui_django.mcp.write_gate import WriteGateDecision, decide_write, is_destructive_operation
|
|
20
32
|
|
|
21
33
|
logger = logging.getLogger(__name__)
|
|
22
34
|
|
|
23
35
|
_BODYLESS_METHODS = frozenset({'GET', 'HEAD', 'OPTIONS', 'TRACE'})
|
|
24
36
|
|
|
25
37
|
|
|
38
|
+
class VerifiedTokenUser:
|
|
39
|
+
"""Authenticated principal for the bearer token checked in ``McpServer.handle``."""
|
|
40
|
+
|
|
41
|
+
is_authenticated = True
|
|
42
|
+
is_anonymous = False
|
|
43
|
+
is_active = True
|
|
44
|
+
|
|
45
|
+
def __init__(self, agent_id: str):
|
|
46
|
+
self.agent_id = agent_id
|
|
47
|
+
self.pk = agent_id
|
|
48
|
+
self.id = agent_id
|
|
49
|
+
|
|
50
|
+
def __str__(self) -> str:
|
|
51
|
+
return self.agent_id
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _strict_company_id(value: Any) -> int:
|
|
55
|
+
"""Non-negative company id. Rejects bool and float so values are not coerced."""
|
|
56
|
+
if isinstance(value, bool) or isinstance(value, float):
|
|
57
|
+
raise ValueError
|
|
58
|
+
if isinstance(value, int):
|
|
59
|
+
if value < 0:
|
|
60
|
+
raise ValueError
|
|
61
|
+
return value
|
|
62
|
+
if isinstance(value, str):
|
|
63
|
+
text = value.strip()
|
|
64
|
+
if text.isdigit():
|
|
65
|
+
return int(text)
|
|
66
|
+
raise ValueError
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _claim_company_id(agent_claims: dict[str, Any]) -> int | None:
|
|
70
|
+
if 'company_id' not in agent_claims or agent_claims.get('company_id') is None:
|
|
71
|
+
return None
|
|
72
|
+
return _strict_company_id(agent_claims['company_id'])
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _delegated_approval_covers(agent_claims: dict[str, Any], tool_name: str) -> bool:
|
|
76
|
+
"""True when ``mcp_gateway_delegated`` names this tool and has not expired.
|
|
77
|
+
|
|
78
|
+
The claim must be an object ``{"action": "<tool name>", "exp": <unix seconds>}``.
|
|
79
|
+
A boolean or any other shape does not skip approval.
|
|
80
|
+
"""
|
|
81
|
+
claim = agent_claims.get('mcp_gateway_delegated')
|
|
82
|
+
if not isinstance(claim, dict):
|
|
83
|
+
return False
|
|
84
|
+
action = claim.get('action')
|
|
85
|
+
if not isinstance(action, str) or not action or action != tool_name:
|
|
86
|
+
return False
|
|
87
|
+
try:
|
|
88
|
+
exp = jwt_unix_timestamp_claim_strict(claim.get('exp'), field='exp')
|
|
89
|
+
except IdentityJwksError:
|
|
90
|
+
return False
|
|
91
|
+
return exp > int(time.time())
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _tool_list_row(tool: dict[str, Any]) -> dict[str, Any]:
|
|
95
|
+
"""Public tools/list row: drop private ``_`` keys except registry ``_meta``."""
|
|
96
|
+
row = {k: v for k, v in tool.items() if not str(k).startswith('_')}
|
|
97
|
+
meta = tool.get('_meta')
|
|
98
|
+
if isinstance(meta, dict):
|
|
99
|
+
row['_meta'] = meta
|
|
100
|
+
return row
|
|
101
|
+
|
|
102
|
+
|
|
26
103
|
class McpServer:
|
|
27
104
|
def __init__(
|
|
28
105
|
self,
|
|
@@ -35,6 +112,10 @@ class McpServer:
|
|
|
35
112
|
approval_handler: Callable[[dict[str, Any]], dict[str, Any] | None] | None = None,
|
|
36
113
|
approval_state: Callable[[dict[str, Any]], str | None] | None = None,
|
|
37
114
|
approval_consume: Callable[..., bool] | None = None,
|
|
115
|
+
identity_issuer: str | None = None,
|
|
116
|
+
identity_jwks_url: str | None = None,
|
|
117
|
+
identity_jwks: dict[str, Any] | None = None,
|
|
118
|
+
mcp_audience: str | None = None,
|
|
38
119
|
):
|
|
39
120
|
self.schema_provider = schema_provider
|
|
40
121
|
self.urlconf = urlconf
|
|
@@ -44,11 +125,28 @@ class McpServer:
|
|
|
44
125
|
self.approval_handler = approval_handler
|
|
45
126
|
self.approval_state = approval_state
|
|
46
127
|
self.approval_consume = approval_consume
|
|
128
|
+
self.identity_issuer = identity_issuer
|
|
129
|
+
self.identity_jwks_url = identity_jwks_url
|
|
130
|
+
self.identity_jwks = identity_jwks
|
|
131
|
+
self.mcp_audience = mcp_audience
|
|
47
132
|
self._factory = APIRequestFactory()
|
|
48
133
|
|
|
49
|
-
def handle(self, request: HttpRequest, *, agent_claims: dict[str, Any] | None) -> JsonResponse:
|
|
134
|
+
def handle(self, request: HttpRequest, *, agent_claims: dict[str, Any] | None = None) -> JsonResponse:
|
|
135
|
+
"""Dispatch one MCP JSON-RPC request.
|
|
136
|
+
|
|
137
|
+
``agent_claims`` is accepted so existing callers keep working. Authorization
|
|
138
|
+
uses the verified bearer token only.
|
|
139
|
+
"""
|
|
140
|
+
del agent_claims
|
|
141
|
+
prepared = self._prepare(request)
|
|
142
|
+
if isinstance(prepared, JsonResponse):
|
|
143
|
+
return prepared
|
|
144
|
+
return self._handle_prepared(request, prepared)
|
|
145
|
+
|
|
146
|
+
def _prepare(self, request: HttpRequest) -> dict[str, Any] | JsonResponse:
|
|
50
147
|
if request.method != 'POST':
|
|
51
148
|
return JsonResponse({'error': 'method_not_allowed'}, status=405)
|
|
149
|
+
agent_claims = self._claims_from_bearer(request)
|
|
52
150
|
if agent_claims is None:
|
|
53
151
|
return JsonResponse({'error': 'unauthorized'}, status=401)
|
|
54
152
|
agent_id = str(agent_claims.get('agent_id') or '')
|
|
@@ -56,15 +154,64 @@ class McpServer:
|
|
|
56
154
|
return JsonResponse({'error': 'unauthorized'}, status=401)
|
|
57
155
|
if check_agent_rate_limit(agent_id):
|
|
58
156
|
return JsonResponse({'error': 'rate_limited'}, status=429)
|
|
59
|
-
company_id = agent_claims.get('company_id')
|
|
60
157
|
try:
|
|
61
|
-
company_id_int =
|
|
62
|
-
except
|
|
63
|
-
|
|
64
|
-
if
|
|
158
|
+
company_id_int = _claim_company_id(agent_claims)
|
|
159
|
+
except ValueError:
|
|
160
|
+
return JsonResponse({'error': 'unauthorized'}, status=401)
|
|
161
|
+
if company_id_int is None:
|
|
162
|
+
agent_claims.pop('company_id', None)
|
|
163
|
+
else:
|
|
164
|
+
agent_claims['company_id'] = company_id_int
|
|
165
|
+
if self.identity_revocation_check is None:
|
|
166
|
+
return JsonResponse({'error': 'revocation_unavailable'}, status=403)
|
|
167
|
+
try:
|
|
168
|
+
revoked = bool(self.identity_revocation_check(agent_id, company_id_int))
|
|
169
|
+
except Exception as exc:
|
|
170
|
+
logger.warning(
|
|
171
|
+
'MCP revocation check failed agent_id=%s err=%s',
|
|
172
|
+
agent_id,
|
|
173
|
+
type(exc).__name__,
|
|
174
|
+
)
|
|
175
|
+
return JsonResponse({'error': 'revocation_unavailable'}, status=403)
|
|
176
|
+
if revoked:
|
|
65
177
|
return JsonResponse({'error': 'agent_revoked'}, status=403)
|
|
66
178
|
if not self._service_allowed(agent_claims, self.service_name):
|
|
67
179
|
return JsonResponse({'error': 'forbidden'}, status=403)
|
|
180
|
+
return agent_claims
|
|
181
|
+
|
|
182
|
+
def _claims_from_bearer(self, request: HttpRequest) -> dict[str, Any] | None:
|
|
183
|
+
issuer = (self.identity_issuer or '').strip().rstrip('/')
|
|
184
|
+
audience = (self.mcp_audience or '').strip()
|
|
185
|
+
if not issuer or not audience:
|
|
186
|
+
return None
|
|
187
|
+
if self.identity_jwks is None and not (self.identity_jwks_url or '').strip():
|
|
188
|
+
return None
|
|
189
|
+
header = str(request.META.get('HTTP_AUTHORIZATION') or '')
|
|
190
|
+
if not header.lower().startswith('bearer '):
|
|
191
|
+
return None
|
|
192
|
+
token = header[7:].strip()
|
|
193
|
+
if not token:
|
|
194
|
+
return None
|
|
195
|
+
try:
|
|
196
|
+
claims = decode_identity_rs256_jwt(
|
|
197
|
+
token,
|
|
198
|
+
audience=audience,
|
|
199
|
+
issuer=issuer,
|
|
200
|
+
jwks_url=(self.identity_jwks_url or '').strip() or None,
|
|
201
|
+
jwks=self.identity_jwks,
|
|
202
|
+
require_claims=('agent_id',),
|
|
203
|
+
)
|
|
204
|
+
except IdentityJwksError:
|
|
205
|
+
return None
|
|
206
|
+
if not access_token_audience_matches(claims, audience):
|
|
207
|
+
return None
|
|
208
|
+
agent_id = claims.get('agent_id')
|
|
209
|
+
if not isinstance(agent_id, str) or not agent_id.strip():
|
|
210
|
+
return None
|
|
211
|
+
claims['agent_id'] = agent_id.strip()
|
|
212
|
+
return claims
|
|
213
|
+
|
|
214
|
+
def _handle_prepared(self, request: HttpRequest, agent_claims: dict[str, Any]) -> JsonResponse:
|
|
68
215
|
try:
|
|
69
216
|
payload = json.loads(request.body.decode('utf-8') or '{}')
|
|
70
217
|
except json.JSONDecodeError:
|
|
@@ -76,7 +223,9 @@ class McpServer:
|
|
|
76
223
|
return JsonResponse(self._result(req_id, {'protocolVersion': '2024-11-05', 'capabilities': {'tools': {}}}))
|
|
77
224
|
if method == 'tools/list':
|
|
78
225
|
schema = self.schema_provider()
|
|
79
|
-
|
|
226
|
+
# Keep ``_meta`` (path/method/read_only): flat agent schemas omit transport
|
|
227
|
+
# fields, and the AI gateway needs registry metadata to route tools/call.
|
|
228
|
+
tools = [_tool_list_row(t) for t in tools_from_schema(schema)]
|
|
80
229
|
return JsonResponse(self._result(req_id, {'tools': tools}))
|
|
81
230
|
if method == 'tools/call':
|
|
82
231
|
return self._tools_call(request, req_id, params, agent_claims)
|
|
@@ -90,7 +239,15 @@ class McpServer:
|
|
|
90
239
|
agent_claims: dict[str, Any],
|
|
91
240
|
) -> JsonResponse:
|
|
92
241
|
tool_name = str(params.get('name') or '')
|
|
93
|
-
arguments = params.get('arguments')
|
|
242
|
+
arguments = params.get('arguments')
|
|
243
|
+
if arguments is None:
|
|
244
|
+
arguments = {}
|
|
245
|
+
try:
|
|
246
|
+
company_id = _claim_company_id(agent_claims)
|
|
247
|
+
except ValueError:
|
|
248
|
+
return JsonResponse(self._error(req_id, -32602, 'company_id does not match the authenticated company'))
|
|
249
|
+
if not tool_arguments_match_company(arguments, company_id):
|
|
250
|
+
return JsonResponse(self._error(req_id, -32602, 'company_id does not match the authenticated company'))
|
|
94
251
|
schema = self.schema_provider()
|
|
95
252
|
tools = tools_from_schema(schema)
|
|
96
253
|
tool = next((t for t in tools if t['name'] == tool_name), None)
|
|
@@ -123,6 +280,9 @@ class McpServer:
|
|
|
123
280
|
allow_destructive_without_asking=bool(agent_claims.get('mcp_destructive')),
|
|
124
281
|
tool_read_only=tool_read_only,
|
|
125
282
|
)
|
|
283
|
+
# Skip a second approval only when the token names this tool and the grant has not expired.
|
|
284
|
+
if decision.needs_approval and _delegated_approval_covers(agent_claims, tool_name):
|
|
285
|
+
decision = WriteGateDecision(allowed=True)
|
|
126
286
|
if decision.needs_approval:
|
|
127
287
|
args_hash = hashlib.sha256(json.dumps(arguments, sort_keys=True, default=str).encode()).hexdigest()
|
|
128
288
|
approval_payload = {
|
|
@@ -205,7 +365,7 @@ class McpServer:
|
|
|
205
365
|
body = arguments.get('body')
|
|
206
366
|
inner_kwargs['data'] = body if body is not None else {}
|
|
207
367
|
drf_request = self._factory.generic(method, resolved_path, **inner_kwargs)
|
|
208
|
-
self._attach_request_principal(drf_request,
|
|
368
|
+
self._attach_request_principal(drf_request, agent_claims)
|
|
209
369
|
from django.urls import resolve
|
|
210
370
|
|
|
211
371
|
match = resolve(resolved_path, urlconf=self.urlconf)
|
|
@@ -245,19 +405,11 @@ class McpServer:
|
|
|
245
405
|
)
|
|
246
406
|
|
|
247
407
|
@staticmethod
|
|
248
|
-
def _attach_request_principal(
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
user = getattr(source_request, 'user', None)
|
|
254
|
-
auth = getattr(source_request, 'auth', None)
|
|
255
|
-
if auth is None and agent_claims:
|
|
256
|
-
auth = agent_claims
|
|
257
|
-
if user is not None or auth is not None:
|
|
258
|
-
force_authenticate(target_request, user=user, token=auth)
|
|
259
|
-
if auth is not None:
|
|
260
|
-
target_request.auth = auth
|
|
408
|
+
def _attach_request_principal(target_request, agent_claims: dict[str, Any]) -> None:
|
|
409
|
+
"""Authenticate the inner view as the verified token, not the outer request user."""
|
|
410
|
+
agent_id = str(agent_claims.get('agent_id') or '')
|
|
411
|
+
force_authenticate(target_request, user=VerifiedTokenUser(agent_id), token=agent_claims)
|
|
412
|
+
target_request.auth = agent_claims
|
|
261
413
|
|
|
262
414
|
@staticmethod
|
|
263
415
|
def _service_allowed(agent_claims: dict[str, Any], service_name: str) -> bool:
|
{shellui_django-0.5.1 → shellui_django-0.6.0}/src/shellui_django/mcp/tests/mcp_routing_urlconf.py
RENAMED
|
@@ -15,8 +15,17 @@ class CompanyItemView(APIView):
|
|
|
15
15
|
underlying = getattr(request, '_request', request)
|
|
16
16
|
auth = getattr(underlying, 'auth', None) or getattr(underlying, '_force_auth_token', None)
|
|
17
17
|
agent_id = auth.get('agent_id') if isinstance(auth, dict) else None
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
user = getattr(request, 'user', None)
|
|
19
|
+
user_ok = bool(getattr(user, 'is_authenticated', False))
|
|
20
|
+
return Response(
|
|
21
|
+
{
|
|
22
|
+
'company_id': company_id,
|
|
23
|
+
'agent_id': agent_id,
|
|
24
|
+
'user_ok': user_ok,
|
|
25
|
+
'user_agent_id': getattr(user, 'agent_id', None),
|
|
26
|
+
'user_marker': getattr(user, 'marker', None),
|
|
27
|
+
}
|
|
28
|
+
)
|
|
20
29
|
|
|
21
30
|
|
|
22
31
|
class RenderPreviewView(APIView):
|