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/mcp_server.py
ADDED
|
@@ -0,0 +1,1356 @@
|
|
|
1
|
+
"""TORT-MCP-001: MCP server wrapping TortoiseSDK. Stdio transport, ~10 tools."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Literal
|
|
10
|
+
|
|
11
|
+
from fastmcp import FastMCP
|
|
12
|
+
from mcp.types import ToolAnnotations
|
|
13
|
+
from tortoise.auth import is_dev_mode as _is_dev_mode
|
|
14
|
+
from tortoise.sdk import TortoiseSDK
|
|
15
|
+
from tortoise import monitoring
|
|
16
|
+
from tortoise.mcp_auth import (_current_team_id, _transport_mode, _get_team_sdk,
|
|
17
|
+
HTTP_ALLOWED, ERR_EXCLUDED)
|
|
18
|
+
|
|
19
|
+
_log = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
def _load_dotenv(path: str | None = None) -> None:
|
|
22
|
+
"""Tiny .env loader — repo-root .env, KEY=VALUE lines, no new deps.
|
|
23
|
+
|
|
24
|
+
Only sets environment keys that are empty/unset, so an explicit
|
|
25
|
+
TORTOISE_DB_URI in the process env always wins. Mirrors the hosted
|
|
26
|
+
entrypoint philosophy: the DB target must be explicit, never accidental.
|
|
27
|
+
"""
|
|
28
|
+
if path is None:
|
|
29
|
+
path = os.path.join(
|
|
30
|
+
os.path.dirname(os.path.abspath(__file__)), "..", ".env"
|
|
31
|
+
)
|
|
32
|
+
if not os.path.exists(path):
|
|
33
|
+
return
|
|
34
|
+
try:
|
|
35
|
+
for raw in Path(path).read_text().splitlines():
|
|
36
|
+
line = raw.strip()
|
|
37
|
+
if not line or line.startswith("#"):
|
|
38
|
+
continue
|
|
39
|
+
if line.startswith("export "):
|
|
40
|
+
line = line[len("export "):]
|
|
41
|
+
if "=" not in line:
|
|
42
|
+
continue
|
|
43
|
+
key, _, value = line.partition("=")
|
|
44
|
+
key = key.strip()
|
|
45
|
+
# python-dotenv semantics: quoted values are literal (no inline
|
|
46
|
+
# comment stripping); unquoted values strip inline comments
|
|
47
|
+
# (whitespace + '#'). A bare '#' in an unquoted value is preserved.
|
|
48
|
+
value = value.strip()
|
|
49
|
+
if value[:1] in ('"', "'") and value[-1:] == value[:1]:
|
|
50
|
+
value = value[1:-1]
|
|
51
|
+
else:
|
|
52
|
+
value = value.split(" #", 1)[0].strip()
|
|
53
|
+
# Only fill keys that are absent — never override an explicitly
|
|
54
|
+
# set (even empty) environment variable.
|
|
55
|
+
if key and key not in os.environ:
|
|
56
|
+
os.environ[key] = value
|
|
57
|
+
except OSError as e:
|
|
58
|
+
_log.debug("Could not read .env (%s): %s — continuing without it", path, e)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
if "pytest" not in sys.modules:
|
|
62
|
+
_load_dotenv() # resolve TORTOISE_DB_URI from repo-root .env (skipped under pytest)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ── Safety annotations ───────────────────────────────────────────
|
|
66
|
+
# readOnlyHint=true: agent auto-approves, no confirmation needed
|
|
67
|
+
# destructiveHint=true: agent MUST get human confirmation
|
|
68
|
+
# idempotentHint=true: repeated calls have no extra side effects
|
|
69
|
+
|
|
70
|
+
mcp = FastMCP("tortoise")
|
|
71
|
+
|
|
72
|
+
# ── Lazy SDK initialization (#451) ─────────────────────────────────
|
|
73
|
+
# sdk is None at import time — _get_sdk() lazily resolves and connects
|
|
74
|
+
# on first call. Prevents import-time network I/O (3x retry + sys.exit)
|
|
75
|
+
# in environments without a live FalkorDB server.
|
|
76
|
+
_sdk = None
|
|
77
|
+
sdk = None # module-level override point (test swap pattern: mcp_mod.sdk = test_sdk)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _get_sdk():
|
|
81
|
+
"""Lazily resolve TORTOISE_DB_URI, connect, and return TortoiseSDK.
|
|
82
|
+
|
|
83
|
+
Cached after first successful call. URI branches + 3x Docker retry
|
|
84
|
+
+ sys.exit(1) on exhaustion are preserved exactly — but deferred
|
|
85
|
+
from import time to first tool call (or first call to main()).
|
|
86
|
+
The module-level ``sdk`` attribute acts as an override (set by
|
|
87
|
+
test_enumeration_surfaces.py swap pattern) — when non-None it is
|
|
88
|
+
returned directly, bypassing lazy init.
|
|
89
|
+
|
|
90
|
+
Error surface: exceptions here (connection failure, sys.exit on retry
|
|
91
|
+
exhaustion) propagate BEFORE _safe() wrapping in tool bodies (call
|
|
92
|
+
arguments are evaluated first). In normal operation main() calls
|
|
93
|
+
_get_sdk() before mcp.run(), so failures surface at server startup —
|
|
94
|
+
equivalent to the pre-#451 import-time behavior. Only callers that
|
|
95
|
+
invoke mcp.run() directly without main() see an unwrapped error.
|
|
96
|
+
|
|
97
|
+
Reset semantics: restoring ``sdk = None`` after a test swap falls
|
|
98
|
+
through to the CACHED _sdk instance — it does not re-connect. Set
|
|
99
|
+
both ``sdk`` and ``_sdk`` to None to force re-initialization.
|
|
100
|
+
"""
|
|
101
|
+
global _sdk
|
|
102
|
+
# Module-level sdk override (test swap pattern) takes priority
|
|
103
|
+
if sdk is not None:
|
|
104
|
+
return sdk
|
|
105
|
+
if _sdk is not None:
|
|
106
|
+
return _sdk
|
|
107
|
+
|
|
108
|
+
_db_uri = os.environ.get("TORTOISE_DB_URI", "")
|
|
109
|
+
if _db_uri.startswith(("docker://", "redis://", "rediss://")):
|
|
110
|
+
from tortoise.projection import FalkorProjection
|
|
111
|
+
import time as _time
|
|
112
|
+
_sdk = TortoiseSDK()
|
|
113
|
+
# Retry Docker connection 3x with backoff; exit on exhaustion (#25 P3a, #32)
|
|
114
|
+
for attempt in range(3):
|
|
115
|
+
try:
|
|
116
|
+
_sdk._proj = FalkorProjection.from_uri(_db_uri)
|
|
117
|
+
if attempt > 0:
|
|
118
|
+
_log.warning("Docker connection succeeded on attempt %d", attempt + 1)
|
|
119
|
+
break
|
|
120
|
+
except Exception as e:
|
|
121
|
+
if attempt < 2:
|
|
122
|
+
_log.warning("Docker connection attempt %d failed: %s — retrying in 2s", attempt + 1, e)
|
|
123
|
+
_time.sleep(2)
|
|
124
|
+
else:
|
|
125
|
+
_log.error("Docker connection failed after 3 attempts. Set TORTOISE_DB_URI or ensure FalkorDB is running.")
|
|
126
|
+
sys.exit(1)
|
|
127
|
+
elif _db_uri:
|
|
128
|
+
# File path — use Lite mode (backward compat: bare non-docker URI).
|
|
129
|
+
# resolve_db_path() rejects relative paths + applies canonical default.
|
|
130
|
+
from tortoise.config import resolve_db_path as _resolve_db_path
|
|
131
|
+
_sdk = TortoiseSDK(db_path=_resolve_db_path(_db_uri))
|
|
132
|
+
else:
|
|
133
|
+
# No URI: default to canonical embedded path via resolve_db_path()
|
|
134
|
+
from tortoise.config import resolve_db_path as _resolve_db_path
|
|
135
|
+
_sdk = TortoiseSDK(db_path=_resolve_db_path())
|
|
136
|
+
return _sdk
|
|
137
|
+
|
|
138
|
+
# Announce auth mode at startup
|
|
139
|
+
if _is_dev_mode():
|
|
140
|
+
_log.warning("TORTOISE_API_KEY not set — running in dev mode (no auth)")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# #329: node/edge-creating MCP write tools that MUST be quota-gated. Completeness
|
|
144
|
+
# is enforced by an introspective test (tests/test_mcp_http.py) that scans every
|
|
145
|
+
# HTTP_ALLOWED tool body for node/edge-creating SDK calls and asserts membership.
|
|
146
|
+
# New node/edge-creating tools MUST be added here.
|
|
147
|
+
_QUOTA_GATED: frozenset[str] = frozenset({
|
|
148
|
+
"tortoise_create_point", "tortoise_create_operator", "tortoise_create_event",
|
|
149
|
+
"tortoise_create_subject", "tortoise_create_object", "tortoise_create_document",
|
|
150
|
+
"tortoise_create_source", "tortoise_checkpoint", "tortoise_file_decision",
|
|
151
|
+
"tortoise_update_entity", "tortoise_update_point", "tortoise_diary_write",
|
|
152
|
+
"tortoise_mitigate_operator",
|
|
153
|
+
# edge-creating tools — edge growth is the same graph-flood family
|
|
154
|
+
"tortoise_create_edge", "tortoise_supersede", "tortoise_invalidate",
|
|
155
|
+
# delegates to hosted_api._seed_demo_graph (creates the 4-layer demo graph)
|
|
156
|
+
"tortoise_onboarding_demo_create",
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# #329: per-team per-minute LLM-call budget for tortoise_analyze (operator LLM
|
|
161
|
+
# keys back outbound calls; the rate limiter alone is not the bound).
|
|
162
|
+
_ANALYZE_LLM_BUDGET: dict[str, list[float]] = {}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _analyze_llm_budget_available() -> bool:
|
|
166
|
+
"""True if this team still has analyze LLM budget this minute (HTTP only).
|
|
167
|
+
|
|
168
|
+
Beyond budget the tool degrades to keyword-only classification (no paid
|
|
169
|
+
outbound call). Stdio (no team context) is not budgeted.
|
|
170
|
+
"""
|
|
171
|
+
import time as _t
|
|
172
|
+
from tortoise.mcp_auth import _current_team_id
|
|
173
|
+
from tortoise.quota import MAX_ANALYZE_LLM_PER_MIN
|
|
174
|
+
team_id = _current_team_id.get()
|
|
175
|
+
if not team_id:
|
|
176
|
+
return True # stdio/operator — no team budget accounting
|
|
177
|
+
now_ts = _t.time()
|
|
178
|
+
bucket = _ANALYZE_LLM_BUDGET.setdefault(team_id, [])
|
|
179
|
+
bucket[:] = [ts for ts in bucket if now_ts - ts < 60]
|
|
180
|
+
# prune -> check -> append (never pop between check and append — that
|
|
181
|
+
# orphans the appended timestamp and silently disables the budget)
|
|
182
|
+
if len(bucket) >= MAX_ANALYZE_LLM_PER_MIN:
|
|
183
|
+
return False
|
|
184
|
+
bucket.append(now_ts)
|
|
185
|
+
return True
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _enforce_quota(resource: str = "points") -> None:
|
|
189
|
+
"""#329: fail-closed team quota pre-write for MCP write tools.
|
|
190
|
+
|
|
191
|
+
HTTP mode: limits come from the middleware-resolved ContextVar (same
|
|
192
|
+
limits REST sees); fallback resolves from the registry. Stdio mode
|
|
193
|
+
(no team context) → skip — operator/trusted (batch caps still apply).
|
|
194
|
+
"""
|
|
195
|
+
from tortoise.mcp_auth import _current_team_id, _current_team_limits
|
|
196
|
+
from tortoise.quota import enforce_team_limit, resolve_team_limits
|
|
197
|
+
team_id = _current_team_id.get()
|
|
198
|
+
if not team_id:
|
|
199
|
+
return # stdio/operator — no team context
|
|
200
|
+
limits = _current_team_limits.get()
|
|
201
|
+
if limits is None:
|
|
202
|
+
limits = resolve_team_limits(team_id)
|
|
203
|
+
# Count on the SAME team SDK the tool writes to (identical connection),
|
|
204
|
+
# so the count and the write can never target different databases.
|
|
205
|
+
enforce_team_limit(limits, resource, sdk=_get_team_sdk())
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _quota_gated(fn, resource: str = "points"):
|
|
209
|
+
"""Wrap a bound SDK method with a pre-write quota check.
|
|
210
|
+
|
|
211
|
+
Preserves the bound-callable style (_safe(_get_team_sdk().name, ...)):
|
|
212
|
+
the quota check runs INSIDE _safe's try so errors surface as structured
|
|
213
|
+
error dicts (see _safe's QuotaExceededError/QuotaCheckError mapping).
|
|
214
|
+
"""
|
|
215
|
+
def _gated(*args, **kwargs):
|
|
216
|
+
_enforce_quota(resource)
|
|
217
|
+
return fn(*args, **kwargs)
|
|
218
|
+
return _gated
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _safe(fn, *args, **kwargs):
|
|
222
|
+
"""Call fn; return error dict on exception instead of raising.
|
|
223
|
+
|
|
224
|
+
#329: QuotaExceededError → {"error", "code": ERR_QUOTA}; QuotaCheckError
|
|
225
|
+
→ {"error", "code": ERR_QUOTA_SERVER} (fail-closed counting).
|
|
226
|
+
|
|
227
|
+
Transport-aware auth gate (#236). Fail-closed: if _transport_mode is None
|
|
228
|
+
(unset/misconfigured) ALL operations reject. HTTP mode trusts transport-level
|
|
229
|
+
auth (TeamResolutionMiddleware 401'd pre-dispatch). Stdio mode keeps the
|
|
230
|
+
dev-mode gate. NEVER depends on is_dev_mode() alone — it returns True in
|
|
231
|
+
hosted production (TORTOISE_API_KEY unset), which would silently bypass auth.
|
|
232
|
+
"""
|
|
233
|
+
mode = _transport_mode.get()
|
|
234
|
+
if mode is None:
|
|
235
|
+
return {
|
|
236
|
+
"error": (
|
|
237
|
+
"Authentication required. MCP transport mode not initialized."
|
|
238
|
+
)
|
|
239
|
+
}
|
|
240
|
+
if mode == "http":
|
|
241
|
+
pass # auth enforced at transport (TeamResolutionMiddleware)
|
|
242
|
+
elif mode == "stdio":
|
|
243
|
+
if not _is_dev_mode():
|
|
244
|
+
return {
|
|
245
|
+
"error": (
|
|
246
|
+
"Authentication required. The MCP stdio transport cannot "
|
|
247
|
+
"carry auth tokens. Use an authenticated HTTP endpoint "
|
|
248
|
+
"(tortoise health-server) with Authorization: Bearer <key> "
|
|
249
|
+
"header, or unset TORTOISE_API_KEY for dev mode."
|
|
250
|
+
)
|
|
251
|
+
}
|
|
252
|
+
else:
|
|
253
|
+
# Unknown transport mode — fail-closed (code-review fix)
|
|
254
|
+
return {"error": f"Unknown MCP transport mode: {mode!r}"}
|
|
255
|
+
try:
|
|
256
|
+
result = fn(*args, **kwargs)
|
|
257
|
+
return result
|
|
258
|
+
except Exception as e:
|
|
259
|
+
monitoring.record_error()
|
|
260
|
+
from tortoise.quota import QuotaCheckError, QuotaExceededError
|
|
261
|
+
if isinstance(e, QuotaExceededError):
|
|
262
|
+
return {"error": str(e), "code": ERR_QUOTA}
|
|
263
|
+
if isinstance(e, QuotaCheckError):
|
|
264
|
+
return {"error": str(e), "code": ERR_QUOTA_SERVER}
|
|
265
|
+
msg = str(e)
|
|
266
|
+
# Sanitize: strip hostnames, ports, passwords from error messages (#43)
|
|
267
|
+
import re
|
|
268
|
+
msg = re.sub(r'://[^@]*@', '://***@', msg) # password in URI
|
|
269
|
+
msg = re.sub(r'(host=|at |to )[\w.-]+(:\d+)?', r'\1***', msg) # host:port
|
|
270
|
+
return {"error": msg}
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _scrub_analyze_answer(answer: str) -> str:
|
|
274
|
+
"""#329: boundary scrub for analyze() answers — strip common internals.
|
|
275
|
+
|
|
276
|
+
analyze() already redacts its own error paths; this is defense-in-depth
|
|
277
|
+
against future regressions (paths, hostnames, credentials).
|
|
278
|
+
"""
|
|
279
|
+
import re
|
|
280
|
+
answer = re.sub(r"://[^@\s]*@", "://***@", answer)
|
|
281
|
+
answer = re.sub(r"(?P<pre>[/\\])\w+\.(?:db|jsonl|log)(?=[\"'\s,)])", r"\g<pre>***", answer)
|
|
282
|
+
return answer[:2000]
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
# #329: quota error codes (registered alongside the other ERR_* in mcp_auth).
|
|
286
|
+
ERR_QUOTA = -32006
|
|
287
|
+
ERR_QUOTA_SERVER = -32007
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _http_excluded_error() -> dict:
|
|
291
|
+
"""#236: JSON-RPC error for tools excluded from the tenant HTTP surface (D4)."""
|
|
292
|
+
return {
|
|
293
|
+
"jsonrpc": "2.0",
|
|
294
|
+
"error": {
|
|
295
|
+
"code": ERR_EXCLUDED,
|
|
296
|
+
"message": "This tool is not available over HTTP. "
|
|
297
|
+
"Use the hosted REST API or stdio MCP.",
|
|
298
|
+
},
|
|
299
|
+
"id": None,
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _parse(v: Any) -> Any:
|
|
304
|
+
"""Parse JSON string inputs from LLM agents into native Python types.
|
|
305
|
+
|
|
306
|
+
FastMCP strict-typed schemas reject JSON strings for list/dict params.
|
|
307
|
+
LLM agents naturally emit JSON strings. This bridges the gap.
|
|
308
|
+
"""
|
|
309
|
+
if isinstance(v, str):
|
|
310
|
+
try:
|
|
311
|
+
return json.loads(v)
|
|
312
|
+
except (json.JSONDecodeError, TypeError):
|
|
313
|
+
return v
|
|
314
|
+
return v
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def tortoise_create_point(kind: str, content: str,
|
|
318
|
+
authoredBy: str | None = None,
|
|
319
|
+
props: Any = None,
|
|
320
|
+
dedup: bool = True) -> dict:
|
|
321
|
+
"""Create a Point node (statement, decision, vision, hypothesis, etc.).
|
|
322
|
+
|
|
323
|
+
dedup=True (default): idempotent — returns existing Point if content matches.
|
|
324
|
+
dedup=False: force-create even if content is identical.
|
|
325
|
+
|
|
326
|
+
→ See /skill:tortoise-graph-reasoning for pointKind guidance:
|
|
327
|
+
evidence is a role (not a kind), use Source for provenance.
|
|
328
|
+
"""
|
|
329
|
+
props = _parse(props)
|
|
330
|
+
merged = dict(props or {})
|
|
331
|
+
if authoredBy:
|
|
332
|
+
merged["authoredBy"] = authoredBy
|
|
333
|
+
# #329 tag batch cap + value validation
|
|
334
|
+
from tortoise.quota import MAX_TAGS_PER_POINT
|
|
335
|
+
tags = merged.get("tags") or []
|
|
336
|
+
if isinstance(tags, list):
|
|
337
|
+
if len(tags) > MAX_TAGS_PER_POINT:
|
|
338
|
+
return {"error": f"tags exceed the cap ({MAX_TAGS_PER_POINT})", "code": ERR_QUOTA}
|
|
339
|
+
for t in tags:
|
|
340
|
+
if not isinstance(t, str) or not t.strip() or len(t) > 200:
|
|
341
|
+
return {"error": f"invalid tag value: {t!r} (must be a non-empty string ≤ 200 chars)"}
|
|
342
|
+
merged["dedup"] = dedup
|
|
343
|
+
return _safe(_quota_gated(_get_team_sdk().create_point, "points"), kind, content, **merged)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def tortoise_query(kind: str | None = None,
|
|
347
|
+
filters: Any = None,
|
|
348
|
+
text: str | None = None,
|
|
349
|
+
order_by: str | None = None,
|
|
350
|
+
min_confidence: float | None = None,
|
|
351
|
+
entity_type: str = "point",
|
|
352
|
+
limit: int = 100) -> list[dict] | dict:
|
|
353
|
+
"""Query points by pointKind and/or property filters.
|
|
354
|
+
|
|
355
|
+
When text is provided, routes through tortoise_fts_query() for hybrid search.
|
|
356
|
+
When text is None, uses existing structural query.
|
|
357
|
+
entity_type: 'point' (default), 'event', 'subject', 'document', 'object', 'operator', or 'source'.
|
|
358
|
+
|
|
359
|
+
When results are empty and a kind filter was provided, a 'suggestion'
|
|
360
|
+
key is added to the response with a hint or "did you mean" suggestion.
|
|
361
|
+
"""
|
|
362
|
+
filters = _parse(filters)
|
|
363
|
+
if text:
|
|
364
|
+
return _safe(_get_team_sdk().tortoise_fts_query, text, kind=kind,
|
|
365
|
+
entity_type=entity_type, limit=limit,
|
|
366
|
+
min_confidence=min_confidence or 0.0,
|
|
367
|
+
order_by=order_by or "relevance")
|
|
368
|
+
result = _safe(_get_team_sdk().query, kind, **(filters or {}))
|
|
369
|
+
# If empty results and a kind filter was provided, attach suggestion
|
|
370
|
+
if isinstance(result, list) and len(result) == 0 and kind is not None:
|
|
371
|
+
from tortoise.query_suggestions import compute_suggestion
|
|
372
|
+
suggestion = compute_suggestion(kind)
|
|
373
|
+
if suggestion:
|
|
374
|
+
return {"results": result, "suggestion": suggestion}
|
|
375
|
+
return result
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def tortoise_paginated_query(kind: str | None = None,
|
|
379
|
+
skip: int = 0, limit: int = 20,
|
|
380
|
+
filters: Any = None) -> dict:
|
|
381
|
+
"""Query points with SKIP/LIMIT pagination. Returns {results, total, hasMore}."""
|
|
382
|
+
filters = _parse(filters)
|
|
383
|
+
return _safe(_get_team_sdk().paginated_query, kind, skip=skip, limit=limit,
|
|
384
|
+
**(filters or {}))
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def tortoise_check_structure() -> list[dict]:
|
|
388
|
+
"""Check Gate 0→4 chain integrity (orphans, dangling refs)."""
|
|
389
|
+
return _safe(_get_team_sdk().check_structure)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def tortoise_summarize_structure() -> dict:
|
|
393
|
+
"""Count points per Gate (by pointKind). Returns {gateN_*, total}."""
|
|
394
|
+
return _safe(_get_team_sdk().summarize_structure)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def tortoise_list_pointkinds() -> list[dict]:
|
|
398
|
+
"""List all pointKinds present in the graph with counts. What EXISTS."""
|
|
399
|
+
return _safe(_get_team_sdk().list_pointkinds)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def tortoise_list_sources() -> list[dict]:
|
|
403
|
+
"""List all Sources with point counts. Where data came FROM."""
|
|
404
|
+
return _safe(_get_team_sdk().list_sources)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def tortoise_list_namespaces() -> list[dict]:
|
|
408
|
+
"""List installed pack namespaces."""
|
|
409
|
+
return _safe(_get_team_sdk().list_namespaces)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def tortoise_list_tags() -> list[dict]:
|
|
413
|
+
"""List all Tag names with count of tagged Points. Where tags are USED."""
|
|
414
|
+
return _safe(_get_team_sdk().list_tags)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def tortoise_query_points_by_tag(tag: str) -> list[dict]:
|
|
418
|
+
"""Return Points connected to a Tag via TAGGED edge."""
|
|
419
|
+
return _safe(_get_team_sdk().query_points_by_tag, tag)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def tortoise_get_point(id: str) -> dict:
|
|
423
|
+
"""Get a single Point by ID. Returns all properties, or empty dict."""
|
|
424
|
+
return _safe(_get_team_sdk().get_point, id)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
# ── Entity Resolution (GAP-01 #6987) ──────────────────────────
|
|
428
|
+
|
|
429
|
+
def tortoise_suggest_entry_points(query: str, limit: int = 5,
|
|
430
|
+
kind_filter: str | None = None) -> list[dict]:
|
|
431
|
+
"""Entity resolution — NL query → matching entities from the graph.
|
|
432
|
+
|
|
433
|
+
Uses hybrid search (tortoise_fts_query) for semantic entity resolution.
|
|
434
|
+
Falls back to string match (CONTAINS) if hybrid search unavailable.
|
|
435
|
+
Returns [{id, name, kind, confidence}] sorted by confidence DESC.
|
|
436
|
+
"""
|
|
437
|
+
try:
|
|
438
|
+
results = _safe(_get_team_sdk().tortoise_fts_query, query, kind=kind_filter, limit=limit)
|
|
439
|
+
if isinstance(results, list) and results and "error" not in results[0]:
|
|
440
|
+
return [{"id": r["id"], "name": r.get("content", ""),
|
|
441
|
+
"kind": r.get("point_kind", ""),
|
|
442
|
+
"confidence": round(
|
|
443
|
+
0.5 * r.get("scores", {}).get("rrf", 0.0) +
|
|
444
|
+
0.5 * r.get("ep", {}).get("confidence_mean", 0.0), 4)}
|
|
445
|
+
for r in results]
|
|
446
|
+
except Exception:
|
|
447
|
+
pass
|
|
448
|
+
return _safe(_get_team_sdk().suggest_entry_points, query, limit=limit, kind_filter=kind_filter)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
# ── Semantic Search (#6990) ────────────────────────────────────
|
|
452
|
+
|
|
453
|
+
def tortoise_search(query: str | None = None, kind: str | None = None,
|
|
454
|
+
threshold: float = 0.0, limit: int = 10,
|
|
455
|
+
min_confidence: float = 0.0,
|
|
456
|
+
order_by: str = "relevance",
|
|
457
|
+
entity_type: str = "point") -> list[dict]:
|
|
458
|
+
"""Hybrid search with RRF fusion + EP annotation.
|
|
459
|
+
|
|
460
|
+
entity_type: 'point' (default), 'event', 'subject', 'document', 'object', 'operator', or 'source'.
|
|
461
|
+
Full-scan mode: omit query, set kind → all Points of kind.
|
|
462
|
+
Best-match mode: provide query → RRF fusion of FTS + vector + structural.
|
|
463
|
+
|
|
464
|
+
Point results annotated with EP breakdown (confidence_mean + variance + contested + contention).
|
|
465
|
+
min_confidence defaults to 0.0 (no filter).
|
|
466
|
+
|
|
467
|
+
order_by (#25, #560):
|
|
468
|
+
- 'relevance' (default): pure RRF fusion order (FTS + vector + structural).
|
|
469
|
+
- 'confidence': sort by the PERSISTED EP confidence (n.confidence), not the
|
|
470
|
+
structural edge ratio.
|
|
471
|
+
- 'graph': graph-informed rerank — weighted fusion of similarity +
|
|
472
|
+
persisted EP confidence + operator connectivity + 30-day recency decay
|
|
473
|
+
(tortoise.ranking.GraphRanker). Results annotated with a
|
|
474
|
+
'graph_ranking' breakdown {similarity, graph_boost, recency_boost,
|
|
475
|
+
final_score, variance, contested}.
|
|
476
|
+
|
|
477
|
+
Contestation is surfaced, never scored: contested claims carry
|
|
478
|
+
ep.contested=true + ep.variance (real EP posterior variance from persisted
|
|
479
|
+
α/β) but are ranked exactly like any other claim with the same confidence
|
|
480
|
+
(#580/#583).
|
|
481
|
+
|
|
482
|
+
Note: threshold default changed from 0.3 (Phase 0 semantic search) to 0.0.
|
|
483
|
+
RRF scores are rank-based (0.01-0.05 range typical), not cosine similarity (0-1).
|
|
484
|
+
Use threshold > 0 to filter out very weak matches; the old 0.3 default would
|
|
485
|
+
reject nearly all RRF results. (#20)
|
|
486
|
+
"""
|
|
487
|
+
return _safe(_get_team_sdk().tortoise_fts_query, query, kind=kind,
|
|
488
|
+
threshold=threshold, limit=limit,
|
|
489
|
+
entity_type=entity_type,
|
|
490
|
+
min_confidence=min_confidence, order_by=order_by)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
# ── EP Belief Propagation (#6908) ────────────────────────────────
|
|
494
|
+
|
|
495
|
+
def tortoise_compute_confidence(factors: Any = None,
|
|
496
|
+
evidence: Any = None,
|
|
497
|
+
anchors: Any = None,
|
|
498
|
+
max_hops: int = 1,
|
|
499
|
+
rel_filter: str = "IMPL|NAND",
|
|
500
|
+
direction: str = "both",
|
|
501
|
+
require_calibration: bool = False) -> dict:
|
|
502
|
+
"""Compute confidence via EP belief propagation. Returns {iterations, converged, confidences}.
|
|
503
|
+
|
|
504
|
+
Pass anchors=[point_ids] for BFS subgraph selection.
|
|
505
|
+
Pass require_calibration=True to gate on calibration state.
|
|
506
|
+
max_hops: BFS depth from anchors (default 1).
|
|
507
|
+
rel_filter: edge types — "IMPL", "NAND", or "IMPL|NAND" (default).
|
|
508
|
+
direction: IMPL traversal — "incoming", "outgoing", or "both" (default).
|
|
509
|
+
"""
|
|
510
|
+
factors = _parse(factors)
|
|
511
|
+
evidence = _parse(evidence)
|
|
512
|
+
anchors = _parse(anchors)
|
|
513
|
+
return _safe(_get_team_sdk().compute_confidence, factors, evidence,
|
|
514
|
+
anchors=anchors,
|
|
515
|
+
max_hops=max_hops, rel_filter=rel_filter,
|
|
516
|
+
direction=direction,
|
|
517
|
+
require_calibration=require_calibration)
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def tortoise_set_point_baseline(claim_id: str, alpha: float, beta: float) -> dict:
|
|
521
|
+
"""Set Beta prior evidence for a claim."""
|
|
522
|
+
return _safe(_get_team_sdk().set_point_baseline, claim_id, alpha, beta)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def tortoise_get_confidence(claim_id: str) -> dict:
|
|
526
|
+
"""Get EP confidence for a claim: {mean, variance, alpha, beta}."""
|
|
527
|
+
return _safe(_get_team_sdk().get_confidence, claim_id)
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def tortoise_calibrate_summary() -> list[dict]:
|
|
531
|
+
"""Audit graph calibration state. Returns per-point guidance."""
|
|
532
|
+
return _safe(_get_team_sdk().calibrate_summary)
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def tortoise_dream(full: bool = False, dirty_only: bool = True,
|
|
536
|
+
max_hops: int = 2) -> dict:
|
|
537
|
+
"""Run EP stabilization (dreaming, #85).
|
|
538
|
+
|
|
539
|
+
Stabilizes confidence values after batch writes without an explicit
|
|
540
|
+
compute_confidence call. Default: dreams the accumulated dirty subgraph
|
|
541
|
+
(incremental). Set full=True for whole-graph stabilization.
|
|
542
|
+
|
|
543
|
+
#329: EXCLUDED from tenant HTTP — whole-graph EP is CPU-heavy
|
|
544
|
+
(operator/stdio only; REST /v1/dream is separately budgeted).
|
|
545
|
+
"""
|
|
546
|
+
if _transport_mode.get() == "http":
|
|
547
|
+
return _http_excluded_error()
|
|
548
|
+
return _safe(_get_team_sdk().dream, dirty_only=dirty_only, full=full,
|
|
549
|
+
max_hops=max_hops)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def tortoise_update_point(id: str, props: Any) -> dict:
|
|
553
|
+
"""Update properties on a Point. Safe — modifies one Point only."""
|
|
554
|
+
props = _parse(props)
|
|
555
|
+
return _safe(_quota_gated(_get_team_sdk().update_point, "points"), id, **(props or {}))
|
|
556
|
+
|
|
557
|
+
def tortoise_create_operator(op_type: str, source_id: str, target_ids: Any,
|
|
558
|
+
direction: str = "bidirectional") -> dict:
|
|
559
|
+
"""Create an operator connecting Points.
|
|
560
|
+
|
|
561
|
+
op_type: 'IMPL' (A supports B), 'NAND' (A contradicts B),
|
|
562
|
+
'composedOf'/'decomposesInto'/'contains'/'wraps' → stored as hasPart edge.
|
|
563
|
+
source_id: source/parent Point ID.
|
|
564
|
+
target_ids: target/child Point IDs (1 for IMPL/NAND, N for part/whole).
|
|
565
|
+
direction: 'bidirectional' (default) or 'unidirectional' — EP propagation direction.
|
|
566
|
+
|
|
567
|
+
→ See /skill:tortoise-graph-reasoning for proper usage:
|
|
568
|
+
annotation, mitigation, NAND constraints, veracity vs implication.
|
|
569
|
+
"""
|
|
570
|
+
target_ids = _parse(target_ids)
|
|
571
|
+
# #329 batch cap on operator target fan-out
|
|
572
|
+
from tortoise.quota import MAX_OPERATOR_TARGETS
|
|
573
|
+
if isinstance(target_ids, list) and len(target_ids) > MAX_OPERATOR_TARGETS:
|
|
574
|
+
return {"error": f"create_operator target_ids exceed the cap ({MAX_OPERATOR_TARGETS})",
|
|
575
|
+
"code": ERR_QUOTA}
|
|
576
|
+
return _safe(_quota_gated(_get_team_sdk().create_operator, "points"), op_type, source_id, target_ids,
|
|
577
|
+
direction=direction)
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def tortoise_annotate_operator(id: str, bias: float, precision: float,
|
|
581
|
+
consistency: float, directness: float) -> dict:
|
|
582
|
+
"""Annotate an operator Point with structured epistemic dimensions.
|
|
583
|
+
|
|
584
|
+
bias: 0-1 — hidden stake beyond stated position.
|
|
585
|
+
precision: 0-1 — how narrow/well-defined the relevance claim is.
|
|
586
|
+
consistency: 0-1 — stability across contexts.
|
|
587
|
+
directness: 0-1 — how directly source bears on target.
|
|
588
|
+
"""
|
|
589
|
+
return _safe(_get_team_sdk().annotate_operator, id, bias, precision, consistency, directness)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def tortoise_get_operator(id: str) -> dict:
|
|
593
|
+
"""Get an operator Point by ID. Returns all properties including annotation dimensions.
|
|
594
|
+
Raises error if the Point is not an operator."""
|
|
595
|
+
point = _safe(_get_team_sdk().get_point, id)
|
|
596
|
+
if isinstance(point, dict) and point and not point.get("is_operator"):
|
|
597
|
+
return {"error": f"Point {id!r} is not an operator"}
|
|
598
|
+
return point
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def tortoise_mitigate_operator(id: str, reason: str, strength: float = 0.5) -> dict:
|
|
602
|
+
"""Create a mitigation Point that modulates an operator's edge strength.
|
|
603
|
+
|
|
604
|
+
reason: Why the edge is weaker than it appears.
|
|
605
|
+
strength: 0-1 — 0=fully neutralized, 1=fully intact (default 0.5).
|
|
606
|
+
Idempotent — second call updates existing mitigation.
|
|
607
|
+
"""
|
|
608
|
+
return _safe(_quota_gated(_get_team_sdk().mitigate_operator, "points"), id, reason, strength)
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def tortoise_file_decision(options: Any, evidence: Any,
|
|
612
|
+
choice: int) -> dict:
|
|
613
|
+
"""File a simple decision directly to the graph.
|
|
614
|
+
|
|
615
|
+
Creates decision + options + evidence + IMPL edges atomically.
|
|
616
|
+
For low-stakes decisions where the answer is clear — no EP,
|
|
617
|
+
no calibration, no research cycles. Under 5 graph operations.
|
|
618
|
+
|
|
619
|
+
options: list of option descriptions (e.g. ["JSON", "YAML", "TOML"])
|
|
620
|
+
evidence: list of evidence statements supporting the choice
|
|
621
|
+
choice: 0-indexed option index (e.g. 0 = JSON)
|
|
622
|
+
|
|
623
|
+
Returns {decision_id, option_ids: [...], evidence_ids: [...]}.
|
|
624
|
+
"""
|
|
625
|
+
options = _parse(options)
|
|
626
|
+
evidence = _parse(evidence)
|
|
627
|
+
# #329 batch caps
|
|
628
|
+
from tortoise.quota import MAX_FILE_DECISION_EVIDENCE, MAX_FILE_DECISION_OPTIONS
|
|
629
|
+
if isinstance(options, list) and len(options) > MAX_FILE_DECISION_OPTIONS:
|
|
630
|
+
return {"error": f"file_decision options exceed the cap ({MAX_FILE_DECISION_OPTIONS})",
|
|
631
|
+
"code": ERR_QUOTA}
|
|
632
|
+
if isinstance(evidence, list) and len(evidence) > MAX_FILE_DECISION_EVIDENCE:
|
|
633
|
+
return {"error": f"file_decision evidence exceeds the cap ({MAX_FILE_DECISION_EVIDENCE})",
|
|
634
|
+
"code": ERR_QUOTA}
|
|
635
|
+
return _safe(_quota_gated(_get_team_sdk().file_decision, "points"), options, evidence, choice)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def tortoise_file_human_approval(approver_id: str, artifact_id: str,
|
|
639
|
+
point_ids: Any,
|
|
640
|
+
decision_content: str | None = None) -> dict:
|
|
641
|
+
"""File a human approval of a planning artifact to the graph (#531).
|
|
642
|
+
|
|
643
|
+
Records an Event (eventKind: humanApproval) with full provenance
|
|
644
|
+
(approver, artifact, approved claims), creates a decision Point
|
|
645
|
+
(pointKind: humanApproval) that seeds grounding and carries an EP
|
|
646
|
+
evidence prior, and fans out unidirectional IMPL edges (label
|
|
647
|
+
approvedBy) from the approval Point to the approved claim Points so
|
|
648
|
+
dependent claims strengthen.
|
|
649
|
+
|
|
650
|
+
approver_id: Subject id of the human approving
|
|
651
|
+
artifact_id: Object/Document id of the artifact being approved
|
|
652
|
+
point_ids: claim Point ids being approved
|
|
653
|
+
decision_content: optional content override for the decision Point
|
|
654
|
+
|
|
655
|
+
Returns {event_id, decision_point_id, impl_operator_ids, confidence_delta}.
|
|
656
|
+
"""
|
|
657
|
+
point_ids = _parse(point_ids)
|
|
658
|
+
return _safe(_get_team_sdk().file_human_approval, approver_id, artifact_id,
|
|
659
|
+
point_ids, decision_content)
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def tortoise_delete_point(id: str) -> dict:
|
|
663
|
+
"""Delete a Point. DESTRUCTIVE — requires human confirmation. Cannot be undone."""
|
|
664
|
+
return _safe(_get_team_sdk().delete_point_wrapped, id)
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def tortoise_invalidate(id: str, corrected_by_id: str) -> dict:
|
|
668
|
+
"""Mark a Point outdated with a CORRECTS edge from the correcting Point.
|
|
669
|
+
|
|
670
|
+
The `corrected_by_id` point CORRECTS the invalidated point.
|
|
671
|
+
Returns {invalidated, id, corrected_by}.
|
|
672
|
+
"""
|
|
673
|
+
return _safe(_quota_gated(_get_team_sdk().invalidate_point, "points"), id, corrected_by_id)
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def tortoise_supersede(old_id: str, new_id: str) -> dict:
|
|
677
|
+
"""Atomically replace old Point with new — CORRECTS edge + outdated flag.
|
|
678
|
+
|
|
679
|
+
Equivalent to invalidate(old_id, new_id) — marks old outdated,
|
|
680
|
+
creates CORRECTS edge from new to old.
|
|
681
|
+
Returns {invalidated, id, corrected_by}.
|
|
682
|
+
"""
|
|
683
|
+
return _safe(_quota_gated(_get_team_sdk().supersede_point, "points"), old_id, new_id)
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
# ── Navigation (#6962, #6963, #6964) ─────────────────────────────
|
|
688
|
+
|
|
689
|
+
def tortoise_entity_profile(entity_id: str, hops: int = 2,
|
|
690
|
+
graph_name: str = "tortoise",
|
|
691
|
+
pointKind: str | None = None,
|
|
692
|
+
confidenceMin: float | None = None) -> dict:
|
|
693
|
+
"""Entity-centric traversal — BFS from entity node, categorize connected nodes.
|
|
694
|
+
|
|
695
|
+
Returns {entity: {...}, connected: {points, documents, events, subjects, objects}}.
|
|
696
|
+
Optional filters: pointKind, confidenceMin.
|
|
697
|
+
"""
|
|
698
|
+
from tortoise.navigation import entityProfile
|
|
699
|
+
proj = _get_team_sdk()._get_proj()
|
|
700
|
+
# #236: HTTP mode ignores user-supplied graph_name — team graph authoritative
|
|
701
|
+
# (cross-tenant injection guard). Stdio mode honors it (operator use).
|
|
702
|
+
if _transport_mode.get() == "http":
|
|
703
|
+
graph_name = f"team_{_current_team_id.get()}"
|
|
704
|
+
return _safe(entityProfile, proj.db, graph_name, entity_id,
|
|
705
|
+
hops=hops, pointKind=pointKind, confidenceMin=confidenceMin)
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def tortoise_traverse(entity_id: str, max_hops: int = 2,
|
|
709
|
+
graph_name: str = "tortoise") -> dict:
|
|
710
|
+
"""Multi-hop graph traversal from entity following ALL relationship types.
|
|
711
|
+
|
|
712
|
+
Returns {entity: {...}, nodes: [{node, relationship, depth}, ...]}.
|
|
713
|
+
"""
|
|
714
|
+
from tortoise.navigation import tortoise_traverse as _traverse
|
|
715
|
+
proj = _get_team_sdk()._get_proj()
|
|
716
|
+
# #236: HTTP mode ignores user-supplied graph_name (cross-tenant guard)
|
|
717
|
+
if _transport_mode.get() == "http":
|
|
718
|
+
graph_name = f"team_{_current_team_id.get()}"
|
|
719
|
+
return _safe(_traverse, proj.db, graph_name, entity_id, max_hops)
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def main():
|
|
723
|
+
_transport_mode.set("stdio")
|
|
724
|
+
monitoring.register(_get_sdk())
|
|
725
|
+
uri = os.environ.get("TORTOISE_DB_URI")
|
|
726
|
+
db_path = os.environ.get("TORTOISE_DB_PATH")
|
|
727
|
+
if not uri and not db_path:
|
|
728
|
+
if os.environ.get("TORTOISE_ALLOW_EMBEDDED") == "1":
|
|
729
|
+
_log.warning(
|
|
730
|
+
"Neither TORTOISE_DB_URI nor TORTOISE_DB_PATH set — running "
|
|
731
|
+
"embedded (empty graph). Test-only escape hatch."
|
|
732
|
+
)
|
|
733
|
+
else:
|
|
734
|
+
_log.error(
|
|
735
|
+
"Neither TORTOISE_DB_URI nor TORTOISE_DB_PATH is set. MCP would "
|
|
736
|
+
"silently connect to an empty embedded DB. Set TORTOISE_DB_URI "
|
|
737
|
+
"(docker://...) or TORTOISE_DB_PATH (canonical embedded path) in "
|
|
738
|
+
"the environment or .env, then restart. "
|
|
739
|
+
"Override with TORTOISE_ALLOW_EMBEDDED=1 (test only)."
|
|
740
|
+
)
|
|
741
|
+
sys.exit(1)
|
|
742
|
+
mcp.run(transport="stdio")
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
if __name__ == "__main__":
|
|
746
|
+
main()
|
|
747
|
+
|
|
748
|
+
# ── P0 Group 3: Checkpoint, Diary, Status, Ingest ──────────────
|
|
749
|
+
|
|
750
|
+
def tortoise_checkpoint(items: Any,
|
|
751
|
+
agent_name: str = "checkpoint",
|
|
752
|
+
threshold: float = 0.95) -> dict:
|
|
753
|
+
"""Session batch save — two-tier dedup (content hash + embedding similarity).
|
|
754
|
+
|
|
755
|
+
items: [{wing, room, content}, ...]
|
|
756
|
+
agent_name: name for provenance events (default: "checkpoint")
|
|
757
|
+
threshold: cosine similarity for semantic dedup (0.0-1.0).
|
|
758
|
+
Set to 1.0 to disable semantic dedup (hash-only).
|
|
759
|
+
Returns {filed: N, duplicates: M}.
|
|
760
|
+
"""
|
|
761
|
+
items = _parse(items)
|
|
762
|
+
# #329 batch cap: a single checkpoint call must not create unbounded nodes
|
|
763
|
+
from tortoise.quota import MAX_CHECKPOINT_ITEMS
|
|
764
|
+
if isinstance(items, list) and len(items) > MAX_CHECKPOINT_ITEMS:
|
|
765
|
+
return {"error": f"checkpoint items exceed the batch cap ({MAX_CHECKPOINT_ITEMS})",
|
|
766
|
+
"code": ERR_QUOTA}
|
|
767
|
+
return _safe(_quota_gated(_get_team_sdk().checkpoint, "points"), items,
|
|
768
|
+
agent_name=agent_name, threshold=threshold)
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def tortoise_diary_write(agent_name: str, entry: str,
|
|
772
|
+
topic: str | None = None,
|
|
773
|
+
wing: str | None = None) -> dict:
|
|
774
|
+
"""Write an agent diary entry (AAAK format suggested).
|
|
775
|
+
Creates a Point with pointKind=diary, authoredBy=agent.
|
|
776
|
+
"""
|
|
777
|
+
return _safe(_quota_gated(_get_team_sdk().diary_write, "points"), agent_name, entry, topic=topic, wing=wing)
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
def tortoise_diary_read(agent_name: str, last_n: int = 10,
|
|
781
|
+
wing: str | None = None) -> list[dict]:
|
|
782
|
+
"""Read recent diary entries for an agent, newest first."""
|
|
783
|
+
return _safe(_get_team_sdk().diary_read, agent_name, last_n, wing=wing)
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def tortoise_list_graphs() -> list[str]:
|
|
787
|
+
"""List graph names. HTTP: only the calling team's own graphs (exact
|
|
788
|
+
team_{team_id} equality — no cross-tenant enumeration). Stdio: full list
|
|
789
|
+
(operator context)."""
|
|
790
|
+
graphs = _safe(_get_team_sdk().list_graphs)
|
|
791
|
+
if not isinstance(graphs, list):
|
|
792
|
+
return graphs
|
|
793
|
+
if _transport_mode.get() == "http":
|
|
794
|
+
from tortoise.mcp_auth import _current_team_id
|
|
795
|
+
team_id = _current_team_id.get()
|
|
796
|
+
own = f"team_{team_id}" if team_id else None
|
|
797
|
+
return [g for g in graphs if own is not None and g == own]
|
|
798
|
+
return graphs
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def tortoise_status() -> dict:
|
|
802
|
+
"""Graph health + entity counts + FalkorDB connectivity.
|
|
803
|
+
Returns {connected, counts: {Point, Event, ...}, total_entities}.
|
|
804
|
+
"""
|
|
805
|
+
return _safe(_get_team_sdk().status)
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def tortoise_health() -> dict:
|
|
809
|
+
"""Health check + basic metrics: graph_size, last_ingest, error_count, uptime."""
|
|
810
|
+
# #236: route through _safe() so every tool is gated (defense-in-depth;
|
|
811
|
+
# reachable only post-auth over HTTP).
|
|
812
|
+
return _safe(monitoring.metrics)
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def tortoise_session_context() -> dict:
|
|
816
|
+
"""Return 'what happened last session' — diary entries, recent Points, Events, confidence changes.
|
|
817
|
+
Returns {no_prior_sessions, diary_entries, recent_points, recent_events, confidence_changes}.
|
|
818
|
+
"""
|
|
819
|
+
return _safe(_get_team_sdk().session_context)
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
def tortoise_ingest_corpus(directory: str) -> dict:
|
|
823
|
+
"""Batch document ingestion — walk directory, parse YAML frontmatter
|
|
824
|
+
from .md files, create/update Document nodes.
|
|
825
|
+
Returns {ingested, updated, skipped}.
|
|
826
|
+
|
|
827
|
+
#236: EXCLUDED from tenant HTTP — walks server filesystem with a
|
|
828
|
+
user-supplied path (path-traversal vector). Stdio-only.
|
|
829
|
+
"""
|
|
830
|
+
if _transport_mode.get() == "http":
|
|
831
|
+
return _http_excluded_error()
|
|
832
|
+
return _safe(_get_team_sdk().ingest_corpus, directory)
|
|
833
|
+
|
|
834
|
+
# ── Taxonomy ─────────────────────────────────────────────────
|
|
835
|
+
|
|
836
|
+
def tortoise_taxonomy() -> dict[str, int]:
|
|
837
|
+
"""Count entities by node label. Returns {Point: N, Event: N, Subject: N, Object: N, Document: N}."""
|
|
838
|
+
return _safe(_get_team_sdk().taxonomy)
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
def tortoise_list_topics(entity_id: str) -> dict:
|
|
842
|
+
"""entityProfile lite for an entity. Returns {id, pointKind, neighbors, neighborCounts}."""
|
|
843
|
+
return _safe(_get_team_sdk().list_topics, entity_id)
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
# ── Graph Analysis ──────────────────────────────────────────────
|
|
847
|
+
|
|
848
|
+
def tortoise_analyze(question: str,
|
|
849
|
+
entityId: str | None = None,
|
|
850
|
+
anchor_ids: Any = None,
|
|
851
|
+
max_hops: int = 1,
|
|
852
|
+
rel_filter: str = "IMPL|NAND",
|
|
853
|
+
direction: str = "both") -> dict:
|
|
854
|
+
"""Answer natural language questions about the Tortoise epistemic graph.
|
|
855
|
+
|
|
856
|
+
Ask things like: "where is the disagreement?" "what supports claim X?"
|
|
857
|
+
"what are we most uncertain about?" "show me the evidence chain for Y."
|
|
858
|
+
|
|
859
|
+
Optional entityId scopes the analysis to a specific entity's subgraph.
|
|
860
|
+
Optional anchor_ids (list of Point IDs) scopes via BFS subgraph selection.
|
|
861
|
+
max_hops: BFS depth from anchors (default 1).
|
|
862
|
+
rel_filter: edge types — "IMPL", "NAND", or "IMPL|NAND" (default).
|
|
863
|
+
direction: IMPL traversal — "incoming", "outgoing", or "both" (default).
|
|
864
|
+
Returns {"answer": "...", "raw": [...], "pattern": "...", "query": "..."}
|
|
865
|
+
"""
|
|
866
|
+
from tortoise.analyze import analyze
|
|
867
|
+
from tortoise.navigation import entityProfile
|
|
868
|
+
|
|
869
|
+
anchor_ids = _parse(anchor_ids)
|
|
870
|
+
|
|
871
|
+
entity_subgraph_ids = None
|
|
872
|
+
if entityId:
|
|
873
|
+
try:
|
|
874
|
+
proj = _get_team_sdk()._get_proj()
|
|
875
|
+
# #236: HTTP mode must use the team graph, NOT the hardcoded
|
|
876
|
+
# "tortoise" graph — that hardcode bypasses team isolation via
|
|
877
|
+
# db.select_graph() (cross-tenant read). Stdio keeps "tortoise".
|
|
878
|
+
gname = f"team_{_current_team_id.get()}" if _transport_mode.get() == "http" else "tortoise"
|
|
879
|
+
profile = entityProfile(proj.db, gname, entityId, hops=2)
|
|
880
|
+
ids = {entityId}
|
|
881
|
+
for category in profile.get("connected", {}).values():
|
|
882
|
+
for node in category:
|
|
883
|
+
if node.get("id"):
|
|
884
|
+
ids.add(node["id"])
|
|
885
|
+
entity_subgraph_ids = ids
|
|
886
|
+
except Exception:
|
|
887
|
+
pass # fall back to full-graph analysis
|
|
888
|
+
|
|
889
|
+
# #329: bound paid outbound LLM calls per team per minute — beyond budget
|
|
890
|
+
# the tool degrades to keyword-only classification.
|
|
891
|
+
use_llm = _analyze_llm_budget_available()
|
|
892
|
+
result = _safe(analyze, question, _get_team_sdk()._get_proj(),
|
|
893
|
+
entity_subgraph_ids=entity_subgraph_ids,
|
|
894
|
+
anchor_ids=anchor_ids,
|
|
895
|
+
max_hops=max_hops,
|
|
896
|
+
rel_filter=rel_filter,
|
|
897
|
+
direction=direction,
|
|
898
|
+
use_llm=use_llm)
|
|
899
|
+
# #329 defense-in-depth: analyze() self-redacts, but scrub the answer at the
|
|
900
|
+
# boundary too in case a future error path leaks internals.
|
|
901
|
+
if isinstance(result, dict) and isinstance(result.get("answer"), str):
|
|
902
|
+
result["answer"] = _scrub_analyze_answer(result["answer"])
|
|
903
|
+
return result
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
# ── P1-3: Staleness Detection ─────────────────────────────────
|
|
907
|
+
|
|
908
|
+
def tortoise_stale(days: int = 30, limit: int = 50) -> dict:
|
|
909
|
+
"""Find Points not updated in N days. Returns {stale, count, cutoff, limit}."""
|
|
910
|
+
return _safe(_get_team_sdk().stale_points, days=days, limit=limit)
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def tortoise_provenance(point_id: str) -> dict:
|
|
914
|
+
"""Provenance chain — "Who decided this?" Follows authoredBy → Subject → delegation."""
|
|
915
|
+
return _safe(_get_team_sdk().provenance, point_id)
|
|
916
|
+
|
|
917
|
+
|
|
918
|
+
# ── Multi-tenancy (#7001) ────────────────────────────────────
|
|
919
|
+
|
|
920
|
+
def tortoise_team_create(name: str) -> dict:
|
|
921
|
+
"""Create isolated team graph via FalkorDB select_graph.
|
|
922
|
+
Generates a per-team API key. Returns {name, graph_name, api_key, id}.
|
|
923
|
+
destructiveHint=true — creates persistent resources.
|
|
924
|
+
idempotentHint=false — duplicate team names raise an error.
|
|
925
|
+
|
|
926
|
+
#236: EXCLUDED from tenant HTTP — provisioning belongs to
|
|
927
|
+
/internal/provision behind FASTAPI_INTERNAL_KEY (privilege boundary).
|
|
928
|
+
Stdio-only.
|
|
929
|
+
"""
|
|
930
|
+
if _transport_mode.get() == "http":
|
|
931
|
+
return _http_excluded_error()
|
|
932
|
+
return _safe(_get_team_sdk().team_create, name)
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
# ── Entity CRUD (ONTOLOGY v2.5) ───────────────────────────────
|
|
936
|
+
|
|
937
|
+
def tortoise_create_subject(name: str, subjectKind: str, props: Any = None) -> dict:
|
|
938
|
+
"""Create a Subject node (team, role, organization, person)."""
|
|
939
|
+
props = _parse(props)
|
|
940
|
+
return _safe(_quota_gated(_get_team_sdk().create_subject, "points"), name, subjectKind, **(props or {}))
|
|
941
|
+
|
|
942
|
+
def tortoise_create_object(name: str, objectKind: str, props: Any = None) -> dict:
|
|
943
|
+
"""Create an Object node (product, customer, skill, etc.)."""
|
|
944
|
+
props = _parse(props)
|
|
945
|
+
return _safe(_quota_gated(_get_team_sdk().create_object, "points"), name, objectKind, **(props or {}))
|
|
946
|
+
|
|
947
|
+
def tortoise_create_event(name: str, eventKind: str, props: Any = None) -> dict:
|
|
948
|
+
"""Create an Event node (meeting, decision, deployment, etc.)."""
|
|
949
|
+
props = _parse(props)
|
|
950
|
+
return _safe(_quota_gated(_get_team_sdk().create_event, "points"), name, eventKind, **(props or {}))
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
def tortoise_get_events(eventKind: str | None = None, limit: int = 20) -> list[dict]:
|
|
954
|
+
"""Get recent Events, optionally filtered by eventKind (e.g. 'AgentSession')."""
|
|
955
|
+
return _safe(_get_team_sdk().get_events, eventKind=eventKind, limit=limit)
|
|
956
|
+
|
|
957
|
+
def tortoise_get_session(session_id: str) -> dict:
|
|
958
|
+
"""Get a single agent session Event by session_id."""
|
|
959
|
+
return _safe(_get_team_sdk().get_session, session_id)
|
|
960
|
+
|
|
961
|
+
def tortoise_index_sessions(directory: str, extract_metadata: bool = True, llm_model: str | None = None) -> dict:
|
|
962
|
+
"""Index session .md files as AgentSession Events. Returns {ingested, updated, skipped, failed, errors}.
|
|
963
|
+
|
|
964
|
+
#236: EXCLUDED from tenant HTTP — walks server filesystem with a
|
|
965
|
+
user-supplied path (path-traversal vector, same as ingest_corpus). Stdio-only.
|
|
966
|
+
"""
|
|
967
|
+
if _transport_mode.get() == "http":
|
|
968
|
+
return _http_excluded_error()
|
|
969
|
+
if not os.path.isdir(directory):
|
|
970
|
+
return {"error": f"Directory not found: {directory!r}. Provide a valid path to a directory containing .md session files."}
|
|
971
|
+
return _safe(_get_team_sdk().index_sessions, directory, extract_metadata=extract_metadata, llm_model=llm_model)
|
|
972
|
+
|
|
973
|
+
def tortoise_search_sessions(query: str, agent: str | None = None, topics: Any = None,
|
|
974
|
+
after: str | None = None, before: str | None = None,
|
|
975
|
+
limit: int = 10, offset: int = 0) -> list[dict]:
|
|
976
|
+
"""Search indexed agent sessions. Returns Events with narrative_arc snippets.
|
|
977
|
+
|
|
978
|
+
after/before bound the search to sessions whose startedAt falls in
|
|
979
|
+
[after, before] (inclusive). Accept ISO-8601 strings (e.g.
|
|
980
|
+
'2026-07-01T00:00:00Z' or '2026-07-31T23:59:59+00:00'); values are
|
|
981
|
+
normalized to UTC. Sessions without startedAt are excluded when a bound
|
|
982
|
+
is set.
|
|
983
|
+
"""
|
|
984
|
+
topics = _parse(topics)
|
|
985
|
+
if isinstance(topics, str):
|
|
986
|
+
topics_list = [t.strip() for t in topics.split(",") if t.strip()]
|
|
987
|
+
elif isinstance(topics, list):
|
|
988
|
+
topics_list = topics
|
|
989
|
+
else:
|
|
990
|
+
topics_list = None
|
|
991
|
+
return _safe(_get_team_sdk().search_sessions, query, agent=agent, topics=topics_list,
|
|
992
|
+
after=after, before=before, limit=limit, offset=offset)
|
|
993
|
+
|
|
994
|
+
def tortoise_create_document(title: str, documentKind: str, props: Any = None) -> dict:
|
|
995
|
+
"""Create a Document node (research, planDoc, meetingNotes, etc.)."""
|
|
996
|
+
props = _parse(props)
|
|
997
|
+
return _safe(_quota_gated(_get_team_sdk().create_document, "points"), title, documentKind, **(props or {}))
|
|
998
|
+
|
|
999
|
+
@mcp.tool(annotations=ToolAnnotations(idempotentHint=True))
|
|
1000
|
+
def tortoise_create_source(url: str, sourceKind: str, tier: str | None = None,
|
|
1001
|
+
sourceDate: str | None = None, props: Any = None) -> dict:
|
|
1002
|
+
"""Create a Source node for provenance (document, web, db, etc.).
|
|
1003
|
+
|
|
1004
|
+
Sources track content origin — url is the permalink key. Points link to
|
|
1005
|
+
Sources via extractedFrom edge (Ontology v2.5). ``tier`` (T0-T4) stores the
|
|
1006
|
+
credibility tier on ``credibilityTier`` (dual-write with tier-form
|
|
1007
|
+
sourceKind); ``sourceDate`` is the evidence-age clock for recency decay.
|
|
1008
|
+
"""
|
|
1009
|
+
props = _parse(props) or {}
|
|
1010
|
+
# tier/sourceDate are first-class kwargs (#398) — pop from props if a legacy
|
|
1011
|
+
# caller passed them there (kwarg wins; avoids TypeError on splat).
|
|
1012
|
+
props.pop("tier", None)
|
|
1013
|
+
props.pop("sourceDate", None)
|
|
1014
|
+
return _safe(_quota_gated(_get_team_sdk().create_source, "points"), url, sourceKind,
|
|
1015
|
+
tier=tier, sourceDate=sourceDate, **props)
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
@mcp.tool()
|
|
1019
|
+
def tortoise_get_source_reliability(url: str) -> dict:
|
|
1020
|
+
"""Derive a Source's reliability (0-1) — query-time, cache-consistency-checked.
|
|
1021
|
+
|
|
1022
|
+
Reliability is the mean of the same modulated prior EP uses as base weight
|
|
1023
|
+
(tier + recency decay + reputation-weighted agent assessments). Untiered +
|
|
1024
|
+
unassessed → None. NOTE: refreshes the documented reliability cache on the
|
|
1025
|
+
Source node (write-through projection), so this tool is not read-only.
|
|
1026
|
+
"""
|
|
1027
|
+
return _safe(_get_team_sdk().get_source_reliability, url)
|
|
1028
|
+
|
|
1029
|
+
|
|
1030
|
+
@mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
|
|
1031
|
+
def tortoise_assess_source(url: str, assessor: str, score: float,
|
|
1032
|
+
rationale: str) -> dict:
|
|
1033
|
+
"""Record an agent's assessment of a Source (0-1 score + rationale).
|
|
1034
|
+
|
|
1035
|
+
Creates a pointKind='assessment' Statement Point (ontology §2 — evaluations
|
|
1036
|
+
are Points, not edges). Latest assessment per (url, assessor) wins; older
|
|
1037
|
+
are marked outdated. Weighted by the assessor's reputation snapshot
|
|
1038
|
+
(compute_reputation at write time). Feeds the source's reliability factor
|
|
1039
|
+
(clamped [0.1, 2.0]).
|
|
1040
|
+
"""
|
|
1041
|
+
return _safe(_get_team_sdk().assess_source, url, assessor, score, rationale)
|
|
1042
|
+
|
|
1043
|
+
|
|
1044
|
+
@mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
|
|
1045
|
+
def tortoise_set_source_tier(url: str, tier: str) -> dict:
|
|
1046
|
+
"""Set (or change) a Source's credibility tier (T0-T4). Non-destructive.
|
|
1047
|
+
|
|
1048
|
+
Writes credibilityTier only — never overwrites sourceKind type strings.
|
|
1049
|
+
Dirty-marks the inheritance gate + clears the reliability cache so EP and
|
|
1050
|
+
reliability reads reflect the new tier promptly.
|
|
1051
|
+
"""
|
|
1052
|
+
return _safe(_get_team_sdk().set_source_tier, url, tier)
|
|
1053
|
+
|
|
1054
|
+
def tortoise_get_entity(id: str) -> dict:
|
|
1055
|
+
"""Get any entity by ID, eventId, or url."""
|
|
1056
|
+
return _safe(_get_team_sdk().get_entity, id)
|
|
1057
|
+
|
|
1058
|
+
def tortoise_update_entity(id: str, props: Any = None) -> dict:
|
|
1059
|
+
"""Update any entity's properties."""
|
|
1060
|
+
props = _parse(props)
|
|
1061
|
+
return _safe(_quota_gated(_get_team_sdk().update_entity, "points"), id, **(props or {}))
|
|
1062
|
+
|
|
1063
|
+
def tortoise_delete_entity(id: str) -> bool:
|
|
1064
|
+
"""Delete any entity by ID."""
|
|
1065
|
+
return _safe(_get_team_sdk().delete_entity, id)
|
|
1066
|
+
|
|
1067
|
+
def tortoise_create_edge(source_id: str, target_id: str, predicate: str) -> bool:
|
|
1068
|
+
"""Create an edge between two entities. Predicate: performs, produces, ownedBy, managedBy, etc."""
|
|
1069
|
+
return _safe(_quota_gated(_get_team_sdk()._get_proj().create_edge, "points"), source_id, target_id, predicate)
|
|
1070
|
+
|
|
1071
|
+
def tortoise_get_governance(subject_id: str) -> list:
|
|
1072
|
+
"""Get all entities owned by a Subject."""
|
|
1073
|
+
return _safe(_get_team_sdk().get_owned_entities, subject_id)
|
|
1074
|
+
|
|
1075
|
+
def tortoise_backfill_v25(dry_run: bool = True) -> dict:
|
|
1076
|
+
"""Backfill database to ONTOLOGY v2.5 schema.
|
|
1077
|
+
|
|
1078
|
+
#236: EXCLUDED from tenant HTTP — schema-level migration (operator-only).
|
|
1079
|
+
"""
|
|
1080
|
+
if _transport_mode.get() == "http":
|
|
1081
|
+
return _http_excluded_error()
|
|
1082
|
+
return _safe(_get_team_sdk().backfill_v25, dry_run=dry_run)
|
|
1083
|
+
|
|
1084
|
+
|
|
1085
|
+
# ── Tool Registry Adapter (#454) ────────────────────────────────
|
|
1086
|
+
# Replaces @mcp.tool() decorators with programmatic registration.
|
|
1087
|
+
# Function bodies remain module-level callables; the adapter wraps each
|
|
1088
|
+
# via FunctionTool.from_function() and registers them on the shared mcp.
|
|
1089
|
+
# Must execute AFTER all tool function definitions (at module bottom).
|
|
1090
|
+
from tortoise.tool_registry import TOOL_REGISTRY, FastMCPAdapter
|
|
1091
|
+
|
|
1092
|
+
_adapter = FastMCPAdapter(mcp)
|
|
1093
|
+
_adapter.register_all(TOOL_REGISTRY, {
|
|
1094
|
+
t.name: globals()[t.name]
|
|
1095
|
+
for t in TOOL_REGISTRY
|
|
1096
|
+
if t.name in globals()
|
|
1097
|
+
})
|
|
1098
|
+
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
# ── Onboarding MCP tools (#498/#499/#500) ───────────────────────
|
|
1102
|
+
# Wrappers for the hosted onboarding flow. These call the team-scoped SDK
|
|
1103
|
+
# directly (same pattern as all tools) — the REST endpoints in hosted_api.py
|
|
1104
|
+
# expose the same operations to the welcome page.
|
|
1105
|
+
|
|
1106
|
+
def _onboarding_state() -> dict:
|
|
1107
|
+
"""Read this team's onboarding progress from the registry Team node."""
|
|
1108
|
+
from tortoise.hosted_api import _get_onboarding_state as _read_state
|
|
1109
|
+
team_id = _current_team_id.get()
|
|
1110
|
+
if team_id is None:
|
|
1111
|
+
return {"error": "No team context (HTTP mode required)"}
|
|
1112
|
+
return _read_state(team_id)
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
@mcp.tool(annotations=ToolAnnotations(idempotentHint=True))
|
|
1116
|
+
def tortoise_onboarding_demo_create() -> dict:
|
|
1117
|
+
"""Create the demo epistemic graph (4 layers) for this team. Idempotent.
|
|
1118
|
+
|
|
1119
|
+
Q4 — 'Create a demo graph?' — shows what Tortoise memory looks like.
|
|
1120
|
+
"""
|
|
1121
|
+
from tortoise.hosted_api import _seed_demo_graph
|
|
1122
|
+
team_id = _current_team_id.get()
|
|
1123
|
+
if team_id is None:
|
|
1124
|
+
return {"error": "No team context (HTTP mode required)"}
|
|
1125
|
+
# #329: demo graph creation creates nodes — quota-gate it
|
|
1126
|
+
_enforce_quota("points")
|
|
1127
|
+
result = _seed_demo_graph(team_id)
|
|
1128
|
+
# Auto-update onboarding state
|
|
1129
|
+
try:
|
|
1130
|
+
from tortoise.hosted_api import _update_onboarding_state
|
|
1131
|
+
_update_onboarding_state(team_id, demo_created=True)
|
|
1132
|
+
except Exception:
|
|
1133
|
+
pass
|
|
1134
|
+
return result
|
|
1135
|
+
|
|
1136
|
+
|
|
1137
|
+
@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
|
|
1138
|
+
def tortoise_onboarding_state() -> dict:
|
|
1139
|
+
"""Return this team's onboarding progress (Q6 verification step)."""
|
|
1140
|
+
return _onboarding_state()
|
|
1141
|
+
|
|
1142
|
+
|
|
1143
|
+
@mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
|
|
1144
|
+
def tortoise_onboarding_session_recording(enabled: bool) -> dict:
|
|
1145
|
+
"""Toggle automatic session recording for this team (Q3)."""
|
|
1146
|
+
team_id = _current_team_id.get()
|
|
1147
|
+
if team_id is None:
|
|
1148
|
+
return {"error": "No team context (HTTP mode required)"}
|
|
1149
|
+
from tortoise.hosted_api import _update_onboarding_state
|
|
1150
|
+
state = _update_onboarding_state(team_id, session_recording=enabled)
|
|
1151
|
+
return {"onboarding": state}
|
|
1152
|
+
|
|
1153
|
+
|
|
1154
|
+
@mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
|
|
1155
|
+
def tortoise_onboarding_github_connect(org: str | None = None) -> dict:
|
|
1156
|
+
"""Initiate GitHub OAuth — returns the authorize URL + CSRF state (Q1)."""
|
|
1157
|
+
team_id = _current_team_id.get()
|
|
1158
|
+
if team_id is None:
|
|
1159
|
+
return {"error": "No team context (HTTP mode required)"}
|
|
1160
|
+
import secrets
|
|
1161
|
+
from urllib.parse import urlencode
|
|
1162
|
+
import os as _os
|
|
1163
|
+
client_id = _os.environ.get("GITHUB_CLIENT_ID")
|
|
1164
|
+
if not client_id:
|
|
1165
|
+
return {"error": "GitHub OAuth not configured"}
|
|
1166
|
+
state = secrets.token_urlsafe(24)
|
|
1167
|
+
# Store CSRF state so the callback can validate it (P2 review fix) —
|
|
1168
|
+
# must be visible to the REST callback handler in the same process.
|
|
1169
|
+
import time as _time
|
|
1170
|
+
from tortoise.hosted_api import _GITHUB_STATES
|
|
1171
|
+
_GITHUB_STATES[state] = {"team_id": team_id, "org": org or team_id,
|
|
1172
|
+
"created_at": _time.time()}
|
|
1173
|
+
callback = _os.environ.get("GITHUB_CALLBACK_URL",
|
|
1174
|
+
"https://api.premiselabs.co/v1/onboarding/github/callback")
|
|
1175
|
+
params = {"client_id": client_id, "redirect_uri": callback,
|
|
1176
|
+
"scope": "repo", "state": state}
|
|
1177
|
+
auth_url = f"https://github.com/login/oauth/authorize?{urlencode(params)}"
|
|
1178
|
+
return {"auth_url": auth_url, "state": state}
|
|
1179
|
+
|
|
1180
|
+
|
|
1181
|
+
@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))
|
|
1182
|
+
def tortoise_onboarding_github_status() -> dict:
|
|
1183
|
+
"""Return GitHub connection status for this team (Q1 verify)."""
|
|
1184
|
+
team_id = _current_team_id.get()
|
|
1185
|
+
if team_id is None:
|
|
1186
|
+
return {"error": "No team context (HTTP mode required)"}
|
|
1187
|
+
sdk = _get_team_sdk()
|
|
1188
|
+
try:
|
|
1189
|
+
reg = sdk._get_registry().query(
|
|
1190
|
+
"MATCH (t:Team {id: $id}) RETURN t.github_token_enc, t.github_org",
|
|
1191
|
+
params={"id": team_id}).result_set
|
|
1192
|
+
except Exception:
|
|
1193
|
+
return {"connected": False, "org": None, "repos_count": None}
|
|
1194
|
+
if not reg or not reg[0][0]:
|
|
1195
|
+
return {"connected": False, "org": None, "repos_count": None}
|
|
1196
|
+
return {"connected": True, "org": reg[0][1], "repos_count": None}
|
|
1197
|
+
|
|
1198
|
+
|
|
1199
|
+
@mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
|
|
1200
|
+
def tortoise_onboarding_github_index(org: str, repo: str | None = None) -> dict:
|
|
1201
|
+
"""Start background GitHub indexing of an org's issues/PRs (Q2).
|
|
1202
|
+
|
|
1203
|
+
Returns {job_id, status} — poll via the REST endpoint or check
|
|
1204
|
+
onboarding state for github_indexed.
|
|
1205
|
+
"""
|
|
1206
|
+
team_id = _current_team_id.get()
|
|
1207
|
+
if team_id is None:
|
|
1208
|
+
return {"error": "No team context (HTTP mode required)"}
|
|
1209
|
+
import secrets as _secrets
|
|
1210
|
+
import asyncio as _asyncio
|
|
1211
|
+
from tortoise.hosted_api import _INDEX_JOBS, _run_indexing, _make_sdk as _ha_make_sdk
|
|
1212
|
+
sdk = _ha_make_sdk(namespace="registry")
|
|
1213
|
+
try:
|
|
1214
|
+
rows = sdk._get_registry().query(
|
|
1215
|
+
"MATCH (t:Team {id: $id}) RETURN t.github_token_enc",
|
|
1216
|
+
params={"id": team_id}).result_set
|
|
1217
|
+
except Exception:
|
|
1218
|
+
return {"error": "Registry unavailable"}
|
|
1219
|
+
if not rows or not rows[0][0]:
|
|
1220
|
+
return {"error": "GitHub not connected. Run tortoise_onboarding_github_connect first."}
|
|
1221
|
+
job_id = _secrets.token_hex(8)
|
|
1222
|
+
_INDEX_JOBS[job_id] = {"status": "started", "progress": 0,
|
|
1223
|
+
"points_created": 0, "error": None,
|
|
1224
|
+
"team_id": team_id,
|
|
1225
|
+
"created_at": _asyncio.get_event_loop().time()}
|
|
1226
|
+
try:
|
|
1227
|
+
_asyncio.get_event_loop().create_task(
|
|
1228
|
+
_run_indexing(job_id, team_id, org, repo))
|
|
1229
|
+
except RuntimeError:
|
|
1230
|
+
return {"error": "No running event loop"}
|
|
1231
|
+
return {"job_id": job_id, "status": "started"}
|
|
1232
|
+
|
|
1233
|
+
|
|
1234
|
+
# ── HTTP Streamable transport (#236) ─────────────────────────────
|
|
1235
|
+
|
|
1236
|
+
def create_http_app(*, allowed_origins: list[str] | None = None,
|
|
1237
|
+
allowed_hosts: list[str] | None = None,
|
|
1238
|
+
rate_limit: int = 100,
|
|
1239
|
+
_registry_sdk=None,
|
|
1240
|
+
auth_mode: Literal["tenant", "static", "none"] = "tenant",
|
|
1241
|
+
api_key: str | None = None,
|
|
1242
|
+
tool_group: str | None = None) -> Any:
|
|
1243
|
+
"""Configured Streamable HTTP app for the hosted platform (#236).
|
|
1244
|
+
|
|
1245
|
+
Mounted at /mcp on the existing FastAPI app. Auth + rate limiting +
|
|
1246
|
+
security headers + body-size caps live INSIDE this app's middleware
|
|
1247
|
+
stack — the parent FastAPI app.mount() does NOT propagate its own
|
|
1248
|
+
middleware to mounted sub-apps (verified Starlette behavior).
|
|
1249
|
+
|
|
1250
|
+
auth_mode (additive, default "tenant" = hosted byte-identical):
|
|
1251
|
+
"tenant" → TeamResolutionMiddleware (registry Bearer tt_ keys)
|
|
1252
|
+
"static" → StaticKeyMiddleware (single TORTOISE_API_KEY, self-host LAN)
|
|
1253
|
+
"none" → no auth middleware (localhost-bound self-host eval)
|
|
1254
|
+
|
|
1255
|
+
tool_group: optional curation-group filter (#523) — role-scoped server
|
|
1256
|
+
(e.g. "memory" exposes only memory tools to the agent).
|
|
1257
|
+
|
|
1258
|
+
path="/": the app is mounted at /mcp on the parent FastAPI app, which
|
|
1259
|
+
strips the mount prefix before dispatching to this sub-app — so routes
|
|
1260
|
+
must live at / (parent /mcp → sub-app /). The GET /mcp metadata route
|
|
1261
|
+
is registered on the shared module-level mcp instance — safe for stdio
|
|
1262
|
+
(route unused) and coexists with the POST/DELETE streamable-http route.
|
|
1263
|
+
"""
|
|
1264
|
+
from starlette.middleware import Middleware
|
|
1265
|
+
from starlette.responses import JSONResponse
|
|
1266
|
+
from tortoise.mcp_auth import (MCPRateLimitMiddleware,
|
|
1267
|
+
SecurityHeadersMiddleware,
|
|
1268
|
+
RequestBodySizeMiddleware)
|
|
1269
|
+
from fastmcp.server.transforms import Transform
|
|
1270
|
+
|
|
1271
|
+
# auth_mode middleware selection. TeamResolutionMiddleware (tenant mode) is
|
|
1272
|
+
# imported here but only ever INSTANTIATED in the tenant branch — static/none
|
|
1273
|
+
# modes never construct it, and hosted_api is only ever lazily imported when
|
|
1274
|
+
# a tenant token is verified (mcp_auth delegates via function-level import).
|
|
1275
|
+
auth_mw = None
|
|
1276
|
+
transport_mw = None
|
|
1277
|
+
group_mw = None
|
|
1278
|
+
if tool_group:
|
|
1279
|
+
from tortoise.mcp_auth import ToolGroupMiddleware
|
|
1280
|
+
group_mw = Middleware(ToolGroupMiddleware, tool_group=tool_group)
|
|
1281
|
+
if auth_mode == "tenant":
|
|
1282
|
+
from tortoise.mcp_auth import TeamResolutionMiddleware
|
|
1283
|
+
auth_mw = Middleware(TeamResolutionMiddleware, registry_sdk=_registry_sdk)
|
|
1284
|
+
elif auth_mode == "static":
|
|
1285
|
+
from tortoise.mcp_auth import StaticKeyMiddleware
|
|
1286
|
+
auth_mw = Middleware(StaticKeyMiddleware, api_key=api_key)
|
|
1287
|
+
from tortoise.mcp_auth import TransportModeMiddleware
|
|
1288
|
+
transport_mw = Middleware(TransportModeMiddleware)
|
|
1289
|
+
elif auth_mode == "none":
|
|
1290
|
+
from tortoise.mcp_auth import TransportModeMiddleware
|
|
1291
|
+
transport_mw = Middleware(TransportModeMiddleware)
|
|
1292
|
+
|
|
1293
|
+
class _HTTPToolFilter(Transform):
|
|
1294
|
+
"""Hide HTTP-excluded tools from tools/list (D4) + optional curation
|
|
1295
|
+
group scoping (#523).
|
|
1296
|
+
|
|
1297
|
+
The excluded tools (team_create/backfill_v25/ingest_corpus) remain
|
|
1298
|
+
registered on the shared module-level mcp instance for stdio, but are
|
|
1299
|
+
filtered out of the HTTP tool listing so tenants can't discover them.
|
|
1300
|
+
When tool_group is set, only that group's tools are listed — role-
|
|
1301
|
+
scoped servers keep the agent's tool-selection surface under ~20.
|
|
1302
|
+
"""
|
|
1303
|
+
async def list_tools(self, tools):
|
|
1304
|
+
from tortoise.mcp_auth import _tool_group
|
|
1305
|
+
group = _tool_group.get()
|
|
1306
|
+
if group:
|
|
1307
|
+
from tortoise.tool_registry import GROUP_BY_NAME
|
|
1308
|
+
return [t for t in tools
|
|
1309
|
+
if t.name in HTTP_ALLOWED
|
|
1310
|
+
and GROUP_BY_NAME.get(t.name) == group]
|
|
1311
|
+
return [t for t in tools if t.name in HTTP_ALLOWED]
|
|
1312
|
+
|
|
1313
|
+
# Guard against transform accumulation: create_http_app() is called at
|
|
1314
|
+
# hosted_api import AND in every test fixture — each call would append a
|
|
1315
|
+
# new _HTTPToolFilter to the shared module-level mcp instance (code-review
|
|
1316
|
+
# P2 fix). Register once.
|
|
1317
|
+
if not getattr(mcp, "_http_tool_filter_registered", False):
|
|
1318
|
+
mcp.add_transform(_HTTPToolFilter())
|
|
1319
|
+
mcp._http_tool_filter_registered = True
|
|
1320
|
+
|
|
1321
|
+
@mcp.custom_route("/", methods=["GET"])
|
|
1322
|
+
async def mcp_metadata(request):
|
|
1323
|
+
return JSONResponse({"status": "ok", "protocol": "mcp",
|
|
1324
|
+
"transport": "streamable-http",
|
|
1325
|
+
"endpoint": "/mcp"})
|
|
1326
|
+
|
|
1327
|
+
middleware = [
|
|
1328
|
+
Middleware(SecurityHeadersMiddleware),
|
|
1329
|
+
Middleware(RequestBodySizeMiddleware),
|
|
1330
|
+
]
|
|
1331
|
+
if auth_mw is not None and auth_mode == "tenant":
|
|
1332
|
+
# Original position: tenant auth sits between body-size and rate-limit
|
|
1333
|
+
# (byte-identical to pre-auth_mode hosted stack).
|
|
1334
|
+
middleware.append(auth_mw)
|
|
1335
|
+
middleware.append(Middleware(MCPRateLimitMiddleware, max_per_minute=rate_limit))
|
|
1336
|
+
if auth_mw is not None and auth_mode != "tenant":
|
|
1337
|
+
# Static mode: rate limiter sits OUTSIDE auth so failed-key attempts are
|
|
1338
|
+
# throttled (code-review P1 — unlimited brute force on a user-chosen key).
|
|
1339
|
+
middleware.append(auth_mw)
|
|
1340
|
+
if transport_mw is not None:
|
|
1341
|
+
# Innermost — runs after auth validated, right before the app:
|
|
1342
|
+
# initializes the transport-mode ContextVars selfhost tools need.
|
|
1343
|
+
middleware.append(transport_mw)
|
|
1344
|
+
if group_mw is not None:
|
|
1345
|
+
# Sets the curation-group ContextVar for the tools/list transform.
|
|
1346
|
+
middleware.append(group_mw)
|
|
1347
|
+
|
|
1348
|
+
return mcp.http_app(
|
|
1349
|
+
transport="streamable-http",
|
|
1350
|
+
stateless_http=True,
|
|
1351
|
+
host_origin_protection=True,
|
|
1352
|
+
allowed_origins=allowed_origins or [],
|
|
1353
|
+
allowed_hosts=allowed_hosts or [],
|
|
1354
|
+
path="/",
|
|
1355
|
+
middleware=middleware,
|
|
1356
|
+
)
|