shellui-django 0.1.0__tar.gz → 0.2.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.
Files changed (34) hide show
  1. {shellui_django-0.1.0 → shellui_django-0.2.0}/CHANGELOG.md +14 -0
  2. {shellui_django-0.1.0 → shellui_django-0.2.0}/PKG-INFO +18 -2
  3. {shellui_django-0.1.0 → shellui_django-0.2.0}/README.md +1 -1
  4. {shellui_django-0.1.0 → shellui_django-0.2.0}/pyproject.toml +22 -1
  5. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/__init__.py +1 -1
  6. shellui_django-0.2.0/src/shellui_django/mcp/gateway.py +358 -0
  7. shellui_django-0.2.0/src/shellui_django/mcp/tests/test_gateway.py +303 -0
  8. {shellui_django-0.1.0 → shellui_django-0.2.0}/.gitignore +0 -0
  9. {shellui_django-0.1.0 → shellui_django-0.2.0}/LICENSE +0 -0
  10. {shellui_django-0.1.0 → shellui_django-0.2.0}/SECURITY.md +0 -0
  11. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/__init__.py +0 -0
  12. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/decorators.py +0 -0
  13. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/identity_jwks.py +0 -0
  14. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/internal.py +0 -0
  15. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/masking.py +0 -0
  16. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/openapi_mcp.py +0 -0
  17. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/openapi_tools.py +0 -0
  18. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/rate_limit.py +0 -0
  19. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/resources.py +0 -0
  20. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/routing.py +0 -0
  21. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/server.py +0 -0
  22. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/__init__.py +0 -0
  23. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/mcp_routing_urlconf.py +0 -0
  24. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/rs256_helpers.py +0 -0
  25. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/test_internal_revocation.py +0 -0
  26. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/test_masking.py +0 -0
  27. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/test_openapi_tools.py +0 -0
  28. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/test_package.py +0 -0
  29. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/test_resources.py +0 -0
  30. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/test_routing.py +0 -0
  31. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/test_server_routing.py +0 -0
  32. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/tests/test_write_gate_mcp.py +0 -0
  33. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/mcp/write_gate.py +0 -0
  34. {shellui_django-0.1.0 → shellui_django-0.2.0}/src/shellui_django/testing/__init__.py +0 -0
@@ -23,6 +23,20 @@ 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.2.0] - 2026-11-02
27
+
28
+ ### ✨ Feature
29
+
30
+ - Add `shellui_django.mcp.gateway`: `AggregatingMcpServer` merges downstream `tools/list` and forwards `tools/call` with service-scoped RS256 tokens (`aud` = `{service}/mcp`). Host apps inject the service URL map, agent lookup, and token minting.
31
+
32
+ ### 📚 Documentation
33
+
34
+ - Document the MCP aggregating gateway in `docs/mcp.md`.
35
+
36
+ ### 🏗 Chore
37
+
38
+ - PyPI metadata: license file, classifiers, keywords and project links.
39
+
26
40
  ## [0.1.0] - 2026-11-02
27
41
 
28
42
  ### ✨ Feature
@@ -1,10 +1,25 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: shellui-django
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Shared Django libraries for Shellui services
5
+ Project-URL: Homepage, https://shellui.com
6
+ Project-URL: Source, https://github.com/shellui/django-commons
7
+ Project-URL: Documentation, https://github.com/shellui/django-commons/tree/main/docs
8
+ Project-URL: Changelog, https://github.com/shellui/django-commons/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/shellui/django-commons/issues
5
10
  Author: Sébastien Barbier
6
11
  License-Expression: MIT
7
12
  License-File: LICENSE
13
+ Keywords: django,djangorestframework,mcp,shellui
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Framework :: Django
16
+ Classifier: Framework :: Django :: 6.0
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Internet :: WWW/HTTP
22
+ Classifier: Topic :: Security
8
23
  Requires-Python: >=3.14
9
24
  Requires-Dist: django==6.0.8
10
25
  Requires-Dist: djangorestframework==3.18.2
@@ -12,6 +27,7 @@ Provides-Extra: mcp
12
27
  Requires-Dist: cryptography>=50.0.0; extra == 'mcp'
13
28
  Requires-Dist: djangorestframework-simplejwt==5.5.1; extra == 'mcp'
14
29
  Requires-Dist: pyjwt>=2.14.0; extra == 'mcp'
30
+ Requires-Dist: requests>=2.32.0; extra == 'mcp'
15
31
  Description-Content-Type: text/markdown
