tortoise-graph 0.2.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.
- tortoise/__init__.py +45 -0
- tortoise/__main__.py +1865 -0
- tortoise/analyze.py +473 -0
- tortoise/api.py +303 -0
- tortoise/archived/search_legacy.py +31 -0
- tortoise/audit.py +236 -0
- tortoise/audit_events.py +284 -0
- tortoise/auth.py +107 -0
- tortoise/backup.py +155 -0
- tortoise/config.py +99 -0
- tortoise/connector_loader.py +74 -0
- tortoise/connectors/__init__.py +5 -0
- tortoise/connectors/github.py +432 -0
- tortoise/connectors/github_docs.py +146 -0
- tortoise/connectors/linear.py +199 -0
- tortoise/connectors/slack.py +222 -0
- tortoise/consistency.py +132 -0
- tortoise/crypto.py +52 -0
- tortoise/deployment.py +62 -0
- tortoise/domain_loader.py +142 -0
- tortoise/dream.py +153 -0
- tortoise/embedded_reaper.py +744 -0
- tortoise/embeddings.py +227 -0
- tortoise/ep.py +534 -0
- tortoise/exceptions.py +16 -0
- tortoise/extractor.py +945 -0
- tortoise/hosted_api.py +1982 -0
- tortoise/hosted_middleware.py +22 -0
- tortoise/idempotency.py +39 -0
- tortoise/ids.py +23 -0
- tortoise/indexer/github_indexer.py +129 -0
- tortoise/ingest.py +614 -0
- tortoise/log.py +29 -0
- tortoise/m0.py +50 -0
- tortoise/mcp_auth.py +337 -0
- tortoise/mcp_client.py +108 -0
- tortoise/mcp_server.py +1356 -0
- tortoise/memory_orchestrator.py +492 -0
- tortoise/memory_scope.py +15 -0
- tortoise/migrate_db.py +244 -0
- tortoise/migrate_kinds.py +141 -0
- tortoise/mining.py +338 -0
- tortoise/models.py +109 -0
- tortoise/monitoring.py +133 -0
- tortoise/navigation.py +216 -0
- tortoise/pack_registry.py +767 -0
- tortoise/pipeline_cli.py +197 -0
- tortoise/projection/__init__.py +913 -0
- tortoise/projection/edges.py +311 -0
- tortoise/projection/entities.py +521 -0
- tortoise/projection/grounding.py +95 -0
- tortoise/projection/propagation.py +114 -0
- tortoise/projection.py +37 -0
- tortoise/quadrature.py +90 -0
- tortoise/query_suggestions.py +194 -0
- tortoise/quota.py +163 -0
- tortoise/ranking.py +280 -0
- tortoise/render.py +108 -0
- tortoise/scripts/manifest.py +67 -0
- tortoise/sdk.py +4713 -0
- tortoise/search_engine.py +887 -0
- tortoise/security.py +268 -0
- tortoise/selfhost.py +157 -0
- tortoise/selfhost_api.py +201 -0
- tortoise/session_continuity.py +82 -0
- tortoise/session_indexer.py +569 -0
- tortoise/shared_state/__init__.py +20 -0
- tortoise/shared_state/concurrency.py +113 -0
- tortoise/shared_state/event_log.py +192 -0
- tortoise/shared_state/events.py +150 -0
- tortoise/shared_state/monitoring.py +87 -0
- tortoise/shared_state/recovery.py +126 -0
- tortoise/shared_state/tests/__init__.py +15 -0
- tortoise/shared_state/tests/test_concurrency.py +123 -0
- tortoise/shared_state/tests/test_events.py +145 -0
- tortoise/shared_state/tests/test_monitoring.py +54 -0
- tortoise/shared_state/tests/test_recovery.py +181 -0
- tortoise/source_credibility.py +306 -0
- tortoise/svbp.py +446 -0
- tortoise/taxonomy.py +71 -0
- tortoise/test_cross_ontology.py +180 -0
- tortoise/test_tortoise_client.py +206 -0
- tortoise/tool_registry.py +805 -0
- tortoise/tortoise_client.py +262 -0
- tortoise/verify_ontology.py +154 -0
- tortoise/version_vector.py +97 -0
- tortoise/weights.py +61 -0
- tortoise_graph-0.2.0.dist-info/METADATA +152 -0
- tortoise_graph-0.2.0.dist-info/RECORD +93 -0
- tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
- tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
- tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
- tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
tortoise/m0.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""M0 spine: transcript file → extractor → JSONL log → projection → grid HTML.
|
|
2
|
+
|
|
3
|
+
python -m tortoise.m0 <transcript.txt> [--out graph.html] [--log events.jsonl]
|
|
4
|
+
|
|
5
|
+
Proves the datatypes, the fold, and the render hang together end to end. No
|
|
6
|
+
FalkorDB, no streaming, no idempotency yet — those are M1+.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from .api import EventAPI
|
|
14
|
+
from .extractor import MockExtractor
|
|
15
|
+
from .log import EventLog
|
|
16
|
+
from .projection import fold, split
|
|
17
|
+
from .render import render
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main(argv=None):
|
|
21
|
+
ap = argparse.ArgumentParser(description="Tortoise M0 spine")
|
|
22
|
+
ap.add_argument("transcript", type=Path)
|
|
23
|
+
ap.add_argument("--out", type=Path, default=Path("graph.html"))
|
|
24
|
+
ap.add_argument("--log", type=Path, default=Path("events.jsonl"))
|
|
25
|
+
args = ap.parse_args(argv)
|
|
26
|
+
|
|
27
|
+
text = args.transcript.read_text(encoding="utf-8")
|
|
28
|
+
source_id = args.transcript.name
|
|
29
|
+
|
|
30
|
+
# fresh log for the spike (idempotent re-ingest is M1)
|
|
31
|
+
if args.log.exists():
|
|
32
|
+
args.log.unlink()
|
|
33
|
+
log = EventLog(args.log)
|
|
34
|
+
api = EventAPI(log, initiated_by="extractor", agent_id=MockExtractor.version)
|
|
35
|
+
|
|
36
|
+
MockExtractor().run(text, source_id, api)
|
|
37
|
+
|
|
38
|
+
points = fold(log.read_all())
|
|
39
|
+
statements, operators = split(points)
|
|
40
|
+
args.out.write_text(render(points, title=f"Tortoise — {source_id}"),
|
|
41
|
+
encoding="utf-8")
|
|
42
|
+
|
|
43
|
+
print(f"transcript : {args.transcript} ({len(text)} chars)")
|
|
44
|
+
print(f"events : {len(log.read_all())} → {args.log}")
|
|
45
|
+
print(f"points : {len(statements)} statements, {len(operators)} operators")
|
|
46
|
+
print(f"render : {args.out}")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
if __name__ == "__main__":
|
|
50
|
+
main()
|
tortoise/mcp_auth.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""MCP HTTP transport auth, rate limit, security headers, SDK resolution (#236).
|
|
2
|
+
|
|
3
|
+
Serves as the auth/rate-limit boundary for the MCP Streamable HTTP endpoint
|
|
4
|
+
mounted at /mcp on the hosted FastAPI app. Imports ONLY tortoise.sdk +
|
|
5
|
+
starlette — mcp_server imports from here (one-directional; no circular import).
|
|
6
|
+
|
|
7
|
+
Design: per-request team-scoped SDK via ContextVar. TeamResolutionMiddleware
|
|
8
|
+
validates the Bearer tt_ token against the control-plane registry
|
|
9
|
+
(apikey_verify) and sets _current_team_id / _transport_mode. Tools resolve the
|
|
10
|
+
request-scoped SDK via _get_team_sdk(). Fail-closed: if _transport_mode is None
|
|
11
|
+
(unset/misconfigured), _safe() rejects ALL operations — it never depends on
|
|
12
|
+
is_dev_mode(), which returns True in hosted production (TORTOISE_API_KEY unset).
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import hmac
|
|
18
|
+
import os
|
|
19
|
+
import time
|
|
20
|
+
from collections import OrderedDict, defaultdict
|
|
21
|
+
from contextvars import ContextVar
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
25
|
+
from starlette.requests import Request
|
|
26
|
+
from starlette.responses import JSONResponse
|
|
27
|
+
|
|
28
|
+
from tortoise.sdk import TortoiseSDK
|
|
29
|
+
|
|
30
|
+
# ── ContextVars ─────────────────────────────────────────────────────────────
|
|
31
|
+
_current_team_id: ContextVar[str | None] = ContextVar("_current_team_id", default=None)
|
|
32
|
+
# #329: resolved team quota limits (from the registry Team node), cached 60s
|
|
33
|
+
# with the auth cache so MCP write tools enforce the SAME limits REST sees.
|
|
34
|
+
_current_team_limits: ContextVar[dict | None] = ContextVar("_current_team_limits", default=None)
|
|
35
|
+
_transport_mode: ContextVar[str | None] = ContextVar("_transport_mode", default=None)
|
|
36
|
+
# Curation group for the active MCP app (#523) — set per request by the app's
|
|
37
|
+
# middleware so the shared tools/list transform filters correctly even when
|
|
38
|
+
# multiple apps exist in one process.
|
|
39
|
+
_tool_group: ContextVar[str | None] = ContextVar("_tool_group", default=None)
|
|
40
|
+
|
|
41
|
+
# mcp_server.py owns lazy SDK init (URI resolution, 3x retry, test-swap
|
|
42
|
+
# pattern). mcp_auth delegates via a function-level import to avoid the
|
|
43
|
+
# circular import (mcp_server imports mcp_auth at module level).
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _get_base_sdk() -> TortoiseSDK:
|
|
47
|
+
"""Lazy module-level SDK for stdio mode. Never touched in HTTP mode.
|
|
48
|
+
|
|
49
|
+
Delegates to tortoise.mcp_server._get_sdk() (the #451 canonical lazy
|
|
50
|
+
init) so there is exactly ONE source of truth for DB resolution. The
|
|
51
|
+
function-level import avoids the mcp_server ↔ mcp_auth cycle.
|
|
52
|
+
"""
|
|
53
|
+
from tortoise import mcp_server as _ms
|
|
54
|
+
return _ms._get_sdk()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ── Team-scoped SDK (D2) ────────────────────────────────────────────────────
|
|
58
|
+
def _get_team_sdk() -> TortoiseSDK:
|
|
59
|
+
"""Request-scoped SDK: team namespace in HTTP mode, base SDK in stdio."""
|
|
60
|
+
team_id = _current_team_id.get()
|
|
61
|
+
if team_id is None:
|
|
62
|
+
return _get_base_sdk()
|
|
63
|
+
return TortoiseSDK(namespace=team_id)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# ── HTTP tool allow-list (derived from registry; #454) ────────────────
|
|
67
|
+
# New tools are EXCLUDED from the tenant HTTP surface unless registered with
|
|
68
|
+
# http_policy=True in tool_registry.py. Zero manual sync — see #454.
|
|
69
|
+
from tortoise.tool_registry import get_http_allowed as _get_http_allowed
|
|
70
|
+
HTTP_ALLOWED: frozenset[str] = _get_http_allowed()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# JSON-RPC error codes (D9)
|
|
74
|
+
ERR_UNAUTHORIZED = -32001
|
|
75
|
+
ERR_RATE_LIMIT = -32002
|
|
76
|
+
ERR_EXCLUDED = -32004
|
|
77
|
+
ERR_REGISTRY = -32005
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _jsonrpc_error(code: int, message: str, data: dict | None = None,
|
|
81
|
+
status: int = 400) -> JSONResponse:
|
|
82
|
+
"""Build an MCP-compatible JSON-RPC error response with an HTTP status."""
|
|
83
|
+
body: dict[str, Any] = {
|
|
84
|
+
"jsonrpc": "2.0",
|
|
85
|
+
"error": {"code": code, "message": message},
|
|
86
|
+
"id": None,
|
|
87
|
+
}
|
|
88
|
+
if data is not None:
|
|
89
|
+
body["error"]["data"] = data
|
|
90
|
+
return JSONResponse(body, status_code=status)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class TeamResolutionMiddleware(BaseHTTPMiddleware):
|
|
94
|
+
"""Bearer tt_ token → team_id ContextVar. 401 pre-tool-leak (D3, D17).
|
|
95
|
+
|
|
96
|
+
Uses TortoiseSDK.apikey_verify() — the same registry O(keys) salted-hash
|
|
97
|
+
scan the REST get_current_team uses. Bounded 60s true-LRU cache protects
|
|
98
|
+
against MCP init bursts.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(self, app, *, max_cache: int = 10000,
|
|
102
|
+
registry_sdk: TortoiseSDK | None = None):
|
|
103
|
+
super().__init__(app)
|
|
104
|
+
self._registry_sdk = registry_sdk # test injection
|
|
105
|
+
self._init_lock = asyncio.Lock()
|
|
106
|
+
self._cache: OrderedDict[str, tuple[float, dict, dict]] = OrderedDict() # (ts, team, limits)
|
|
107
|
+
self._max_cache = max_cache
|
|
108
|
+
|
|
109
|
+
async def _get_registry_sdk(self) -> TortoiseSDK:
|
|
110
|
+
if self._registry_sdk is None:
|
|
111
|
+
async with self._init_lock:
|
|
112
|
+
if self._registry_sdk is None:
|
|
113
|
+
# Delegate to hosted_api._make_sdk (canonical SDK builder —
|
|
114
|
+
# handles TORTOISE_DB_URI vs embedded TORTOISE_DB_PATH vs
|
|
115
|
+
# /data fallback). Function-level import avoids any cycle.
|
|
116
|
+
from tortoise import hosted_api as _ha
|
|
117
|
+
self._registry_sdk = _ha._make_sdk(namespace="registry")
|
|
118
|
+
return self._registry_sdk
|
|
119
|
+
|
|
120
|
+
async def dispatch(self, request: Request, call_next):
|
|
121
|
+
# GET metadata route + DELETE (stateless no-op) skip auth (cycle-2 P1 fix)
|
|
122
|
+
if request.method != "POST":
|
|
123
|
+
return await call_next(request)
|
|
124
|
+
auth = request.headers.get("Authorization", "")
|
|
125
|
+
if not auth.startswith("Bearer ") or not auth[7:].startswith("tt_"):
|
|
126
|
+
return _jsonrpc_error(
|
|
127
|
+
ERR_UNAUTHORIZED,
|
|
128
|
+
"Unauthorized: invalid or missing Bearer token. "
|
|
129
|
+
"Expected format: Authorization: Bearer tt_<key>",
|
|
130
|
+
status=401,
|
|
131
|
+
)
|
|
132
|
+
token = auth[7:]
|
|
133
|
+
now = time.time()
|
|
134
|
+
cached = self._cache.get(token)
|
|
135
|
+
if cached and now - cached[0] < 60:
|
|
136
|
+
team, limits = cached[1], cached[2]
|
|
137
|
+
self._cache.move_to_end(token) # true LRU
|
|
138
|
+
else:
|
|
139
|
+
try:
|
|
140
|
+
sdk = await self._get_registry_sdk()
|
|
141
|
+
team = sdk.apikey_verify(token)
|
|
142
|
+
except Exception:
|
|
143
|
+
# Registry down → 503, never 500/stack-trace
|
|
144
|
+
return _jsonrpc_error(
|
|
145
|
+
ERR_REGISTRY,
|
|
146
|
+
"Authentication temporarily unavailable. Try again shortly.",
|
|
147
|
+
status=503,
|
|
148
|
+
)
|
|
149
|
+
if team is None:
|
|
150
|
+
return _jsonrpc_error(
|
|
151
|
+
ERR_UNAUTHORIZED,
|
|
152
|
+
"Unauthorized: invalid API key. "
|
|
153
|
+
"Expected format: Authorization: Bearer tt_<key>",
|
|
154
|
+
status=401,
|
|
155
|
+
)
|
|
156
|
+
# #329: resolve quota limits (registry Team node) — fail-closed
|
|
157
|
+
# enforcement still applies with defaults if resolution fails.
|
|
158
|
+
from tortoise.quota import resolve_team_limits
|
|
159
|
+
try:
|
|
160
|
+
limits = resolve_team_limits(team["team_id"])
|
|
161
|
+
except Exception:
|
|
162
|
+
limits = {"team_id": team["team_id"]}
|
|
163
|
+
if len(self._cache) >= self._max_cache:
|
|
164
|
+
self._cache.popitem(last=False) # evict LRU
|
|
165
|
+
self._cache[token] = (now, team, limits)
|
|
166
|
+
_current_team_id.set(team["team_id"])
|
|
167
|
+
_current_team_limits.set(limits)
|
|
168
|
+
_transport_mode.set("http")
|
|
169
|
+
# No .reset() needed: Starlette creates a fresh asyncio task per request;
|
|
170
|
+
# ContextVars are copy-on-write per task (verified by
|
|
171
|
+
# test_contextvar_not_leaked_to_next_request).
|
|
172
|
+
return await call_next(request)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class TransportModeMiddleware(BaseHTTPMiddleware):
|
|
176
|
+
"""Self-host transport init (auth_mode="static" | "none", #338).
|
|
177
|
+
|
|
178
|
+
TeamResolutionMiddleware sets these ContextVars for tenant mode; selfhost
|
|
179
|
+
modes have no tenant resolution, so this middleware initializes them:
|
|
180
|
+
_transport_mode="http" (passes _safe()'s fail-closed gate — auth was
|
|
181
|
+
enforced at transport: static key check or localhost-bound none mode) and
|
|
182
|
+
_current_team_id="selfhost" (isolated team_selfhost graph namespace).
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
async def dispatch(self, request: Request, call_next):
|
|
186
|
+
_transport_mode.set("http")
|
|
187
|
+
_current_team_id.set("selfhost")
|
|
188
|
+
return await call_next(request)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class ToolGroupMiddleware(BaseHTTPMiddleware):
|
|
192
|
+
"""Set the curation group ContextVar per request (#523).
|
|
193
|
+
|
|
194
|
+
The tools/list transform is registered ONCE on the shared module-level mcp
|
|
195
|
+
instance, so per-app group scoping must come from request context — not
|
|
196
|
+
capture at app construction (which would let the first app win).
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
def __init__(self, app, *, tool_group: str | None):
|
|
200
|
+
super().__init__(app)
|
|
201
|
+
self._tool_group = tool_group
|
|
202
|
+
|
|
203
|
+
async def dispatch(self, request: Request, call_next):
|
|
204
|
+
_tool_group.set(self._tool_group)
|
|
205
|
+
return await call_next(request)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class StaticKeyMiddleware(BaseHTTPMiddleware):
|
|
209
|
+
"""Static API-key auth for single-tenant self-host (auth_mode="static").
|
|
210
|
+
|
|
211
|
+
Validates a single configured key (TORTOISE_API_KEY) with constant-time
|
|
212
|
+
compare. Fail-closed: if api_key is None (misconfiguration), all POSTs
|
|
213
|
+
are rejected 503 — never allow unauthenticated writes.
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
def __init__(self, app, *, api_key: str | None):
|
|
217
|
+
super().__init__(app)
|
|
218
|
+
self._api_key = api_key
|
|
219
|
+
|
|
220
|
+
async def dispatch(self, request: Request, call_next):
|
|
221
|
+
# GET metadata route + DELETE (stateless no-op) skip auth, matching
|
|
222
|
+
# TeamResolutionMiddleware behavior.
|
|
223
|
+
if request.method != "POST":
|
|
224
|
+
return await call_next(request)
|
|
225
|
+
if self._api_key is None:
|
|
226
|
+
return JSONResponse(
|
|
227
|
+
{"jsonrpc": "2.0", "error": {"code": -32099, "message": "Static auth misconfigured: no API key set."}, "id": None},
|
|
228
|
+
status_code=503,
|
|
229
|
+
)
|
|
230
|
+
auth = request.headers.get("Authorization", "")
|
|
231
|
+
if not auth.startswith("Bearer "):
|
|
232
|
+
return _jsonrpc_error(
|
|
233
|
+
ERR_UNAUTHORIZED,
|
|
234
|
+
"Unauthorized: missing Bearer token.",
|
|
235
|
+
status=401,
|
|
236
|
+
)
|
|
237
|
+
token = auth[7:]
|
|
238
|
+
if not hmac.compare_digest(token.encode(), self._api_key.encode()):
|
|
239
|
+
return _jsonrpc_error(
|
|
240
|
+
ERR_UNAUTHORIZED,
|
|
241
|
+
"Unauthorized: invalid API key.",
|
|
242
|
+
status=401,
|
|
243
|
+
)
|
|
244
|
+
return await call_next(request)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class MCPRateLimitMiddleware(BaseHTTPMiddleware):
|
|
248
|
+
"""Per-key token bucket for ALL POSTs to /mcp (D8). 429 JSON-RPC -32002.
|
|
249
|
+
|
|
250
|
+
limit_get=True (parent app / #525): rate-limits GETs too — /v1/* endpoints
|
|
251
|
+
accept the static key and would otherwise be an unthrottled brute-force
|
|
252
|
+
surface. The /mcp sub-app keeps the default (GET = metadata/SSE only).
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
def __init__(self, app, max_per_minute: int = 100, limit_get: bool = False,
|
|
256
|
+
paths_prefix: tuple[str, ...] = ()):
|
|
257
|
+
super().__init__(app)
|
|
258
|
+
self.max_per_minute = max_per_minute
|
|
259
|
+
self._limit_get = limit_get
|
|
260
|
+
self._paths_prefix = paths_prefix
|
|
261
|
+
self._buckets: dict[str, list[float]] = defaultdict(list)
|
|
262
|
+
self._lock = asyncio.Lock()
|
|
263
|
+
self._last_cleanup = time.time()
|
|
264
|
+
self._disabled = os.environ.get("RATE_LIMIT_DISABLED") == "1"
|
|
265
|
+
|
|
266
|
+
async def dispatch(self, request: Request, call_next):
|
|
267
|
+
if self._disabled:
|
|
268
|
+
return await call_next(request)
|
|
269
|
+
if self._paths_prefix and not any(request.url.path.startswith(p) for p in self._paths_prefix):
|
|
270
|
+
return await call_next(request) # scope to /v1 (code-review P2, #525)
|
|
271
|
+
if request.method != "POST" and not self._limit_get:
|
|
272
|
+
return await call_next(request) # GET metadata not rate-limited (unless limit_get)
|
|
273
|
+
auth = request.headers.get("Authorization", "")
|
|
274
|
+
if auth.startswith("Bearer "):
|
|
275
|
+
key_id = auth[7:]
|
|
276
|
+
else:
|
|
277
|
+
# IP fallback; guard None client
|
|
278
|
+
ip = request.client.host if request.client and request.client.host else "unknown"
|
|
279
|
+
key_id = f"ip:{ip}"
|
|
280
|
+
now = time.time()
|
|
281
|
+
async with self._lock:
|
|
282
|
+
# Periodic cleanup: filter stale timestamps from ALL buckets, then
|
|
283
|
+
# prune empty ones (code-review fix — mirrors hosted_api's
|
|
284
|
+
# RateLimitMiddleware pattern; prevents one-off-IP bucket growth)
|
|
285
|
+
if now - self._last_cleanup > 60:
|
|
286
|
+
stale = []
|
|
287
|
+
for k, v in list(self._buckets.items()):
|
|
288
|
+
v[:] = [t for t in v if now - t < 60]
|
|
289
|
+
if not v:
|
|
290
|
+
stale.append(k)
|
|
291
|
+
for k in stale:
|
|
292
|
+
del self._buckets[k]
|
|
293
|
+
self._last_cleanup = now
|
|
294
|
+
bucket = self._buckets[key_id]
|
|
295
|
+
bucket[:] = [t for t in bucket if now - t < 60]
|
|
296
|
+
if len(bucket) >= self.max_per_minute:
|
|
297
|
+
resp = _jsonrpc_error(ERR_RATE_LIMIT, "Rate limit exceeded",
|
|
298
|
+
{"retry_after": 30}, status=429)
|
|
299
|
+
resp.headers["Retry-After"] = "30"
|
|
300
|
+
return resp
|
|
301
|
+
bucket.append(now)
|
|
302
|
+
return await call_next(request)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
|
|
306
|
+
"""HSTS + X-Content-Type-Options + X-Frame-Options on /mcp responses.
|
|
307
|
+
|
|
308
|
+
Parent FastAPI middleware does NOT propagate to mounted sub-apps, so the
|
|
309
|
+
MCP stack needs its own security headers.
|
|
310
|
+
"""
|
|
311
|
+
|
|
312
|
+
async def dispatch(self, request: Request, call_next):
|
|
313
|
+
resp = await call_next(request)
|
|
314
|
+
resp.headers.setdefault("Strict-Transport-Security",
|
|
315
|
+
"max-age=31536000; includeSubDomains")
|
|
316
|
+
resp.headers.setdefault("X-Content-Type-Options", "nosniff")
|
|
317
|
+
resp.headers.setdefault("X-Frame-Options", "DENY")
|
|
318
|
+
return resp
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
class RequestBodySizeMiddleware(BaseHTTPMiddleware):
|
|
322
|
+
"""Reject POST bodies > 1MB (D13).
|
|
323
|
+
|
|
324
|
+
Caveat: chunked transfer-encoding has NO content-length header — the
|
|
325
|
+
header check misses it. Infrastructure layer (Fly/nginx client_max_body_size
|
|
326
|
+
or uvicorn limit) is the primary defense; this middleware is best-effort.
|
|
327
|
+
"""
|
|
328
|
+
|
|
329
|
+
MAX_BODY = 1_000_000
|
|
330
|
+
|
|
331
|
+
async def dispatch(self, request: Request, call_next):
|
|
332
|
+
if request.method == "POST":
|
|
333
|
+
length = request.headers.get("content-length")
|
|
334
|
+
if length and int(length) > self.MAX_BODY:
|
|
335
|
+
return _jsonrpc_error(-32600, "Request body too large (max 1MB)",
|
|
336
|
+
status=413)
|
|
337
|
+
return await call_next(request)
|
tortoise/mcp_client.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Tortoise MCP client (#338 T2.1).
|
|
2
|
+
|
|
3
|
+
Thin wrapper over fastmcp's built-in client (StreamableHttpTransport +
|
|
4
|
+
BearerAuth) — zero new third-party deps. Connects to a Tortoise daemon
|
|
5
|
+
(self-host http://localhost:8000/mcp or hosted endpoint) and calls the
|
|
6
|
+
registry tool surface (tool_registry #510, single source of truth).
|
|
7
|
+
|
|
8
|
+
Sync wrappers over fastmcp's async API via asyncio.run() — script callers
|
|
9
|
+
(e.g. the minutes bridge) stay synchronous.
|
|
10
|
+
|
|
11
|
+
Graceful degradation: availability/status never raise — a down daemon
|
|
12
|
+
reports "tortoise_unavailable" so script callers skip cleanly.
|
|
13
|
+
|
|
14
|
+
Seeds #526 (thin driver package — this client is the future pip surface).
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import logging
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
_logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
_DEFAULT_URL = "http://localhost:8000/mcp"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _mcp_url() -> str:
|
|
28
|
+
import os
|
|
29
|
+
return os.environ.get("TORTOISE_MCP_URL", _DEFAULT_URL)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _api_key() -> str | None:
|
|
33
|
+
import os
|
|
34
|
+
return os.environ.get("TORTOISE_API_KEY")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _run(coro):
|
|
38
|
+
"""Run an async fastmcp call from sync code (script-friendly)."""
|
|
39
|
+
return asyncio.run(coro)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get_client():
|
|
43
|
+
"""Build a fastmcp Client bound to TORTOISE_MCP_URL (+ BearerAuth).
|
|
44
|
+
|
|
45
|
+
Lazy imports keep the module importable when fastmcp is unavailable
|
|
46
|
+
(graceful degradation for scripts).
|
|
47
|
+
"""
|
|
48
|
+
from fastmcp.client import Client
|
|
49
|
+
from fastmcp.client.auth.bearer import BearerAuth
|
|
50
|
+
from fastmcp.client.transports.http import StreamableHttpTransport
|
|
51
|
+
|
|
52
|
+
transport = StreamableHttpTransport(url=_mcp_url())
|
|
53
|
+
auth = BearerAuth(_api_key()) if _api_key() else None
|
|
54
|
+
return Client(
|
|
55
|
+
transport,
|
|
56
|
+
auth=auth,
|
|
57
|
+
client_info={"name": "tortoise-mcp-client", "version": "0.1.0"},
|
|
58
|
+
auto_initialize=True,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def status() -> dict[str, Any]:
|
|
63
|
+
"""Connectivity + surface probe. Never raises.
|
|
64
|
+
|
|
65
|
+
Returns {"status": "ok", "url": ..., "tools": N} when reachable, else
|
|
66
|
+
{"status": "tortoise_unavailable", "url": ..., "error": ...}.
|
|
67
|
+
"""
|
|
68
|
+
async def _probe() -> dict[str, Any]:
|
|
69
|
+
client = get_client()
|
|
70
|
+
async with client:
|
|
71
|
+
tools = await client.list_tools()
|
|
72
|
+
return {"status": "ok", "url": _mcp_url(), "tools": len(tools)}
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
return _run(_probe())
|
|
76
|
+
except Exception as exc: # noqa: BLE001 — probe reports, never raises
|
|
77
|
+
_logger.debug("tortoise unavailable: %s", exc)
|
|
78
|
+
return {"status": "tortoise_unavailable", "url": _mcp_url(), "error": str(exc)}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def available() -> bool:
|
|
82
|
+
"""True when the daemon is reachable (status probe)."""
|
|
83
|
+
return status().get("status") == "ok"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def list_tools() -> list[str]:
|
|
87
|
+
"""Names of the tools exposed by the daemon (registry surface)."""
|
|
88
|
+
async def _list() -> list[str]:
|
|
89
|
+
client = get_client()
|
|
90
|
+
async with client:
|
|
91
|
+
tools = await client.list_tools()
|
|
92
|
+
return [t.name for t in tools]
|
|
93
|
+
|
|
94
|
+
return _run(_list())
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def call_tool(name: str, arguments: dict[str, Any] | None = None) -> Any:
|
|
98
|
+
"""Call an MCP tool (e.g. tortoise_create_point) and return its result.
|
|
99
|
+
|
|
100
|
+
Raises on transport/auth failure — callers that want graceful behavior
|
|
101
|
+
should check `available()` first (or catch exceptions).
|
|
102
|
+
"""
|
|
103
|
+
async def _call() -> Any:
|
|
104
|
+
client = get_client()
|
|
105
|
+
async with client:
|
|
106
|
+
return await client.call_tool(name, arguments or {})
|
|
107
|
+
|
|
108
|
+
return _run(_call())
|