stele-mcp 18.16.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ build/
7
+ dist/
8
+ .venv/
9
+ venv/
10
+
11
+ # Tooling caches
12
+ .pytest_cache/
13
+ .mypy_cache/
14
+ .ruff_cache/
15
+ .coverage
16
+ htmlcov/
17
+
18
+ # Editors / OS
19
+ .vscode/
20
+ .idea/
21
+ .DS_Store
22
+
23
+ # Local scratch
24
+ *.local.*
25
+ tmp/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stele contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.5
2
+ Name: stele-mcp
3
+ Version: 18.16.1
4
+ Summary: MCP stdio server for Stele — named tools over the governed experiential-memory ledger.
5
+ Project-URL: Homepage, https://github.com/leocelis/stele
6
+ Project-URL: Documentation, https://github.com/leocelis/stele/blob/main/docs/OSS_GUIDE.md
7
+ Project-URL: Repository, https://github.com/leocelis/stele
8
+ Project-URL: Changelog, https://github.com/leocelis/stele/blob/main/CHANGELOG.md
9
+ Author: Stele contributors
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: ai-agents,mcp,memory,stele
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: mcp<2,>=1.0
22
+ Requires-Dist: stele-core
23
+ Provides-Extra: hosted
24
+ Requires-Dist: httpx>=0.27; extra == 'hosted'
25
+ Requires-Dist: starlette>=0.37; extra == 'hosted'
26
+ Requires-Dist: stele-core[mysql]; extra == 'hosted'
27
+ Requires-Dist: uvicorn>=0.30; extra == 'hosted'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # stele-mcp
31
+
32
+ MCP stdio server for [`stele-core`](../stele-core).
33
+
34
+ ## Tools
35
+
36
+ | Tool | Role |
37
+ |---|---|
38
+ | `stele_add` | Quarantine a distilled entry |
39
+ | `stele_update` | Patch non-state fields |
40
+ | `stele_promote` | Oracle-gated promotion |
41
+ | `stele_supersede` | Invalidate old belief; new entry quarantined |
42
+ | `stele_delete` | True erase by entry or subject |
43
+ | `stele_search` | Budgeted hybrid retrieval |
44
+ | `stele_reflect` | Dedupe / expire / surface conflicts |
45
+ | `stele_list_contested` | Open conflict queue |
46
+ | `stele_resolve_contested` | Evidenced supersede of a contested pair |
47
+ | `stele_link` | Link entry → artifact/test/entry/source |
48
+
49
+ ## Run
50
+
51
+ ```bash
52
+ export STELE_STORE=./.stele-store
53
+ stele-mcp
54
+ ```
@@ -0,0 +1,25 @@
1
+ # stele-mcp
2
+
3
+ MCP stdio server for [`stele-core`](../stele-core).
4
+
5
+ ## Tools
6
+
7
+ | Tool | Role |
8
+ |---|---|
9
+ | `stele_add` | Quarantine a distilled entry |
10
+ | `stele_update` | Patch non-state fields |
11
+ | `stele_promote` | Oracle-gated promotion |
12
+ | `stele_supersede` | Invalidate old belief; new entry quarantined |
13
+ | `stele_delete` | True erase by entry or subject |
14
+ | `stele_search` | Budgeted hybrid retrieval |
15
+ | `stele_reflect` | Dedupe / expire / surface conflicts |
16
+ | `stele_list_contested` | Open conflict queue |
17
+ | `stele_resolve_contested` | Evidenced supersede of a contested pair |
18
+ | `stele_link` | Link entry → artifact/test/entry/source |
19
+
20
+ ## Run
21
+
22
+ ```bash
23
+ export STELE_STORE=./.stele-store
24
+ stele-mcp
25
+ ```
@@ -0,0 +1,52 @@
1
+ [project]
2
+ name = "stele-mcp"
3
+ version = "18.16.1"
4
+ description = "MCP stdio server for Stele — named tools over the governed experiential-memory ledger."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Stele contributors" }]
10
+ keywords = ["mcp", "ai-agents", "memory", "stele"]
11
+ classifiers = [
12
+ "Development Status :: 5 - Production/Stable",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Intended Audience :: Developers",
18
+ "Typing :: Typed",
19
+ ]
20
+ dependencies = [
21
+ "stele-core",
22
+ "mcp>=1.0,<2",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ hosted = [
27
+ "stele-core[mysql]",
28
+ "uvicorn>=0.30",
29
+ "starlette>=0.37",
30
+ "httpx>=0.27",
31
+ ]
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/leocelis/stele"
35
+ Documentation = "https://github.com/leocelis/stele/blob/main/docs/OSS_GUIDE.md"
36
+ Repository = "https://github.com/leocelis/stele"
37
+ Changelog = "https://github.com/leocelis/stele/blob/main/CHANGELOG.md"
38
+
39
+ [project.scripts]
40
+ stele-mcp = "stele_mcp.server:main_core"
41
+ stele-mcp-core = "stele_mcp.server:main_core"
42
+ stele-mcp-full = "stele_mcp.server:main"
43
+
44
+ [build-system]
45
+ requires = ["hatchling"]
46
+ build-backend = "hatchling.build"
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ packages = ["src/stele_mcp"]
50
+
51
+ [tool.uv.sources]
52
+ stele-core = { workspace = true }
@@ -0,0 +1,7 @@
1
+ """Stele MCP server package."""
2
+
3
+ from stele_mcp.server import main, mcp
4
+
5
+ __all__ = ["main", "mcp"]
6
+
7
+ __version__ = "1.1.0"
@@ -0,0 +1,223 @@
1
+ """Bearer auth + in-process rate limit for hosted Stele MCP (HTTP only).
2
+
3
+ Reads API keys from STELE_API_KEYS (comma-separated). Stdio transport never
4
+ uses this middleware (process isolation).
5
+
6
+ Fail-closed: empty STELE_API_KEYS rejects all non-exempt requests unless
7
+ STELE_AUTH_DISABLED=true (local tests only — never on hosted).
8
+
9
+ Key generation:
10
+ python -c "import secrets; print('stl_deploy_' + secrets.token_urlsafe(24))"
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import collections
16
+ import contextvars
17
+ import hashlib
18
+ import hmac
19
+ import logging
20
+ import os
21
+ import secrets
22
+ import threading
23
+ import time
24
+
25
+ from starlette.requests import Request
26
+ from starlette.responses import JSONResponse
27
+
28
+ current_key_id: contextvars.ContextVar[str] = contextvars.ContextVar(
29
+ "stele_current_key_id", default="local"
30
+ )
31
+ current_key_sha: contextvars.ContextVar[str] = contextvars.ContextVar(
32
+ "stele_current_key_sha", default=""
33
+ )
34
+
35
+ _log = logging.getLogger("stele_mcp.auth")
36
+
37
+ _raw = os.environ.get("STELE_API_KEYS", "")
38
+ VALID_API_KEYS: set[str] = {k.strip() for k in _raw.split(",") if k.strip()}
39
+ AUTH_DISABLED: bool = os.environ.get("STELE_AUTH_DISABLED", "false").lower() == "true"
40
+ _EXEMPT_PATHS: frozenset[str] = frozenset({"/health", "/healthz"})
41
+
42
+ RATE_LIMIT_PER_MINUTE: float = float(os.environ.get("STELE_RATE_LIMIT_PER_MINUTE", "120"))
43
+ RATE_LIMIT_BURST: float = float(os.environ.get("STELE_RATE_LIMIT_BURST", "20"))
44
+ _MAX_TRACKED_RATE_LIMIT_KEYS = 1000
45
+
46
+
47
+ class _TokenBucket:
48
+ __slots__ = ("tokens", "last_refill")
49
+
50
+ def __init__(self, capacity: float, now: float) -> None:
51
+ self.tokens = capacity
52
+ self.last_refill = now
53
+
54
+
55
+ class RateLimiter:
56
+ """In-process per-key token bucket. Correct for instance_count=1 only."""
57
+
58
+ def __init__(
59
+ self,
60
+ rate_per_minute: float = RATE_LIMIT_PER_MINUTE,
61
+ burst: float = RATE_LIMIT_BURST,
62
+ max_tracked_keys: int = _MAX_TRACKED_RATE_LIMIT_KEYS,
63
+ ) -> None:
64
+ self._rate_per_second = rate_per_minute / 60.0
65
+ self._burst = burst
66
+ self._max_tracked = max_tracked_keys
67
+ self._buckets: collections.OrderedDict[str, _TokenBucket] = collections.OrderedDict()
68
+ self._lock = threading.Lock()
69
+
70
+ def allow(self, key: str) -> tuple[bool, float]:
71
+ now = time.monotonic()
72
+ with self._lock:
73
+ bucket = self._buckets.get(key)
74
+ if bucket is None:
75
+ bucket = _TokenBucket(self._burst, now)
76
+ self._buckets[key] = bucket
77
+ if len(self._buckets) > self._max_tracked:
78
+ self._buckets.popitem(last=False)
79
+ else:
80
+ self._buckets.move_to_end(key)
81
+
82
+ elapsed = now - bucket.last_refill
83
+ bucket.tokens = min(self._burst, bucket.tokens + elapsed * self._rate_per_second)
84
+ bucket.last_refill = now
85
+
86
+ if bucket.tokens >= 1.0:
87
+ bucket.tokens -= 1.0
88
+ return True, 0.0
89
+
90
+ deficit = 1.0 - bucket.tokens
91
+ retry_after = deficit / self._rate_per_second if self._rate_per_second > 0 else 60.0
92
+ return False, retry_after
93
+
94
+
95
+ _rate_limiter = RateLimiter()
96
+
97
+
98
+ class SteleAuthMiddleware:
99
+ """ASGI middleware: Bearer tokens for all non-exempt HTTP paths."""
100
+
101
+ def __init__(self, app) -> None:
102
+ self.app = app
103
+
104
+ async def __call__(self, scope, receive, send) -> None:
105
+ if scope["type"] != "http":
106
+ await self.app(scope, receive, send)
107
+ return
108
+
109
+ path: str = scope.get("path", "")
110
+
111
+ if path in _EXEMPT_PATHS or AUTH_DISABLED:
112
+ await self.app(scope, receive, send)
113
+ return
114
+
115
+ err, key_id, key_sha = _extract_and_validate(scope)
116
+ if err is not None:
117
+ response = JSONResponse(err, status_code=401)
118
+ await response(scope, receive, send)
119
+ return
120
+
121
+ allowed, retry_after = _rate_limiter.allow(key_id)
122
+ if not allowed:
123
+ _log.warning(
124
+ "AUTH rate_limited key=%s path=%s retry_after=%.1fs", key_id, path, retry_after
125
+ )
126
+ response = JSONResponse(
127
+ {"error": "Rate limit exceeded", "retry_after_seconds": round(retry_after, 1)},
128
+ status_code=429,
129
+ headers={
130
+ "Retry-After": str(int(retry_after) + 1),
131
+ "RateLimit-Policy": f'"default";q={int(RATE_LIMIT_PER_MINUTE)};w=60',
132
+ "RateLimit": '"default";r=0',
133
+ },
134
+ )
135
+ await response(scope, receive, send)
136
+ return
137
+
138
+ _log.info("AUTH ok key=%s path=%s", key_id, path)
139
+ token = current_key_id.set(key_id)
140
+ sha_token = current_key_sha.set(key_sha)
141
+ try:
142
+ await self.app(scope, receive, send)
143
+ finally:
144
+ current_key_sha.reset(sha_token)
145
+ current_key_id.reset(token)
146
+
147
+
148
+ def _extract_and_validate(scope) -> tuple[dict | None, str | None, str]:
149
+ path = scope.get("path", "")
150
+
151
+ if not VALID_API_KEYS and not AUTH_DISABLED:
152
+ _log.warning("AUTH no_keys_configured path=%s — rejecting (fail-closed)", path)
153
+ return {
154
+ "error": (
155
+ "Server has no API keys configured (STELE_API_KEYS is unset). "
156
+ "Refusing all requests. Set STELE_API_KEYS, or "
157
+ "STELE_AUTH_DISABLED=true for local dev only."
158
+ )
159
+ }, None, ""
160
+
161
+ headers: dict[bytes, bytes] = dict(scope.get("headers", []))
162
+ raw_auth: str = headers.get(b"authorization", b"").decode("utf-8", errors="replace")
163
+
164
+ if not raw_auth:
165
+ _log.warning("AUTH missing_header path=%s", path)
166
+ return {"error": "Missing Authorization header"}, None, ""
167
+
168
+ if not raw_auth.startswith("Bearer "):
169
+ _log.warning("AUTH bad_format path=%s", path)
170
+ return {"error": "Invalid Authorization header. Expected: Bearer <token>"}, None, ""
171
+
172
+ api_key = raw_auth[7:].strip()
173
+
174
+ if not api_key:
175
+ _log.warning("AUTH empty_key path=%s", path)
176
+ return {"error": "Empty API key"}, None, ""
177
+
178
+ if AUTH_DISABLED and not VALID_API_KEYS:
179
+ _log.warning(
180
+ "AUTH no_keys_configured path=%s — allowed (STELE_AUTH_DISABLED=true)", path
181
+ )
182
+ return None, "unconfigured", ""
183
+
184
+ if not _key_matches(api_key):
185
+ _log.warning("AUTH invalid_key key_prefix=%s path=%s", api_key[:8], path)
186
+ return {"error": "Invalid API key"}, None, ""
187
+
188
+ return None, _key_id(api_key), hashlib.sha256(api_key.encode()).hexdigest()
189
+
190
+
191
+ def _key_matches(candidate: str) -> bool:
192
+ matched = False
193
+ for valid_key in VALID_API_KEYS:
194
+ if hmac.compare_digest(candidate, valid_key):
195
+ matched = True
196
+ return matched
197
+
198
+
199
+ def _key_id(api_key: str) -> str:
200
+ return hashlib.sha256(api_key.encode()).hexdigest()[:8]
201
+
202
+
203
+ async def validate_api_key(request: Request) -> tuple[JSONResponse | None, str | None]:
204
+ if AUTH_DISABLED:
205
+ return None, None
206
+
207
+ path = request.url.path
208
+ if path in _EXEMPT_PATHS:
209
+ return None, None
210
+
211
+ err, key_id, _sha = _extract_and_validate({"headers": list(request.headers.raw), "path": path})
212
+ if err is not None:
213
+ return JSONResponse(err, status_code=401), None
214
+ return None, key_id
215
+
216
+
217
+ def generate_api_key(username: str = "user") -> str:
218
+ token = secrets.token_urlsafe(24)
219
+ return f"stl_{username}_{token}"
220
+
221
+
222
+ def hash_api_key(api_key: str) -> str:
223
+ return hashlib.sha256(api_key.encode()).hexdigest()
File without changes