16
32
 
17
33
  # shellui-django
@@ -32,7 +48,7 @@ pip install shellui-django
32
48
  pip install shellui-django[mcp] # MCP server helpers
33
49
  ```
34
50
 
35
- Requires Python 3.14+, Django, and DRF. The `[mcp]` extra adds PyJWT, cryptography, and SimpleJWT for MCP auth and signed internal calls.
51
+ Requires Python 3.14+, Django, and DRF. The `[mcp]` extra adds PyJWT, cryptography, SimpleJWT, and requests for MCP auth, signed internal calls, and the aggregating gateway.
36
52
 
37
53
  ## Modules
38
54
 
@@ -16,7 +16,7 @@ pip install shellui-django
16
16
  pip install shellui-django[mcp] # MCP server helpers
17
17
  ```
18
18
 
19
- Requires Python 3.14+, Django, and DRF. The `[mcp]` extra adds PyJWT, cryptography, and SimpleJWT for MCP auth and signed internal calls.
19
+ Requires Python 3.14+, Django, and DRF. The `[mcp]` extra adds PyJWT, cryptography, SimpleJWT, and requests for MCP auth, signed internal calls, and the aggregating gateway.
20
20
 
21
21
  ## Modules
22
22
 
@@ -1,9 +1,22 @@
1
1
  [project]
2
2
  name = "shellui-django"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "Shared Django libraries for Shellui services"
5
5
  readme = "README.md"
6
6
  license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ keywords = ["django", "djangorestframework", "mcp", "shellui"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Framework :: Django",
12
+ "Framework :: Django :: 6.0",
13
+ "Intended Audience :: Developers",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.14",
17
+ "Topic :: Security",
18
+ "Topic :: Internet :: WWW/HTTP",
19
+ ]
7
20
  requires-python = ">=3.14"
8
21
  authors = [{ name = "Sébastien Barbier" }]
