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.
- shellui_django/__init__.py +3 -0
- shellui_django/mcp/__init__.py +27 -0
- shellui_django/mcp/decorators.py +35 -0
- shellui_django/mcp/identity_jwks.py +109 -0
- shellui_django/mcp/internal.py +264 -0
- shellui_django/mcp/masking.py +78 -0
- shellui_django/mcp/openapi_mcp.py +135 -0
- shellui_django/mcp/openapi_tools.py +120 -0
- shellui_django/mcp/rate_limit.py +26 -0
- shellui_django/mcp/resources.py +53 -0
- shellui_django/mcp/routing.py +90 -0
- shellui_django/mcp/server.py +280 -0
- shellui_django/mcp/write_gate.py +53 -0
- shellui_django/testing/__init__.py +7 -0
- shellui_django-0.1.0.dist-info/METADATA +65 -0
- shellui_django-0.1.0.dist-info/RECORD +18 -0
- shellui_django-0.1.0.dist-info/WHEEL +4 -0
- shellui_django-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Build MCP tool definitions from a drf-spectacular OpenAPI schema."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from shellui_django.mcp.openapi_mcp import tool_access_flags
|
|
9
|
+
from shellui_django.mcp.routing import path_parameter_names
|
|
10
|
+
|
|
11
|
+
MCP_TOOL_TAG = 'mcp-tools'
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _parameter_field_names(operation: dict[str, Any], *, location: str) -> tuple[list[str], list[str]]:
|
|
15
|
+
names: list[str] = []
|
|
16
|
+
required: list[str] = []
|
|
17
|
+
for param in operation.get('parameters') or []:
|
|
18
|
+
if not isinstance(param, dict) or param.get('in') != location:
|
|
19
|
+
continue
|
|
20
|
+
name = param.get('name')
|
|
21
|
+
if not name:
|
|
22
|
+
continue
|
|
23
|
+
names.append(str(name))
|
|
24
|
+
if param.get('required'):
|
|
25
|
+
required.append(str(name))
|
|
26
|
+
return names, required
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _body_field_names(operation: dict[str, Any]) -> tuple[list[str], list[str]]:
|
|
30
|
+
request_body = operation.get('requestBody') or {}
|
|
31
|
+
if not isinstance(request_body, dict):
|
|
32
|
+
return [], []
|
|
33
|
+
content = request_body.get('content') or {}
|
|
34
|
+
schema = content.get('application/json', {}).get('schema') or {}
|
|
35
|
+
if not isinstance(schema, dict):
|
|
36
|
+
return [], []
|
|
37
|
+
props = schema.get('properties') or {}
|
|
38
|
+
if not isinstance(props, dict):
|
|
39
|
+
return [], []
|
|
40
|
+
names = [str(key) for key in props.keys()]
|
|
41
|
+
required_raw = schema.get('required') or []
|
|
42
|
+
required = [str(key) for key in required_raw if str(key) in names]
|
|
43
|
+
return names, required
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _slug_tool_name(method: str, path: str, operation_id: str | None) -> str:
|
|
47
|
+
if operation_id:
|
|
48
|
+
base = re.sub(r'[^a-zA-Z0-9_]+', '_', operation_id).strip('_').lower()
|
|
49
|
+
if base:
|
|
50
|
+
return base[:120]
|
|
51
|
+
cleaned = re.sub(r'[^a-zA-Z0-9_]+', '_', f'{method}_{path}').strip('_').lower()
|
|
52
|
+
return cleaned[:120]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def tools_from_schema(schema: dict[str, Any]) -> list[dict[str, Any]]:
|
|
56
|
+
paths = schema.get('paths') or {}
|
|
57
|
+
tools: list[dict[str, Any]] = []
|
|
58
|
+
for path, path_item in paths.items():
|
|
59
|
+
if not isinstance(path_item, dict):
|
|
60
|
+
continue
|
|
61
|
+
for method, operation in path_item.items():
|
|
62
|
+
if method.lower() not in {'get', 'post', 'put', 'patch', 'delete'}:
|
|
63
|
+
continue
|
|
64
|
+
if not isinstance(operation, dict):
|
|
65
|
+
continue
|
|
66
|
+
tags = operation.get('tags') or []
|
|
67
|
+
if MCP_TOOL_TAG not in tags:
|
|
68
|
+
continue
|
|
69
|
+
name = _slug_tool_name(method, path, operation.get('operationId'))
|
|
70
|
+
description = (operation.get('summary') or operation.get('description') or name).strip()
|
|
71
|
+
path_params = path_parameter_names(path)
|
|
72
|
+
query_fields, query_required = _parameter_field_names(operation, location='query')
|
|
73
|
+
body_fields, body_required = _body_field_names(operation)
|
|
74
|
+
properties: dict[str, Any] = {
|
|
75
|
+
'path': {'type': 'string', 'const': path},
|
|
76
|
+
'method': {'type': 'string', 'enum': [method.upper()]},
|
|
77
|
+
'query': {'type': 'object', 'additionalProperties': False, 'properties': {}},
|
|
78
|
+
'body': {'type': 'object', 'additionalProperties': False, 'properties': {}},
|
|
79
|
+
}
|
|
80
|
+
required = ['path', 'method']
|
|
81
|
+
if path_params:
|
|
82
|
+
properties['path_params'] = {
|
|
83
|
+
'type': 'object',
|
|
84
|
+
'additionalProperties': False,
|
|
85
|
+
'properties': {param: {'type': 'string'} for param in path_params},
|
|
86
|
+
'required': path_params,
|
|
87
|
+
}
|
|
88
|
+
required.append('path_params')
|
|
89
|
+
if query_fields:
|
|
90
|
+
properties['query']['properties'] = {field: {} for field in query_fields}
|
|
91
|
+
if body_fields:
|
|
92
|
+
properties['body']['properties'] = {field: {} for field in body_fields}
|
|
93
|
+
access = tool_access_flags(operation)
|
|
94
|
+
tools.append(
|
|
95
|
+
{
|
|
96
|
+
'name': name,
|
|
97
|
+
'description': description,
|
|
98
|
+
'inputSchema': {
|
|
99
|
+
'type': 'object',
|
|
100
|
+
'properties': properties,
|
|
101
|
+
'required': required,
|
|
102
|
+
'additionalProperties': False,
|
|
103
|
+
},
|
|
104
|
+
'_meta': {
|
|
105
|
+
'path': path,
|
|
106
|
+
'method': method.upper(),
|
|
107
|
+
'operationId': operation.get('operationId'),
|
|
108
|
+
'path_params': path_params,
|
|
109
|
+
'query_fields': query_fields or None,
|
|
110
|
+
'query_required': query_required or None,
|
|
111
|
+
'body_fields': body_fields or None,
|
|
112
|
+
'body_required': body_required or None,
|
|
113
|
+
'read_only': access['read_only'],
|
|
114
|
+
'destructive': access['destructive'],
|
|
115
|
+
'mcp_tagged': access['tagged'],
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
)
|
|
119
|
+
tools.sort(key=lambda t: t['name'])
|
|
120
|
+
return tools
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Per-agent MCP rate limiting (cache-backed)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from django.conf import settings
|
|
6
|
+
from django.core.cache import cache
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _limit_spec() -> tuple[int, int]:
|
|
10
|
+
limits = getattr(settings, 'MCP_RATE_LIMITS', None) or {}
|
|
11
|
+
spec = limits.get('mcp_agent') or limits.get('default') or {'limit': 120, 'window': 60}
|
|
12
|
+
return int(spec['limit']), int(spec['window'])
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def check_agent_rate_limit(agent_id: str) -> bool:
|
|
16
|
+
"""Return True when the agent is over the limit."""
|
|
17
|
+
if not getattr(settings, 'AUTH_RATE_LIMIT_ENABLED', True):
|
|
18
|
+
return False
|
|
19
|
+
limit, window = _limit_spec()
|
|
20
|
+
key = f'mcp_rate:agent:{agent_id}'
|
|
21
|
+
try:
|
|
22
|
+
count = cache.incr(key)
|
|
23
|
+
except ValueError:
|
|
24
|
+
cache.add(key, 1, timeout=window)
|
|
25
|
+
count = 1
|
|
26
|
+
return count > limit
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""RFC 8707 resource indicators for MCP (audience = canonical ``/mcp`` URL)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hmac
|
|
6
|
+
from urllib.parse import urlsplit
|
|
7
|
+
|
|
8
|
+
MCP_RESOURCE_SUFFIX = '/mcp'
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def mcp_resource_from_origin(origin: str) -> str:
|
|
12
|
+
"""Build the protected resource identifier for a Shellui service origin."""
|
|
13
|
+
base = str(origin or '').strip().rstrip('/')
|
|
14
|
+
if not base:
|
|
15
|
+
return ''
|
|
16
|
+
return f'{base}{MCP_RESOURCE_SUFFIX}'
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def normalize_resource_indicator(raw: str | None) -> str | None:
|
|
20
|
+
"""
|
|
21
|
+
Canonical resource URL for authorize/token/refresh ``resource`` parameter.
|
|
22
|
+
Must be absolute https (or http loopback) ending in ``/mcp`` with no fragment.
|
|
23
|
+
"""
|
|
24
|
+
s = str(raw or '').strip()
|
|
25
|
+
if not s or '#' in s:
|
|
26
|
+
return None
|
|
27
|
+
if s.endswith('/'):
|
|
28
|
+
s = s.rstrip('/')
|
|
29
|
+
if not s.endswith(MCP_RESOURCE_SUFFIX):
|
|
30
|
+
return None
|
|
31
|
+
try:
|
|
32
|
+
parsed = urlsplit(s)
|
|
33
|
+
except ValueError:
|
|
34
|
+
return None
|
|
35
|
+
if parsed.scheme not in ('http', 'https') or not parsed.netloc:
|
|
36
|
+
return None
|
|
37
|
+
if parsed.path != MCP_RESOURCE_SUFFIX:
|
|
38
|
+
return None
|
|
39
|
+
if parsed.query or parsed.fragment:
|
|
40
|
+
return None
|
|
41
|
+
host = (parsed.hostname or '').lower()
|
|
42
|
+
if parsed.scheme == 'http' and host not in ('127.0.0.1', 'localhost', '::1'):
|
|
43
|
+
return None
|
|
44
|
+
return s
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def access_token_audience_matches(payload: dict, expected_resource: str) -> bool:
|
|
48
|
+
"""True when JWT ``aud`` equals this service's MCP resource URL."""
|
|
49
|
+
expected = normalize_resource_indicator(expected_resource) or ''
|
|
50
|
+
presented = normalize_resource_indicator(str(payload.get('aud') or '')) or ''
|
|
51
|
+
if not expected or not presented:
|
|
52
|
+
return False
|
|
53
|
+
return hmac.compare_digest(expected, presented)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""OpenAPI path templates and MCP tool argument validation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
_PATH_PARAM_RE = re.compile(r'\{([^}]+)\}')
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class McpToolArgumentError(ValueError):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def path_parameter_names(path_template: str) -> list[str]:
|
|
17
|
+
return _PATH_PARAM_RE.findall(path_template)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def materialize_openapi_path(path_template: str, path_params: dict[str, Any]) -> str:
|
|
21
|
+
"""Substitute ``{name}`` segments with URL-encoded values (fail closed on injection)."""
|
|
22
|
+
names = path_parameter_names(path_template)
|
|
23
|
+
if not isinstance(path_params, dict):
|
|
24
|
+
raise McpToolArgumentError('path_params must be an object.')
|
|
25
|
+
if set(path_params.keys()) != set(names):
|
|
26
|
+
missing = sorted(set(names) - set(path_params.keys()))
|
|
27
|
+
extra = sorted(set(path_params.keys()) - set(names))
|
|
28
|
+
if missing:
|
|
29
|
+
raise McpToolArgumentError(f'Missing path parameters: {", ".join(missing)}')
|
|
30
|
+
raise McpToolArgumentError(f'Unexpected path parameters: {", ".join(extra)}')
|
|
31
|
+
resolved = path_template
|
|
32
|
+
for name in names:
|
|
33
|
+
raw = path_params[name]
|
|
34
|
+
if raw is None:
|
|
35
|
+
raise McpToolArgumentError(f'Path parameter {name} is required.')
|
|
36
|
+
text = str(raw).strip()
|
|
37
|
+
if not text:
|
|
38
|
+
raise McpToolArgumentError(f'Path parameter {name} is required.')
|
|
39
|
+
if '/' in text or '{' in text or '}' in text:
|
|
40
|
+
raise McpToolArgumentError(f'Path parameter {name} is invalid.')
|
|
41
|
+
encoded = quote(text, safe='')
|
|
42
|
+
token = '{' + name + '}'
|
|
43
|
+
if token not in resolved:
|
|
44
|
+
raise McpToolArgumentError('Unresolved path template.')
|
|
45
|
+
resolved = resolved.replace(token, encoded, 1)
|
|
46
|
+
if _PATH_PARAM_RE.search(resolved):
|
|
47
|
+
raise McpToolArgumentError('Unresolved path template.')
|
|
48
|
+
return resolved
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _validate_param_object(
|
|
52
|
+
label: str,
|
|
53
|
+
value: Any,
|
|
54
|
+
allowed: list[str] | None,
|
|
55
|
+
*,
|
|
56
|
+
required: list[str] | None = None,
|
|
57
|
+
) -> None:
|
|
58
|
+
if value is None:
|
|
59
|
+
value = {}
|
|
60
|
+
if not isinstance(value, dict):
|
|
61
|
+
raise McpToolArgumentError(f'{label} must be an object.')
|
|
62
|
+
if allowed is None:
|
|
63
|
+
return
|
|
64
|
+
allowed_set = set(allowed)
|
|
65
|
+
extra = sorted(set(value.keys()) - allowed_set)
|
|
66
|
+
if extra:
|
|
67
|
+
raise McpToolArgumentError(f'Unexpected {label} fields: {", ".join(extra)}')
|
|
68
|
+
if required:
|
|
69
|
+
missing = sorted(set(required) - set(value.keys()))
|
|
70
|
+
if missing:
|
|
71
|
+
raise McpToolArgumentError(f'Missing required {label} fields: {", ".join(missing)}')
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def validate_mcp_tool_arguments(arguments: dict[str, Any], meta: dict[str, Any]) -> None:
|
|
75
|
+
path_params = arguments.get('path_params')
|
|
76
|
+
if path_params is None:
|
|
77
|
+
path_params = {}
|
|
78
|
+
materialize_openapi_path(str(meta.get('path') or ''), path_params)
|
|
79
|
+
_validate_param_object(
|
|
80
|
+
'query',
|
|
81
|
+
arguments.get('query'),
|
|
82
|
+
meta.get('query_fields'),
|
|
83
|
+
required=meta.get('query_required') or None,
|
|
84
|
+
)
|
|
85
|
+
_validate_param_object(
|
|
86
|
+
'body',
|
|
87
|
+
arguments.get('body'),
|
|
88
|
+
meta.get('body_fields'),
|
|
89
|
+
required=meta.get('body_required') or None,
|
|
90
|
+
)
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""Streamable HTTP MCP endpoint handler (JSON-RPC over POST /mcp)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from django.http import HttpRequest, JsonResponse
|
|
12
|
+
from rest_framework.test import APIRequestFactory, force_authenticate
|
|
13
|
+
|
|
14
|
+
from shellui_django.mcp.masking import redact_mapping
|
|
15
|
+
from shellui_django.mcp.openapi_mcp import marker_tree_for_operation_request, marker_tree_for_operation_response
|
|
16
|
+
from shellui_django.mcp.openapi_tools import tools_from_schema
|
|
17
|
+
from shellui_django.mcp.rate_limit import check_agent_rate_limit
|
|
18
|
+
from shellui_django.mcp.routing import McpToolArgumentError, materialize_openapi_path, validate_mcp_tool_arguments
|
|
19
|
+
from shellui_django.mcp.write_gate import decide_write, is_destructive_operation
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
_BODYLESS_METHODS = frozenset({'GET', 'HEAD', 'OPTIONS', 'TRACE'})
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class McpServer:
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
*,
|
|
30
|
+
schema_provider: Callable[[], dict[str, Any]],
|
|
31
|
+
urlconf: str,
|
|
32
|
+
service_name: str,
|
|
33
|
+
identity_revocation_check: Callable[[str, int | None], bool] | None = None,
|
|
34
|
+
on_call: Callable[[dict[str, Any]], None] | None = None,
|
|
35
|
+
approval_handler: Callable[[dict[str, Any]], dict[str, Any] | None] | None = None,
|
|
36
|
+
approval_state: Callable[[dict[str, Any]], str | None] | None = None,
|
|
37
|
+
approval_consume: Callable[..., bool] | None = None,
|
|
38
|
+
):
|
|
39
|
+
self.schema_provider = schema_provider
|
|
40
|
+
self.urlconf = urlconf
|
|
41
|
+
self.service_name = service_name
|
|
42
|
+
self.identity_revocation_check = identity_revocation_check
|
|
43
|
+
self.on_call = on_call
|
|
44
|
+
self.approval_handler = approval_handler
|
|
45
|
+
self.approval_state = approval_state
|
|
46
|
+
self.approval_consume = approval_consume
|
|
47
|
+
self._factory = APIRequestFactory()
|
|
48
|
+
|
|
49
|
+
def handle(self, request: HttpRequest, *, agent_claims: dict[str, Any] | None) -> JsonResponse:
|
|
50
|
+
if request.method != 'POST':
|
|
51
|
+
return JsonResponse({'error': 'method_not_allowed'}, status=405)
|
|
52
|
+
if agent_claims is None:
|
|
53
|
+
return JsonResponse({'error': 'unauthorized'}, status=401)
|
|
54
|
+
agent_id = str(agent_claims.get('agent_id') or '')
|
|
55
|
+
if not agent_id:
|
|
56
|
+
return JsonResponse({'error': 'unauthorized'}, status=401)
|
|
57
|
+
if check_agent_rate_limit(agent_id):
|
|
58
|
+
return JsonResponse({'error': 'rate_limited'}, status=429)
|
|
59
|
+
company_id = agent_claims.get('company_id')
|
|
60
|
+
try:
|
|
61
|
+
company_id_int = int(company_id) if company_id is not None else None
|
|
62
|
+
except (TypeError, ValueError):
|
|
63
|
+
company_id_int = None
|
|
64
|
+
if self.identity_revocation_check and self.identity_revocation_check(agent_id, company_id_int):
|
|
65
|
+
return JsonResponse({'error': 'agent_revoked'}, status=403)
|
|
66
|
+
if not self._service_allowed(agent_claims, self.service_name):
|
|
67
|
+
return JsonResponse({'error': 'forbidden'}, status=403)
|
|
68
|
+
try:
|
|
69
|
+
payload = json.loads(request.body.decode('utf-8') or '{}')
|
|
70
|
+
except json.JSONDecodeError:
|
|
71
|
+
return JsonResponse({'error': 'invalid_json'}, status=400)
|
|
72
|
+
method = payload.get('method')
|
|
73
|
+
req_id = payload.get('id')
|
|
74
|
+
params = payload.get('params') or {}
|
|
75
|
+
if method == 'initialize':
|
|
76
|
+
return JsonResponse(self._result(req_id, {'protocolVersion': '2024-11-05', 'capabilities': {'tools': {}}}))
|
|
77
|
+
if method == 'tools/list':
|
|
78
|
+
schema = self.schema_provider()
|
|
79
|
+
tools = [{k: v for k, v in t.items() if not k.startswith('_')} for t in tools_from_schema(schema)]
|
|
80
|
+
return JsonResponse(self._result(req_id, {'tools': tools}))
|
|
81
|
+
if method == 'tools/call':
|
|
82
|
+
return self._tools_call(request, req_id, params, agent_claims)
|
|
83
|
+
return JsonResponse(self._error(req_id, -32601, 'Method not found'))
|
|
84
|
+
|
|
85
|
+
def _tools_call(
|
|
86
|
+
self,
|
|
87
|
+
request: HttpRequest,
|
|
88
|
+
req_id: Any,
|
|
89
|
+
params: dict[str, Any],
|
|
90
|
+
agent_claims: dict[str, Any],
|
|
91
|
+
) -> JsonResponse:
|
|
92
|
+
tool_name = str(params.get('name') or '')
|
|
93
|
+
arguments = params.get('arguments') or {}
|
|
94
|
+
schema = self.schema_provider()
|
|
95
|
+
tools = tools_from_schema(schema)
|
|
96
|
+
tool = next((t for t in tools if t['name'] == tool_name), None)
|
|
97
|
+
if tool is None:
|
|
98
|
+
return JsonResponse(self._error(req_id, -32602, 'Unknown tool'))
|
|
99
|
+
meta = tool.get('_meta') or {}
|
|
100
|
+
path_template = str(meta.get('path') or '')
|
|
101
|
+
path = str(arguments.get('path') or path_template)
|
|
102
|
+
method = str(arguments.get('method') or meta.get('method') or 'GET').upper()
|
|
103
|
+
if path != path_template or method != meta.get('method'):
|
|
104
|
+
return JsonResponse(self._error(req_id, -32602, 'Tool path mismatch'))
|
|
105
|
+
try:
|
|
106
|
+
validate_mcp_tool_arguments(arguments if isinstance(arguments, dict) else {}, meta)
|
|
107
|
+
path_params = arguments.get('path_params') if isinstance(arguments.get('path_params'), dict) else {}
|
|
108
|
+
resolved_path = materialize_openapi_path(path_template, path_params)
|
|
109
|
+
except McpToolArgumentError as exc:
|
|
110
|
+
return JsonResponse(self._error(req_id, -32602, str(exc)))
|
|
111
|
+
|
|
112
|
+
access = str(agent_claims.get('mcp_access') or 'read_only')
|
|
113
|
+
read_level = str(agent_claims.get('mcp_read') or 'safe')
|
|
114
|
+
operation = self._operation(schema, path_template, method)
|
|
115
|
+
destructive = bool(meta.get('destructive')) or is_destructive_operation(operation)
|
|
116
|
+
tool_read_only = bool(meta.get('read_only'))
|
|
117
|
+
request_markers = marker_tree_for_operation_request(operation, schema)
|
|
118
|
+
response_markers = marker_tree_for_operation_response(operation, schema)
|
|
119
|
+
decision = decide_write(
|
|
120
|
+
method=method,
|
|
121
|
+
access_mode=access,
|
|
122
|
+
destructive=destructive,
|
|
123
|
+
allow_destructive_without_asking=bool(agent_claims.get('mcp_destructive')),
|
|
124
|
+
tool_read_only=tool_read_only,
|
|
125
|
+
)
|
|
126
|
+
if decision.needs_approval:
|
|
127
|
+
args_hash = hashlib.sha256(json.dumps(arguments, sort_keys=True, default=str).encode()).hexdigest()
|
|
128
|
+
approval_payload = {
|
|
129
|
+
'agent_id': agent_claims.get('agent_id'),
|
|
130
|
+
'company_id': agent_claims.get('company_id'),
|
|
131
|
+
'service': self.service_name,
|
|
132
|
+
'action': tool_name,
|
|
133
|
+
'arguments': arguments,
|
|
134
|
+
'arguments_hash': args_hash,
|
|
135
|
+
'path': resolved_path,
|
|
136
|
+
'method': method,
|
|
137
|
+
}
|
|
138
|
+
granted = False
|
|
139
|
+
if self.approval_state:
|
|
140
|
+
state = self.approval_state(approval_payload)
|
|
141
|
+
if state == 'executed':
|
|
142
|
+
return JsonResponse(
|
|
143
|
+
self._result(
|
|
144
|
+
req_id,
|
|
145
|
+
{'content': [{'type': 'text', 'text': 'Approval already used.'}], 'isError': True},
|
|
146
|
+
)
|
|
147
|
+
)
|
|
148
|
+
if state == 'approved':
|
|
149
|
+
approval_id = approval_payload.get('approval_id')
|
|
150
|
+
if approval_id and self.approval_consume:
|
|
151
|
+
consumed = self.approval_consume(str(approval_id), approval_payload)
|
|
152
|
+
if consumed:
|
|
153
|
+
granted = True
|
|
154
|
+
else:
|
|
155
|
+
return JsonResponse(
|
|
156
|
+
self._result(
|
|
157
|
+
req_id,
|
|
158
|
+
{'content': [{'type': 'text', 'text': 'Approval unavailable.'}], 'isError': True},
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
elif state == 'pending':
|
|
162
|
+
return JsonResponse(
|
|
163
|
+
self._result(
|
|
164
|
+
req_id,
|
|
165
|
+
{
|
|
166
|
+
'content': [{'type': 'text', 'text': 'Approval pending.'}],
|
|
167
|
+
'isError': True,
|
|
168
|
+
'meta': {'status': 'pending'},
|
|
169
|
+
},
|
|
170
|
+
)
|
|
171
|
+
)
|
|
172
|
+
if not granted and self.approval_handler:
|
|
173
|
+
pending = self.approval_handler(approval_payload)
|
|
174
|
+
if pending:
|
|
175
|
+
return JsonResponse(
|
|
176
|
+
self._result(
|
|
177
|
+
req_id,
|
|
178
|
+
{
|
|
179
|
+
'content': [{'type': 'text', 'text': 'Approval required.'}],
|
|
180
|
+
'isError': True,
|
|
181
|
+
'meta': {'approval_id': pending.get('id'), 'status': 'pending'},
|
|
182
|
+
},
|
|
183
|
+
)
|
|
184
|
+
)
|
|
185
|
+
if not granted:
|
|
186
|
+
return JsonResponse(
|
|
187
|
+
self._result(
|
|
188
|
+
req_id,
|
|
189
|
+
{'content': [{'type': 'text', 'text': decision.reason or 'Forbidden'}], 'isError': True},
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
if not decision.allowed:
|
|
193
|
+
return JsonResponse(
|
|
194
|
+
self._result(
|
|
195
|
+
req_id,
|
|
196
|
+
{'content': [{'type': 'text', 'text': decision.reason or 'Forbidden'}], 'isError': True},
|
|
197
|
+
)
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
inner_kwargs: dict[str, Any] = {
|
|
201
|
+
'query_params': arguments.get('query') or {},
|
|
202
|
+
'HTTP_AUTHORIZATION': request.META.get('HTTP_AUTHORIZATION', ''),
|
|
203
|
+
}
|
|
204
|
+
if method not in _BODYLESS_METHODS:
|
|
205
|
+
body = arguments.get('body')
|
|
206
|
+
inner_kwargs['data'] = body if body is not None else {}
|
|
207
|
+
drf_request = self._factory.generic(method, resolved_path, **inner_kwargs)
|
|
208
|
+
self._attach_request_principal(drf_request, request, agent_claims)
|
|
209
|
+
from django.urls import resolve
|
|
210
|
+
|
|
211
|
+
match = resolve(resolved_path, urlconf=self.urlconf)
|
|
212
|
+
response = match.func(drf_request, *match.args, **match.kwargs)
|
|
213
|
+
status_code = getattr(response, 'status_code', 500)
|
|
214
|
+
try:
|
|
215
|
+
data = response.data # type: ignore[attr-defined]
|
|
216
|
+
except AttributeError:
|
|
217
|
+
data = {'detail': 'ok'}
|
|
218
|
+
read_sensitive = read_level == 'sensitive'
|
|
219
|
+
redacted = redact_mapping(
|
|
220
|
+
data if isinstance(data, dict) else {'result': data},
|
|
221
|
+
read_sensitive=read_sensitive,
|
|
222
|
+
markers=response_markers,
|
|
223
|
+
)
|
|
224
|
+
if self.on_call:
|
|
225
|
+
self.on_call(
|
|
226
|
+
{
|
|
227
|
+
'agent_id': agent_claims.get('agent_id'),
|
|
228
|
+
'company_id': agent_claims.get('company_id'),
|
|
229
|
+
'service': self.service_name,
|
|
230
|
+
'tool': tool_name,
|
|
231
|
+
'method': method,
|
|
232
|
+
'path': resolved_path,
|
|
233
|
+
'status': status_code,
|
|
234
|
+
'arguments': redact_mapping(arguments, read_sensitive=False, markers=request_markers),
|
|
235
|
+
}
|
|
236
|
+
)
|
|
237
|
+
return JsonResponse(
|
|
238
|
+
self._result(
|
|
239
|
+
req_id,
|
|
240
|
+
{
|
|
241
|
+
'content': [{'type': 'text', 'text': json.dumps(redacted)}],
|
|
242
|
+
'isError': status_code >= 400,
|
|
243
|
+
},
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
@staticmethod
|
|
248
|
+
def _attach_request_principal(
|
|
249
|
+
target_request,
|
|
250
|
+
source_request: HttpRequest,
|
|
251
|
+
agent_claims: dict[str, Any],
|
|
252
|
+
) -> None:
|
|
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
|
|
261
|
+
|
|
262
|
+
@staticmethod
|
|
263
|
+
def _service_allowed(agent_claims: dict[str, Any], service_name: str) -> bool:
|
|
264
|
+
scope = [part for part in str(agent_claims.get('scope') or '').split() if part]
|
|
265
|
+
if not scope:
|
|
266
|
+
return False
|
|
267
|
+
return service_name in scope
|
|
268
|
+
|
|
269
|
+
@staticmethod
|
|
270
|
+
def _operation(schema: dict[str, Any], path: str, method: str) -> dict[str, Any] | None:
|
|
271
|
+
item = (schema.get('paths') or {}).get(path) or {}
|
|
272
|
+
return item.get(method.lower())
|
|
273
|
+
|
|
274
|
+
@staticmethod
|
|
275
|
+
def _result(req_id: Any, result: dict[str, Any]) -> dict[str, Any]:
|
|
276
|
+
return {'jsonrpc': '2.0', 'id': req_id, 'result': result}
|
|
277
|
+
|
|
278
|
+
@staticmethod
|
|
279
|
+
def _error(req_id: Any, code: int, message: str) -> dict[str, Any]:
|
|
280
|
+
return {'jsonrpc': '2.0', 'id': req_id, 'error': {'code': code, 'message': message}}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Gate write operations by agent access mode."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
ACCESS_READ_ONLY = 'read_only'
|
|
8
|
+
ACCESS_ASK = 'ask'
|
|
9
|
+
ACCESS_FULL = 'full'
|
|
10
|
+
|
|
11
|
+
SAFE_METHODS = frozenset({'GET', 'HEAD', 'OPTIONS'})
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class WriteGateDecision:
|
|
15
|
+
__slots__ = ('allowed', 'needs_approval', 'reason')
|
|
16
|
+
|
|
17
|
+
def __init__(self, *, allowed: bool, needs_approval: bool = False, reason: str = ''):
|
|
18
|
+
self.allowed = allowed
|
|
19
|
+
self.needs_approval = needs_approval
|
|
20
|
+
self.reason = reason
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def decide_write(
|
|
24
|
+
*,
|
|
25
|
+
method: str,
|
|
26
|
+
access_mode: str,
|
|
27
|
+
destructive: bool,
|
|
28
|
+
allow_destructive_without_asking: bool,
|
|
29
|
+
tool_read_only: bool = False,
|
|
30
|
+
) -> WriteGateDecision:
|
|
31
|
+
if tool_read_only:
|
|
32
|
+
return WriteGateDecision(allowed=True)
|
|
33
|
+
m = (method or 'GET').upper()
|
|
34
|
+
if m in SAFE_METHODS:
|
|
35
|
+
return WriteGateDecision(allowed=True)
|
|
36
|
+
if access_mode == ACCESS_READ_ONLY:
|
|
37
|
+
return WriteGateDecision(allowed=False, reason='Agent is read only.')
|
|
38
|
+
if access_mode == ACCESS_FULL:
|
|
39
|
+
if destructive and not allow_destructive_without_asking:
|
|
40
|
+
return WriteGateDecision(allowed=False, needs_approval=True, reason='Destructive change requires approval.')
|
|
41
|
+
return WriteGateDecision(allowed=True)
|
|
42
|
+
if access_mode == ACCESS_ASK:
|
|
43
|
+
return WriteGateDecision(allowed=False, needs_approval=True, reason='Write requires approval.')
|
|
44
|
+
return WriteGateDecision(allowed=False, reason='Unknown access mode.')
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def is_destructive_operation(operation: dict[str, Any] | None) -> bool:
|
|
48
|
+
if not operation:
|
|
49
|
+
return False
|
|
50
|
+
for tag in operation.get('tags') or []:
|
|
51
|
+
if str(tag).lower() in {'destructive', 'mcp-destructive'}:
|
|
52
|
+
return True
|
|
53
|
+
return False
|