9
22
  dependencies = [
@@ -11,11 +24,19 @@ dependencies = [
11
24
  "djangorestframework==3.18.2",
12
25
  ]
13
26
 
27
+ [project.urls]
28
+ Homepage = "https://shellui.com"
29
+ Source = "https://github.com/shellui/django-commons"
30
+ Documentation = "https://github.com/shellui/django-commons/tree/main/docs"
31
+ Changelog = "https://github.com/shellui/django-commons/blob/main/CHANGELOG.md"
32
+ Issues = "https://github.com/shellui/django-commons/issues"
33
+
14
34
  [project.optional-dependencies]
15
35
  mcp = [
16
36
  "cryptography>=50.0.0",
17
37
  "djangorestframework-simplejwt==5.5.1",
18
38
  "pyjwt>=2.14.0",
39
+ "requests>=2.32.0",
19
40
  ]
20
41
 
21
42
  [dependency-groups]
@@ -1,3 +1,3 @@
1
1
  """Shared Django libraries for Shellui services."""
2
2
 
3
- __version__ = '0.1.0'
3
+ __version__ = '0.2.0'
@@ -0,0 +1,358 @@
1
+ """Aggregated MCP gateway: merge downstream ``tools/list`` and forward ``tools/call``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+ from typing import Any, Protocol
10
+
11
+ import requests
12
+ from django.core.cache import cache as django_cache
13
+ from django.http import HttpRequest, JsonResponse
14
+
15
+ from shellui_django.mcp.openapi_tools import tools_from_schema
16
+ from shellui_django.mcp.rate_limit import check_agent_rate_limit
17
+ from shellui_django.mcp.server import McpServer
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ _TOOLS_CACHE_PREFIX = 'mcp_gateway:tools:'
22
+ _TOOL_ROUTE_PREFIX = 'mcp_gateway:route:'
23
+
24
+
25
+ class _CacheBackend(Protocol):
26
+ def get(self, key: str, default: Any = None) -> Any: ...
27
+
28
+ def set(self, key: str, value: Any, timeout: int | float | None = None) -> Any: ...
29
+
30
+
31
+ class _AgentRecord(Protocol):
32
+ services_allowed: list[str] | None
33
+
34
+
35
+ def scope_service_ids(agent_claims: dict[str, Any]) -> set[str]:
36
+ return {part for part in str(agent_claims.get('scope') or '').split() if part}
37
+
38
+
39
+ def service_allowed(agent_services: list[str] | None, service_id: str) -> bool:
40
+ allowed = {str(s) for s in (agent_services or [])}
41
+ return service_id in allowed
42
+
43
+
44
+ def public_mcp_tools(raw: list[dict[str, Any]]) -> list[dict[str, Any]]:
45
+ out: list[dict[str, Any]] = []
46
+ for tool in raw:
47
+ if not isinstance(tool, dict):
48
+ continue
49
+ out.append({k: v for k, v in tool.items() if not str(k).startswith('_')})
50
+ return out
51
+
52
+
53
+ def merge_tool_catalog(
54
+ local_tools: list[dict[str, Any]],
55
+ remote_by_service: dict[str, list[dict[str, Any]]],
56
+ *,
57
+ local_service_id: str,
58
+ remember_route: Callable[[str, str, str], None],
59
+ ) -> list[dict[str, Any]]:
60
+ taken: set[str] = set()
61
+ merged: list[dict[str, Any]] = []
62
+
63
+ for tool in local_tools:
64
+ name = str(tool.get('name') or '')
65
+ if not name:
66
+ continue
67
+ taken.add(name)
68
+ remember_route(name, local_service_id, name)
69
+ merged.append(tool)
70
+
71
+ for service_id, tools in remote_by_service.items():
72
+ for tool in tools:
73
+ downstream_name = str(tool.get('name') or '')
74
+ if not downstream_name:
75
+ continue
76
+ export_name = downstream_name
77
+ if export_name in taken:
78
+ export_name = f'{service_id}__{downstream_name}'
79
+ if export_name in taken:
80
+ export_name = f'{service_id}__{downstream_name}__gateway'
81
+ taken.add(export_name)
82
+ remember_route(export_name, service_id, downstream_name)
83
+ if export_name == downstream_name:
84
+ merged.append(tool)
85
+ else:
86
+ merged.append({**tool, 'name': export_name})
87
+ return merged
88
+
89
+
90
+ def gateway_instructions(
91
+ agent_claims: dict[str, Any],
92
+ *,
93
+ agent: _AgentRecord | None,
94
+ service_urls: dict[str, str],
95
+ title: str,
96
+ ) -> str:
97
+ scope = scope_service_ids(agent_claims)
98
+ allowed_rows = set(agent.services_allowed or []) if agent else set()
99
+ connected = sorted(sid for sid in scope if sid in allowed_rows and sid in service_urls)
100
+ return (
101
+ f'{title}\n'
102
+ f'Connected services: {", ".join(connected) or "none"}.\n'
103
+ 'Remote tools run on the downstream service with the same agent access level and approvals.\n'
104
+ 'Use the list_services tool for per-service MCP URLs and resource-bound tokens.'
105
+ )
106
+
107
+
108
+ @dataclass(frozen=True, slots=True)
109
+ class McpGatewayConfig:
110
+ """Host-injected gateway wiring (service map, agent lookup, downstream tokens)."""
111
+
112
+ get_service_urls: Callable[[], dict[str, str]]
113
+ resolve_agent: Callable[[dict[str, Any]], _AgentRecord | None]
114
+ mint_downstream_token: Callable[[_AgentRecord, str], str]
115
+ local_service_id: str
116
+ tools_cache_ttl_seconds: int = 30
117
+ downstream_timeout_seconds: float = 5.0
118
+ instructions_title: str = 'Shellui MCP gateway.'
119
+ cache: _CacheBackend | None = None
120
+
121
+
122
+ class AggregatingMcpServer(McpServer):
123
+ """MCP server that aggregates downstream ``tools/list`` and forwards ``tools/call``."""
124
+
125
+ def __init__(self, *, gateway: McpGatewayConfig, **kwargs: Any) -> None:
126
+ super().__init__(**kwargs)
127
+ self._gateway = gateway
128
+
129
+ def _cache(self) -> _CacheBackend:
130
+ return self._gateway.cache or django_cache
131
+
132
+ def _remember_route(self, export_name: str, service_id: str, downstream_name: str) -> None:
133
+ self._cache().set(
134
+ f'{_TOOL_ROUTE_PREFIX}{export_name}',
135
+ {'service_id': service_id, 'downstream_name': downstream_name},
136
+ self._gateway.tools_cache_ttl_seconds,
137
+ )
138
+
139
+ def _lookup_route(self, tool_name: str) -> dict[str, str] | None:
140
+ meta = self._cache().get(f'{_TOOL_ROUTE_PREFIX}{tool_name}')
141
+ if isinstance(meta, dict) and meta.get('service_id') and meta.get('downstream_name'):
142
+ return {'service_id': str(meta['service_id']), 'downstream_name': str(meta['downstream_name'])}
143
+ return None
144
+
145
+ def _fetch_remote_tools_list(self, *, mcp_url: str, bearer_token: str) -> list[dict[str, Any]] | None:
146
+ cache_key = f'{_TOOLS_CACHE_PREFIX}{mcp_url}'
147
+ cached = self._cache().get(cache_key)
148
+ if isinstance(cached, list):
149
+ return cached
150
+ payload = {'jsonrpc': '2.0', 'id': 1, 'method': 'tools/list', 'params': {}}
151
+ try:
152
+ response = requests.post(
153
+ mcp_url,
154
+ json=payload,
155
+ headers={
156
+ 'Authorization': f'Bearer {bearer_token}',
157
+ 'Content-Type': 'application/json',
158
+ 'Accept': 'application/json',
159
+ },
160
+ timeout=self._gateway.downstream_timeout_seconds,
161
+ )
162
+ except (requests.RequestException, OSError) as exc:
163
+ logger.warning('MCP gateway tools/list transport error url=%s err=%s', mcp_url, type(exc).__name__)
164
+ return None
165
+ if response.status_code >= 400:
166
+ logger.warning('MCP gateway tools/list HTTP %s url=%s', response.status_code, mcp_url)
167
+ return None
168
+ try:
169
+ body = response.json()
170
+ except ValueError:
171
+ logger.warning('MCP gateway tools/list invalid JSON url=%s', mcp_url)
172
+ return None
173
+ tools = (body.get('result') or {}).get('tools')
174
+ if not isinstance(tools, list):
175
+ logger.warning('MCP gateway tools/list missing tools url=%s', mcp_url)
176
+ return None
177
+ public = public_mcp_tools(tools)
178
+ self._cache().set(cache_key, public, self._gateway.tools_cache_ttl_seconds)
179
+ return public
180
+
181
+ def handle(self, request: HttpRequest, *, agent_claims: dict[str, Any] | None) -> JsonResponse:
182
+ if request.method != 'POST':
183
+ return JsonResponse({'error': 'method_not_allowed'}, status=405)
184
+ if agent_claims is None:
185
+ return JsonResponse({'error': 'unauthorized'}, status=401)
186
+ agent_id = str(agent_claims.get('agent_id') or '')
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)
200
+ try:
201
+ payload = json.loads(request.body.decode('utf-8') or '{}')
202
+ except json.JSONDecodeError:
203
+ return JsonResponse({'error': 'invalid_json'}, status=400)
204
+ method = payload.get('method')
205
+ req_id = payload.get('id')
206
+ params = payload.get('params') or {}
207
+ if method == 'initialize':
208
+ agent = self._gateway.resolve_agent(agent_claims)
209
+ urls = self._gateway.get_service_urls()
210
+ return JsonResponse(
211
+ self._result(
212
+ req_id,
213
+ {
214
+ 'protocolVersion': '2024-11-05',
215
+ 'capabilities': {'tools': {}},
216
+ 'instructions': gateway_instructions(
217
+ agent_claims,
218
+ agent=agent,
219
+ service_urls=urls,
220
+ title=self._gateway.instructions_title,
221
+ ),
222
+ },
223
+ )
224
+ )
225
+ if method == 'tools/list':
226
+ return self._aggregated_tools_list(req_id, agent_claims)
227
+ if method == 'tools/call':
228
+ forwarded = self._maybe_forward_tool_call(request, req_id, params, agent_claims)
229
+ if forwarded is not None:
230
+ return forwarded
231
+ return super().handle(request, agent_claims=agent_claims)
232
+
233
+ def _aggregated_tools_list(self, req_id: Any, agent_claims: dict[str, Any]) -> JsonResponse:
234
+ agent = self._gateway.resolve_agent(agent_claims)
235
+ if agent is None:
236
+ return JsonResponse(self._error(req_id, -32603, 'Forbidden'))
237
+ scope = scope_service_ids(agent_claims)
238
+ allowed = scope & set(agent.services_allowed or [])
239
+ schema = self.schema_provider()
240
+ local = public_mcp_tools(tools_from_schema(schema))
241
+ remote: dict[str, list[dict[str, Any]]] = {}
242
+ urls = self._gateway.get_service_urls()
243
+ local_id = self._gateway.local_service_id
244
+ for service_id, mcp_url in urls.items():
245
+ if service_id == local_id:
246
+ continue
247
+ if service_id not in allowed:
248
+ continue
249
+ token = self._gateway.mint_downstream_token(agent, mcp_url)
250
+ tools = self._fetch_remote_tools_list(mcp_url=mcp_url, bearer_token=token)
251
+ if tools is not None:
252
+ remote[service_id] = tools
253
+
254
+ def remember(export_name: str, sid: str, downstream_name: str) -> None:
255
+ self._remember_route(export_name, sid, downstream_name)
256
+
257
+ tools = merge_tool_catalog(
258
+ local,
259
+ remote,
260
+ local_service_id=local_id,
261
+ remember_route=remember,
262
+ )
263
+ return JsonResponse(self._result(req_id, {'tools': tools}))
264
+
265
+ def _maybe_forward_tool_call(
266
+ self,
267
+ request: HttpRequest,
268
+ req_id: Any,
269
+ params: dict[str, Any],
270
+ agent_claims: dict[str, Any],
271
+ ) -> JsonResponse | None:
272
+ tool_name = str(params.get('name') or '')
273
+ if not tool_name:
274
+ return None
275
+ route = self._lookup_route(tool_name)
276
+ local_id = self._gateway.local_service_id
277
+ if route is None:
278
+ schema = self.schema_provider()
279
+ local_names = {str(t.get('name')) for t in tools_from_schema(schema)}
280
+ if tool_name in local_names:
281
+ return None
282
+ return JsonResponse(self._error(req_id, -32602, 'Unknown tool'))
283
+ service_id = route['service_id']
284
+ if service_id == local_id:
285
+ return None
286
+ scope = scope_service_ids(agent_claims)
287
+ if not service_allowed(list(scope), service_id):
288
+ return JsonResponse(self._error(req_id, -32602, 'Forbidden'))
289
+ agent = self._gateway.resolve_agent(agent_claims)
290
+ if agent is None or not service_allowed(agent.services_allowed or [], service_id):
291
+ return JsonResponse(self._error(req_id, -32602, 'Forbidden'))
292
+ mcp_url = self._gateway.get_service_urls().get(service_id)
293
+ if not mcp_url:
294
+ return JsonResponse(self._error(req_id, -32602, 'Service unavailable'))
295
+ token = self._gateway.mint_downstream_token(agent, mcp_url)
296
+ downstream_params = dict(params)
297
+ downstream_params['name'] = route['downstream_name']
298
+ rpc = {
299
+ 'jsonrpc': '2.0',
300
+ 'id': req_id,
301
+ 'method': 'tools/call',
302
+ 'params': downstream_params,
303
+ }
304
+ try:
305
+ response = requests.post(
306
+ mcp_url,
307
+ json=rpc,
308
+ headers={
309
+ 'Authorization': f'Bearer {token}',
310
+ 'Content-Type': 'application/json',
311
+ 'Accept': 'application/json',
312
+ },
313
+ timeout=self._gateway.downstream_timeout_seconds,
314
+ )
315
+ except (requests.RequestException, OSError) as exc:
316
+ logger.warning(
317
+ 'MCP gateway tools/call transport error service=%s tool=%s err=%s',
318
+ service_id,
319
+ tool_name,
320
+ type(exc).__name__,
321
+ )
322
+ return JsonResponse(
323
+ self._result(
324
+ req_id,
325
+ {
326
+ 'content': [{'type': 'text', 'text': 'Downstream service unavailable.'}],
327
+ 'isError': True,
328
+ },
329
+ )
330
+ )
331
+ if response.status_code >= 400:
332
+ logger.warning(
333
+ 'MCP gateway tools/call HTTP %s service=%s tool=%s',
334
+ response.status_code,
335
+ service_id,
336
+ tool_name,
337
+ )
338
+ return JsonResponse(
339
+ self._result(
340
+ req_id,
341
+ {
342
+ 'content': [{'type': 'text', 'text': 'Downstream service error.'}],
343
+ 'isError': True,
344
+ },
345
+ )
346
+ )
347
+ try:
348
+ body = response.json()
349
+ except ValueError:
350
+ return JsonResponse(
351
+ self._result(
352
+ req_id,
353
+ {'content': [{'type': 'text', 'text': 'Invalid downstream response.'}], 'isError': True},
354
+ )
355
+ )
356
+ if not isinstance(body, dict):
357
+ return JsonResponse(self._error(req_id, -32603, 'Invalid downstream response'))
358
+ return JsonResponse(body)
@@ -0,0 +1,303 @@
1
+ """Aggregated MCP gateway: tenant isolation, forwarding, and tool catalog."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass
7
+ from unittest.mock import patch
8
+
9
+ import jwt
10
+ from django.core.cache import cache
11
+ from django.test import RequestFactory, SimpleTestCase, override_settings
12
+
13
+ from shellui_django.mcp.gateway import AggregatingMcpServer, McpGatewayConfig, public_mcp_tools
14
+
15
+ IDENTITY_MCP = 'https://identity.test/mcp'
16
+ STORAGE_MCP = 'https://storage.test/mcp'
17
+
18
+ LOCAL_SCHEMA = {
19
+ 'paths': {
20
+ '/api/v1/mcp/services/': {
21
+ 'get': {
22
+ 'tags': ['mcp-tools'],
23
+ 'operationId': 'api_v1_mcp_services_list',
24
+ },
25
+ },
26
+ },
27
+ }
28
+
29
+ EMPTY_SCHEMA: dict = {'paths': {}}
30
+
31
+
32
+ @dataclass
33
+ class StubAgent:
34
+ id: str
35
+ company_id: int
36
+ services_allowed: list[str]
37
+
38
+
39
+ def _rpc(method: str, **params):
40
+ body = {'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params or {}}
41
+ return json.dumps(body)
42
+
43
+
44
+ def _mint(agent: StubAgent, resource: str) -> str:
45
+ return jwt.encode(
46
+ {
47
+ 'agent_id': agent.id,
48
+ 'company_id': agent.company_id,
49
+ 'aud': resource,
50
+ 'scope': ' '.join(agent.services_allowed),
51
+ },
52
+ 'test-secret',
53
+ algorithm='HS256',
54
+ )
55
+
56
+
57
+ def _resolve(claims: dict) -> StubAgent | None:
58
+ agent_id = claims.get('agent_id')
59
+ company_id = claims.get('company_id')
60
+ if not agent_id or company_id is None:
61
+ return None
62
+ scope = [p for p in str(claims.get('scope') or '').split() if p]
63
+ return StubAgent(id=str(agent_id), company_id=int(company_id), services_allowed=scope)
64
+
65
+
66
+ @override_settings(
67
+ AUTH_RATE_LIMIT_ENABLED=False,
68
+ CACHES={
69
+ 'default': {
70
+ 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
71
+ 'LOCATION': 'mcp-gateway-tests',
72
+ }
73
+ },
74
+ )
75
+ class McpGatewayTests(SimpleTestCase):
76
+ def setUp(self):
77
+ cache.clear()
78
+ self.factory = RequestFactory()
79
+ self.agent_a = StubAgent(
80
+ id='agent-a',
81
+ company_id=10,
82
+ services_allowed=['identity', 'storage'],
83
+ )
84
+ self.agent_b = StubAgent(
85
+ id='agent-b',
86
+ company_id=20,
87
+ services_allowed=['identity', 'storage'],
88
+ )
89
+ self.claims_a = {
90
+ 'agent_id': self.agent_a.id,
91
+ 'company_id': self.agent_a.company_id,
92
+ 'scope': 'identity storage',
93
+ 'mcp_access': 'full',
94
+ }
95
+ self.claims_b = {
96
+ 'agent_id': self.agent_b.id,
97
+ 'company_id': self.agent_b.company_id,
98
+ 'scope': 'identity storage',
99
+ 'mcp_access': 'full',
100
+ }
101
+ self._agents = {
102
+ (self.agent_a.id, self.agent_a.company_id): self.agent_a,
103
+ (self.agent_b.id, self.agent_b.company_id): self.agent_b,
104
+ }
105
+
106
+ def resolve(claims: dict) -> StubAgent | None:
107
+ key = (str(claims.get('agent_id')), int(claims.get('company_id')))
108
+ return self._agents.get(key)
109
+
110
+ self.gateway_config = McpGatewayConfig(
111
+ get_service_urls=lambda: {'identity': IDENTITY_MCP, 'storage': STORAGE_MCP},
112
+ resolve_agent=resolve,
113
+ mint_downstream_token=_mint,
114
+ local_service_id='identity',
115
+ instructions_title='Shellui Identity MCP gateway.',
116
+ )
117
+ self.server = AggregatingMcpServer(
118
+ gateway=self.gateway_config,
119
+ schema_provider=lambda: LOCAL_SCHEMA,
120
+ urlconf='shellui_django.mcp.tests.mcp_routing_urlconf',
121
+ service_name='identity',
122
+ )
123
+
124
+ def _post(self, body: str, *, claims: dict | None = None):
125
+ request = self.factory.post('/mcp', data=body, content_type='application/json')
126
+ request.user = None
127
+ request.auth = claims
128
+ return self.server.handle(request, agent_claims=claims)
129
+
130
+ @patch('shellui_django.mcp.gateway.requests.post')
131
+ def test_tools_list_includes_remote_when_downstream_ok(self, post):
132
+ storage_tools = {
133
+ 'jsonrpc': '2.0',
134
+ 'id': 1,
135
+ 'result': {'tools': [{'name': 'storage_v1_list_buckets', 'description': 'List buckets'}]},
136
+ }
137
+
138
+ def side_effect(url, **kwargs):
139
+ from unittest.mock import Mock
140
+
141
+ resp = Mock()
142
+ resp.status_code = 200
143
+ resp.json.return_value = storage_tools
144
+ return resp
145
+
146
+ post.side_effect = side_effect
147
+ response = self._post(_rpc('tools/list'), claims=self.claims_a)
148
+ self.assertEqual(response.status_code, 200)
149
+ names = {t['name'] for t in json.loads(response.content)['result']['tools']}
150
+ self.assertIn('storage_v1_list_buckets', names)
151
+ self.assertIn('api_v1_mcp_services_list', names)
152
+
153
+ @patch('shellui_django.mcp.gateway.requests.post')
154
+ def test_downstream_failure_omits_remote_tools(self, post):
155
+ post.side_effect = ConnectionError('refused')
156
+ response = self._post(_rpc('tools/list'), claims=self.claims_a)
157
+ self.assertEqual(response.status_code, 200)
158
+ names = {t['name'] for t in json.loads(response.content)['result']['tools']}
159
+ self.assertNotIn('storage_v1_list_buckets', names)
160
+ self.assertIn('api_v1_mcp_services_list', names)
161
+
162
+ @patch('shellui_django.mcp.gateway.requests.post')
163
+ def test_collision_adds_service_namespace(self, post):
164
+ dup_tool = {'name': 'shared_tool', 'description': 'dup'}
165
+
166
+ def side_effect(url, **kwargs):
167
+ from unittest.mock import Mock
168
+
169
+ resp = Mock()
170
+ resp.status_code = 200
171
+ resp.json.return_value = {'jsonrpc': '2.0', 'id': 1, 'result': {'tools': [dup_tool]}}
172
+ return resp
173
+
174
+ post.side_effect = side_effect
175
+ server = AggregatingMcpServer(
176
+ gateway=self.gateway_config,
177
+ schema_provider=lambda: EMPTY_SCHEMA,
178
+ urlconf='shellui_django.mcp.tests.mcp_routing_urlconf',
179
+ service_name='identity',
180
+ )
181
+ with patch(
182
+ 'shellui_django.mcp.gateway.tools_from_schema',
183
+ return_value=[{'name': 'shared_tool', 'description': 'local'}],
184
+ ):
185
+ request = self.factory.post('/mcp', data=_rpc('tools/list'), content_type='application/json')
186
+ response = server.handle(request, agent_claims=self.claims_a)
187
+ names = [t['name'] for t in json.loads(response.content)['result']['tools']]
188
+ self.assertEqual(len(names), len(set(names)))
189
+ self.assertIn('storage__shared_tool', names)
190
+
191
+ @patch('shellui_django.mcp.gateway.requests.post')
192
+ def test_services_allowed_blocks_forward(self, post):
193
+ claims = {
194
+ 'agent_id': self.agent_a.id,
195
+ 'company_id': self.agent_a.company_id,
196
+ 'scope': 'identity',
197
+ 'mcp_access': 'full',
198
+ }
199
+ self.agent_a.services_allowed = ['identity']
200
+ server = AggregatingMcpServer(
201
+ gateway=self.gateway_config,
202
+ schema_provider=lambda: EMPTY_SCHEMA,
203
+ urlconf='shellui_django.mcp.tests.mcp_routing_urlconf',
204
+ service_name='identity',
205
+ )
206
+ with patch('shellui_django.mcp.gateway.tools_from_schema', return_value=[]):
207
+ list_resp = server.handle(
208
+ self.factory.post('/mcp', data=_rpc('tools/list'), content_type='application/json'),
209
+ agent_claims=claims,
210
+ )
211
+ self.assertEqual(list_resp.status_code, 200)
212
+ post.assert_not_called()
213
+ cache.set(
214
+ 'mcp_gateway:route:storage_v1_x',
215
+ {'service_id': 'storage', 'downstream_name': 'storage_v1_x'},
216
+ 60,
217
+ )
218
+ call_resp = server.handle(
219
+ self.factory.post(
220
+ '/mcp',
221
+ data=_rpc('tools/call', name='storage_v1_x', arguments={}),
222
+ content_type='application/json',
223
+ ),
224
+ agent_claims=claims,
225
+ )
226
+ self.assertEqual(call_resp.status_code, 200)
227
+ self.assertIn('Forbidden', json.loads(call_resp.content)['error']['message'])
228
+ post.assert_not_called()
229
+
230
+ @patch('shellui_django.mcp.gateway.requests.post')
231
+ def test_tenant_isolation_on_forwarded_call(self, post):
232
+ from unittest.mock import Mock
233
+
234
+ downstream = {
235
+ 'jsonrpc': '2.0',
236
+ 'id': 1,
237
+ 'result': {'content': [{'type': 'text', 'text': 'ok'}], 'isError': False},
238
+ }
239
+ resp = Mock()
240
+ resp.status_code = 200
241
+ resp.json.return_value = downstream
242
+ post.return_value = resp
243
+
244
+ cache.set(
245
+ 'mcp_gateway:route:storage_v1_run',
246
+ {'service_id': 'storage', 'downstream_name': 'storage_v1_run'},
247
+ 60,
248
+ )
249
+ response = self.server.handle(
250
+ self.factory.post(
251
+ '/mcp',
252
+ data=_rpc('tools/call', name='storage_v1_run', arguments={'body': {'company_id': 10}}),
253
+ content_type='application/json',
254
+ ),
255
+ agent_claims=self.claims_b,
256
+ )
257
+ self.assertEqual(response.status_code, 200)
258
+ self.assertEqual(json.loads(response.content)['result']['content'][0]['text'], 'ok')
259
+ self.assertEqual(post.call_count, 1)
260
+ _args, kwargs = post.call_args
261
+ self.assertEqual(_args[0], STORAGE_MCP)
262
+ auth_header = kwargs['headers']['Authorization']
263
+ self.assertTrue(auth_header.startswith('Bearer '))
264
+ downstream_token = auth_header.split(' ', 1)[1]
265
+ payload = jwt.decode(downstream_token, options={'verify_signature': False})
266
+ self.assertEqual(payload['company_id'], self.agent_b.company_id)
267
+ self.assertEqual(payload['agent_id'], self.agent_b.id)
268
+ self.assertEqual(payload['aud'], STORAGE_MCP)
269
+
270
+ @patch('shellui_django.mcp.gateway.requests.post', side_effect=ConnectionError('down'))
271
+ def test_no_token_in_logs(self, _post):
272
+ config = McpGatewayConfig(
273
+ get_service_urls=lambda: {'identity': IDENTITY_MCP, 'storage': STORAGE_MCP},
274
+ resolve_agent=lambda c: self._agents.get((str(c['agent_id']), int(c['company_id']))),
275
+ mint_downstream_token=lambda _agent, _resource: 'mcp-test-token-leak-check',
276
+ local_service_id='identity',
277
+ )
278
+ server = AggregatingMcpServer(
279
+ gateway=config,
280
+ schema_provider=lambda: LOCAL_SCHEMA,
281
+ urlconf='shellui_django.mcp.tests.mcp_routing_urlconf',
282
+ service_name='identity',
283
+ )
284
+ with self.assertLogs('shellui_django.mcp.gateway', level='WARNING') as logs:
285
+ server.handle(
286
+ self.factory.post('/mcp', data=_rpc('tools/list'), content_type='application/json'),
287
+ agent_claims=self.claims_a,
288
+ )
289
+ joined = '\n'.join(logs.output)
290
+ self.assertNotIn('mcp-test-token-leak-check', joined)
291
+ self.assertNotIn('Bearer ', joined)
292
+
293
+ def test_initialize_lists_connected_services(self):
294
+ response = self._post(_rpc('initialize'), claims=self.claims_a)
295
+ instructions = json.loads(response.content)['result']['instructions']
296
+ self.assertIn('identity', instructions)
297
+ self.assertIn('storage', instructions)
298
+
299
+
300
+ class GatewayHelperTests(SimpleTestCase):
301
+ def test_public_mcp_tools_strips_private_keys(self):
302
+ raw = [{'name': 'a', '_meta': {'x': 1}}]
303
+ self.assertEqual(public_mcp_tools(raw), [{'name': 'a'}])
File without changes