sessionyard 0.7.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.
Files changed (62) hide show
  1. agent_chat/001_core.sql +172 -0
  2. agent_chat/002_coordination.sql +63 -0
  3. agent_chat/003_harness_admission.sql +10 -0
  4. agent_chat/004_session_titles.sql +3 -0
  5. agent_chat/005_viewer.sql +9 -0
  6. agent_chat/006_quotas.sql +6 -0
  7. agent_chat/007_sender_receipts.sql +20 -0
  8. agent_chat/008_direct_threads.sql +49 -0
  9. agent_chat/009_pm_mark.sql +23 -0
  10. agent_chat/010_quota_backfill.sql +12 -0
  11. agent_chat/011_roles_and_work.sql +31 -0
  12. agent_chat/__init__.py +1 -0
  13. agent_chat/adapter.py +414 -0
  14. agent_chat/admin.py +524 -0
  15. agent_chat/api.py +641 -0
  16. agent_chat/auth.py +226 -0
  17. agent_chat/browser.py +118 -0
  18. agent_chat/browser_verify.py +487 -0
  19. agent_chat/browser_verify_artifacts.py +280 -0
  20. agent_chat/browser_verify_checks.py +236 -0
  21. agent_chat/browser_verify_run.py +523 -0
  22. agent_chat/cli.py +532 -0
  23. agent_chat/client.py +272 -0
  24. agent_chat/deliveries.py +555 -0
  25. agent_chat/events.py +48 -0
  26. agent_chat/feed.py +193 -0
  27. agent_chat/http_boundary.py +154 -0
  28. agent_chat/instance_client.py +349 -0
  29. agent_chat/instance_file.py +207 -0
  30. agent_chat/instance_worker.py +326 -0
  31. agent_chat/mcp/__init__.py +5 -0
  32. agent_chat/mcp/__main__.py +39 -0
  33. agent_chat/mcp/app.py +183 -0
  34. agent_chat/mcp/auth.py +67 -0
  35. agent_chat/mcp/config.py +55 -0
  36. agent_chat/mcp/tools.py +295 -0
  37. agent_chat/metrics.py +60 -0
  38. agent_chat/models.py +430 -0
  39. agent_chat/openapi.py +322 -0
  40. agent_chat/producer.py +208 -0
  41. agent_chat/protocol.py +71 -0
  42. agent_chat/publication.py +252 -0
  43. agent_chat/receipts.py +225 -0
  44. agent_chat/retention.py +154 -0
  45. agent_chat/roles.py +153 -0
  46. agent_chat/rooms.py +179 -0
  47. agent_chat/sessions.py +340 -0
  48. agent_chat/skills/agent-chat/SKILL.md +64 -0
  49. agent_chat/state.py +144 -0
  50. agent_chat/storage.py +110 -0
  51. agent_chat/threads.py +50 -0
  52. agent_chat/web/Manrope-OFL.txt +93 -0
  53. agent_chat/web/Manrope-Variable.ttf +0 -0
  54. agent_chat/web/chat.css +936 -0
  55. agent_chat/web/chat.js +1922 -0
  56. agent_chat/web/i18n.js +340 -0
  57. agent_chat/web/index.html +264 -0
  58. sessionyard-0.7.0.dist-info/METADATA +314 -0
  59. sessionyard-0.7.0.dist-info/RECORD +62 -0
  60. sessionyard-0.7.0.dist-info/WHEEL +4 -0
  61. sessionyard-0.7.0.dist-info/entry_points.txt +3 -0
  62. sessionyard-0.7.0.dist-info/licenses/LICENSE +661 -0
@@ -0,0 +1,326 @@
1
+ """One private stdin/stdout lifecycle worker; no launcher, native send or retry.
2
+
3
+ The parent supplies one explicit join, then serial heartbeat, pending, claim, settle,
4
+ status, receipts, receipts_delivered and end requests. EOF, idle expiry and failure end only this
5
+ instance. All I/O runs under a real process deadline, including DNS and pipe backpressure. Imports
6
+ start nothing.
7
+ """
8
+
9
+ import json
10
+ import re
11
+ import signal
12
+ import sys
13
+ from collections.abc import Callable
14
+ from pathlib import Path
15
+ from time import monotonic
16
+ from typing import Any
17
+ from uuid import UUID
18
+
19
+ from . import instance_client, instance_file
20
+ from .models import LEASE_SECONDS, ChatError, DeliveryClaim, DeliveryResult, Heartbeat, ReceiptDelivery
21
+
22
+ MAX_FRAME = 128 * 1024
23
+ REQUEST_SECONDS = 20
24
+ IDLE_SECONDS = 90
25
+ # A server restart fails a poll or a heartbeat without ending the session. Each op tolerates its own
26
+ # unbroken failure streak for less than the server lease; one success of that op ends the streak.
27
+ # A repeated heartbeat is safe, a claim or settle is not. Receipts are advisory and have no streak: a receipt
28
+ # read or mark that fails, whatever the code or the length of the failure, answers `refused` and never ends the
29
+ # worker, because the parent offers the receipt again at its next poll. Liveness stays with heartbeat, pending
30
+ # and claim, which fail closed. The receipts read includes the session's mute flag (`_receipts_with_mute`), so a
31
+ # failed mute read is the same refusal, not the fatal `status` request.
32
+ PENDING_OUTAGE = frozenset({"TRANSPORT_UNAVAILABLE", "SERVICE_UNAVAILABLE"})
33
+ HEARTBEAT_OUTAGE = PENDING_OUTAGE | {"REQUEST_UNCERTAIN"}
34
+
35
+
36
+ def _interrupt(_signum: int, _frame: Any) -> None:
37
+ raise TimeoutError("worker interrupted")
38
+
39
+
40
+ def _read(expected: int) -> dict[str, Any] | None:
41
+ raw = sys.stdin.buffer.readline(MAX_FRAME + 1)
42
+ if not raw:
43
+ return None
44
+ if len(raw) > MAX_FRAME or not raw.endswith(b"\n"):
45
+ raise ChatError("INVALID_REQUEST")
46
+ request = json.loads(raw.decode("utf-8"))
47
+ if not isinstance(request, dict) or type(request.get("id")) is not int or request["id"] != expected:
48
+ raise ChatError("INVALID_REQUEST")
49
+ return request
50
+
51
+
52
+ def _write(frame: dict[str, Any], credentials: tuple[str, ...]) -> None:
53
+ rendered = json.dumps(frame, ensure_ascii=True)
54
+ # Lifecycle replies contain metadata only. Never pass a reflected credential
55
+ # to the parent even if an upstream response contains it in a label.
56
+ for credential in credentials:
57
+ if credential:
58
+ rendered = re.sub(re.escape(credential), "[REDACTED]", rendered, flags=re.IGNORECASE)
59
+ data = (rendered + "\n").encode("ascii")
60
+ if len(data) > MAX_FRAME:
61
+ raise ChatError("INVALID_RESPONSE")
62
+ sys.stdout.buffer.write(data)
63
+ sys.stdout.buffer.flush()
64
+
65
+
66
+ def _join(request: dict[str, Any]) -> instance_client.JoinedInstance:
67
+ if (
68
+ set(request)
69
+ != {
70
+ "id",
71
+ "op",
72
+ "enabled",
73
+ "directory",
74
+ "native_session_id",
75
+ "boot_id",
76
+ "server_origin",
77
+ "host_token",
78
+ "harness",
79
+ }
80
+ or request["op"] != "join"
81
+ ):
82
+ raise ChatError("INVALID_REQUEST")
83
+ if not isinstance(request["directory"], str) or not Path(request["directory"]).is_absolute():
84
+ raise ChatError("INVALID_REQUEST")
85
+ return instance_client.join_instance(
86
+ Path(request["directory"]),
87
+ request["native_session_id"],
88
+ UUID(request["boot_id"]),
89
+ server_origin=request["server_origin"],
90
+ host_token=request["host_token"],
91
+ harness=request["harness"],
92
+ enabled=request["enabled"],
93
+ )
94
+
95
+
96
+ def _end(instance: instance_client.JoinedInstance, directory: Path) -> dict[str, Any]:
97
+ """End this binding, then drop its record; a failed end keeps the file and the server lease is the fallback."""
98
+ result = instance_client.end(instance)
99
+ instance_file.discard_instance(directory, instance.binding.boot_id)
100
+ return result
101
+
102
+
103
+ def _asks_bodies(request: dict[str, Any]) -> bool:
104
+ """The optional `bodies` flag of pending and claim: absent is false, and only a JSON boolean is accepted."""
105
+ flag = request.get("bodies", False)
106
+ if type(flag) is not bool:
107
+ raise ChatError("INVALID_REQUEST")
108
+ return flag
109
+
110
+
111
+ def _is_pending(request: dict[str, Any]) -> bool:
112
+ return request.get("op") == "pending" and {"id", "op"} <= set(request) <= {"id", "op", "bodies"}
113
+
114
+
115
+ def _delivery(instance: instance_client.JoinedInstance, request: dict[str, Any]) -> dict[str, Any]:
116
+ operation = request.get("op")
117
+ try:
118
+ if _is_pending(request):
119
+ return instance_client.pending(instance, _asks_bodies(request))
120
+ if operation == "claim" and {"id", "op", "key", "messages"} <= set(request) <= {
121
+ "id",
122
+ "op",
123
+ "key",
124
+ "messages",
125
+ "bodies",
126
+ }:
127
+ return instance_client.claim(
128
+ instance, UUID(request["key"]), DeliveryClaim(messages=request["messages"]), _asks_bodies(request)
129
+ )
130
+ if operation == "settle" and set(request) == {"id", "op", "attempt", "result"}:
131
+ return instance_client.settle(
132
+ instance, UUID(request["attempt"]), DeliveryResult.model_validate(request["result"])
133
+ )
134
+ except ChatError as error:
135
+ # A definite refusal is the ledger's answer, not a failed transport, and that holds for settlement
136
+ # too: a reservation that lapsed while the native send ran answers DELIVERY_CLOSED, and the server has
137
+ # already settled the attempt as uncertain. Ending the worker there would disable chat for the whole
138
+ # session over an ordinary race. Only an uncertain or unavailable transport ends the worker.
139
+ if error.code in {
140
+ "DELIVERY_DISABLED",
141
+ "DELIVERY_BLOCKED",
142
+ "DELIVERY_IN_FLIGHT",
143
+ "DELIVERY_BATCH_CONFLICT",
144
+ "DELIVERY_CLOSED",
145
+ "DELIVERY_EXHAUSTED",
146
+ "DELIVERY_BACKOFF",
147
+ "DELIVERY_INELIGIBLE",
148
+ "CONSULTATION_LIMIT",
149
+ "WAKE_LIMIT",
150
+ "NOT_FOUND",
151
+ "MESSAGE_EXPIRED",
152
+ }:
153
+ return {"refused": error.code}
154
+ raise
155
+ raise ChatError("INVALID_REQUEST")
156
+
157
+
158
+ def _receipts_with_mute(instance: instance_client.JoinedInstance) -> dict[str, Any]:
159
+ """The receipt feed, and the session's `muted` flag when the feed has rows, as one answer.
160
+
161
+ A receipt waits while the session is muted, so the parent needs the flag before it shows one. `status` is a
162
+ fatal request in this worker: a parent that asked for it separately would end the session over an advisory
163
+ receipt. The flag is read here instead, inside the receipt refusal, so a failed or malformed read answers
164
+ `refused` for the whole request and the worker keeps serving. An empty feed has nothing to hold, so it needs no
165
+ flag. An older worker never sends one, which a parent must read as muted.
166
+ """
167
+ feed = instance_client.receipts(instance)
168
+ if feed["receipts"]:
169
+ muted = instance_client.status(instance).get("muted")
170
+ if type(muted) is not bool:
171
+ raise ChatError("INVALID_RESPONSE")
172
+ feed["muted"] = muted
173
+ return feed
174
+
175
+
176
+ def main() -> int:
177
+ instance = None
178
+ directory: Path | None = None
179
+ ended = False
180
+ sequence = 0
181
+ code = 0
182
+ credentials: tuple[str, ...] = ()
183
+ pending_at: float | None = None
184
+ pending_delay = 2.0
185
+ published_state: Heartbeat | None = None
186
+ failing_since: dict[str, float] = {}
187
+ terminated = False
188
+
189
+ def _terminate(signum: int, frame: Any) -> None:
190
+ # SIGTERM makes the blocked request fail like a transport error. Record it so it is never tolerated.
191
+ nonlocal terminated
192
+ terminated = True
193
+ _interrupt(signum, frame)
194
+
195
+ def _outage(op: str, error: ChatError, codes: frozenset[str]) -> bool:
196
+ if terminated or error.code not in codes:
197
+ return False
198
+ return monotonic() - failing_since.setdefault(op, monotonic()) < LEASE_SECONDS
199
+
200
+ def _receipt(call: Callable[..., Any], *arguments: Any) -> Any:
201
+ try:
202
+ return call(*arguments)
203
+ except ChatError as error:
204
+ if terminated: # SIGTERM interrupted the call: a stop still ends the worker
205
+ raise
206
+ return {"refused": error.code}
207
+
208
+ signal.signal(signal.SIGALRM, _interrupt)
209
+ signal.signal(signal.SIGTERM, _terminate)
210
+ signal.setitimer(signal.ITIMER_REAL, REQUEST_SECONDS)
211
+ try:
212
+ request = _read(0)
213
+ if request is None:
214
+ return 0
215
+ instance = _join(request)
216
+ directory = Path(request["directory"])
217
+ credentials = (request["host_token"], instance.binding.token)
218
+ _write(
219
+ {
220
+ "id": 0,
221
+ "result": {
222
+ "session_id": str(instance.session_id),
223
+ "instance_id": str(instance.instance_id),
224
+ "room_id": str(instance.room_id),
225
+ "host": instance.host,
226
+ "harness": instance.harness,
227
+ "instance_file": str(directory / f"{instance.binding.boot_id}.json"),
228
+ },
229
+ },
230
+ credentials,
231
+ )
232
+ # Host authority is not needed again. Do not retain it across idle waits.
233
+ credentials = (instance.binding.token,)
234
+ request = None
235
+ # Local housekeeping after the join reply: peers' records untouched for an hour. No content, no network.
236
+ instance_file.sweep_stale(directory, instance.binding.boot_id)
237
+ while True:
238
+ sequence += 1
239
+ signal.setitimer(signal.ITIMER_REAL, IDLE_SECONDS)
240
+ request = _read(sequence)
241
+ signal.setitimer(signal.ITIMER_REAL, REQUEST_SECONDS)
242
+ if request is None:
243
+ break
244
+ operation = request.get("op")
245
+ if operation == "heartbeat" and set(request) == {"id", "op", "state"}:
246
+ state = Heartbeat.model_validate(request["state"])
247
+ try:
248
+ result = instance_client.heartbeat(instance, state)
249
+ except ChatError as error:
250
+ if not _outage("heartbeat", error, HEARTBEAT_OUTAGE):
251
+ raise
252
+ # Nothing was published or renewed; the parent's next heartbeat is the retry.
253
+ result = {"refused": error.code}
254
+ else:
255
+ failing_since.pop("heartbeat", None)
256
+ instance_file.touch_instance(directory, instance.binding.boot_id)
257
+ if state != published_state:
258
+ pending_at, pending_delay = None, 2.0
259
+ published_state = state
260
+ elif _is_pending(request):
261
+ if pending_at is not None and monotonic() < pending_at:
262
+ result = {"messages": []}
263
+ else:
264
+ try:
265
+ result = _delivery(instance, request)
266
+ except ChatError as error:
267
+ if not _outage("pending", error, PENDING_OUTAGE):
268
+ raise
269
+ result = {"refused": error.code}
270
+ else:
271
+ # An admission refusal also proves the server answered.
272
+ failing_since.pop("pending", None)
273
+ if result == {"messages": []}:
274
+ pending_at = monotonic() + pending_delay
275
+ pending_delay = min(8.0, pending_delay * 2)
276
+ elif result.get("messages"):
277
+ pending_at, pending_delay = None, 2.0
278
+ elif operation == "status" and set(request) == {"id", "op"}:
279
+ result = instance_client.status(instance)
280
+ elif operation == "receipts" and set(request) == {"id", "op"}:
281
+ # Receipts never wake: the parent outputs them at its next native boundary, then marks them.
282
+ result = _receipt(_receipts_with_mute, instance)
283
+ elif operation == "receipts_delivered" and set(request) == {"id", "op", "receipts"}:
284
+ receipts = ReceiptDelivery(receipts=request["receipts"])
285
+ # A refusal marks nothing: the parent keeps its evidence and marks again at its next poll.
286
+ result = _receipt(instance_client.receipts_delivered, instance, receipts)
287
+ elif operation == "end" and set(request) == {"id", "op"}:
288
+ result = _end(instance, directory)
289
+ ended = True
290
+ else:
291
+ result = _delivery(instance, request)
292
+ _write({"id": sequence, "result": result}, credentials)
293
+ if ended:
294
+ break
295
+ except ChatError as error:
296
+ code = 1
297
+ _error(sequence, error.code)
298
+ except (ValueError, TypeError, KeyError, AttributeError, RecursionError):
299
+ code = 1
300
+ _error(sequence, "INVALID_REQUEST")
301
+ except (OSError, KeyboardInterrupt):
302
+ code = 1
303
+ # Timeout or loss of the parent does not prove that a mutation failed.
304
+ _error(sequence, "REQUEST_UNCERTAIN")
305
+ finally:
306
+ if instance is not None and directory is not None and not ended:
307
+ signal.setitimer(signal.ITIMER_REAL, REQUEST_SECONDS)
308
+ try:
309
+ _end(instance, directory)
310
+ except (ChatError, OSError, KeyboardInterrupt):
311
+ code = 1 # the server lease remains the fallback, not a success claim
312
+ signal.setitimer(signal.ITIMER_REAL, 0)
313
+ return code
314
+
315
+
316
+ def _error(sequence: int, code: str) -> None:
317
+ # Fixed codes only, no tracebacks, input, destination or upstream text.
318
+ signal.setitimer(signal.ITIMER_REAL, 1)
319
+ try:
320
+ _write({"id": sequence, "error": {"code": code}}, ())
321
+ except (ChatError, OSError):
322
+ pass
323
+
324
+
325
+ if __name__ == "__main__":
326
+ raise SystemExit(main())
@@ -0,0 +1,5 @@
1
+ """Optional MCP surface for Agent Chat.
2
+
3
+ The package is imported only through the ``agent-chat-mcp`` console script or
4
+ the ``mcp`` extra. The base client install stays free of FastMCP and psycopg.
5
+ """
@@ -0,0 +1,39 @@
1
+ """Launch the optional Agent Chat MCP service over Streamable HTTP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ import uvicorn
9
+
10
+ from .app import create_app
11
+ from .config import load_config
12
+
13
+
14
+ def main(argv: list[str] | None = None) -> int:
15
+ parser = argparse.ArgumentParser(
16
+ prog="agent-chat-mcp",
17
+ description="Agent Chat MCP service (Streamable HTTP, bearer instance tokens).",
18
+ )
19
+ parser.add_argument("--config", required=True, metavar="PATH", help="JSON configuration file")
20
+ args = parser.parse_args(argv)
21
+ try:
22
+ config = load_config(args.config)
23
+ except (OSError, ValueError):
24
+ print("agent-chat-mcp: CONFIG_INVALID", file=sys.stderr)
25
+ return 2
26
+ uvicorn.run(
27
+ create_app(config),
28
+ host=config.bind_host,
29
+ port=config.port,
30
+ log_config=None,
31
+ access_log=False,
32
+ proxy_headers=False,
33
+ server_header=False,
34
+ )
35
+ return 0
36
+
37
+
38
+ if __name__ == "__main__":
39
+ raise SystemExit(main())
agent_chat/mcp/app.py ADDED
@@ -0,0 +1,183 @@
1
+ """FastMCP application factory for Agent Chat."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+ from urllib.parse import urlsplit
10
+
11
+ from fastmcp import FastMCP
12
+ from fastmcp.exceptions import ToolError
13
+ from fastmcp.exceptions import ValidationError as FastMCPValidationError
14
+ from fastmcp.server.middleware import Middleware
15
+ from fastmcp.server.providers.skills import SkillsDirectoryProvider
16
+ from starlette.responses import JSONResponse, Response
17
+
18
+ from ..metrics import Metrics
19
+ from .auth import AgentChatTokenVerifier
20
+ from .config import Config
21
+ from .tools import register, registered_tool_names
22
+
23
+
24
+ class SafeToolErrors(Middleware):
25
+ """Replace framework argument-validation details with a stable code."""
26
+
27
+ def __init__(self, metrics: Metrics, tools: frozenset[str]):
28
+ self.metrics = metrics
29
+ self.tools = tools
30
+
31
+ async def on_call_tool(self, context, call_next):
32
+ requested = getattr(getattr(context, "message", None), "name", "unknown")
33
+ tool = requested if requested in self.tools else "unknown"
34
+ try:
35
+ result = await call_next(context)
36
+ except FastMCPValidationError:
37
+ self.metrics.inc("agent_chat_mcp_tool_calls_total", {"tool": tool, "outcome": "error"})
38
+ raise ToolError("INVALID_REQUEST") from None
39
+ except Exception:
40
+ self.metrics.inc("agent_chat_mcp_tool_calls_total", {"tool": tool, "outcome": "error"})
41
+ raise
42
+ payload = getattr(result, "structured_content", None)
43
+ outcome = "error" if getattr(result, "is_error", False) or (
44
+ isinstance(payload, dict) and "error" in payload
45
+ ) else "ok"
46
+ self.metrics.inc("agent_chat_mcp_tool_calls_total", {"tool": tool, "outcome": outcome})
47
+ return result
48
+
49
+
50
+ def create_mcp(config: Config, metrics: Metrics) -> FastMCP:
51
+ mcp = FastMCP(
52
+ name="agent-chat",
53
+ auth=AgentChatTokenVerifier(config.agent_chat_origin, allow_service_http=True),
54
+ middleware=[SafeToolErrors(metrics, registered_tool_names(config.enable_writes))],
55
+ mask_error_details=True,
56
+ )
57
+ skills = Path(__file__).resolve().parent.parent / "skills"
58
+ if skills.is_dir():
59
+ mcp.add_provider(SkillsDirectoryProvider(roots=skills))
60
+ register(mcp, config)
61
+ return mcp
62
+
63
+
64
+ READINESS_PROBE = r"""
65
+ import http.client
66
+ import sys
67
+ from urllib.parse import urlsplit
68
+
69
+ url = sys.stdin.readline().strip()
70
+ parts = urlsplit(url)
71
+ connection = None
72
+ try:
73
+ if parts.scheme == "https":
74
+ connection = http.client.HTTPSConnection(parts.hostname, parts.port or 443, timeout=2)
75
+ else:
76
+ connection = http.client.HTTPConnection(parts.hostname, parts.port or 80, timeout=2)
77
+ connection.request("GET", parts.path or "/readyz")
78
+ response = connection.getresponse()
79
+ sys.exit(0 if response.status == 200 else 1)
80
+ except Exception:
81
+ sys.exit(1)
82
+ finally:
83
+ if connection is not None:
84
+ connection.close()
85
+ """
86
+
87
+
88
+ class HealthEndpoints:
89
+ """Serve liveness and readiness outside MCP authentication."""
90
+
91
+ def __init__(self, app, config: Config, metrics: Metrics):
92
+ self.app = app
93
+ self.config = config
94
+ self.metrics = metrics
95
+ self._readiness: asyncio.Task[bool] | None = None
96
+
97
+ async def __call__(self, scope, receive, send):
98
+ if scope["type"] == "http" and scope["method"] == "GET":
99
+ if scope["path"] == "/healthz":
100
+ await JSONResponse({"status": "ok"})(scope, receive, send)
101
+ return
102
+ if scope["path"] == "/metrics":
103
+ await Response(self.metrics.render(), media_type="text/plain; version=0.0.4")(scope, receive, send)
104
+ return
105
+ if scope["path"] == "/readyz":
106
+ try:
107
+ ready = await self._readiness_check()
108
+ except Exception:
109
+ ready = False
110
+ if ready:
111
+ await JSONResponse({"status": "ready"})(scope, receive, send)
112
+ else:
113
+ await JSONResponse(
114
+ {"status": "not_ready", "code": "UPSTREAM_UNAVAILABLE"},
115
+ status_code=503,
116
+ )(scope, receive, send)
117
+ return
118
+ await self.app(scope, receive, send)
119
+
120
+ async def _readiness_check(self) -> bool:
121
+ if self._readiness is None or self._readiness.done():
122
+ self._readiness = asyncio.create_task(self._probe())
123
+ return await asyncio.shield(self._readiness)
124
+
125
+ async def _probe(self) -> bool:
126
+ url = f"{self.config.agent_chat_origin.rstrip('/')}/readyz"
127
+ environment = {
128
+ name: os.environ[name]
129
+ for name in ("SSL_CERT_FILE", "SSL_CERT_DIR")
130
+ if name in os.environ
131
+ }
132
+ try:
133
+ process = await asyncio.create_subprocess_exec(
134
+ sys.executable, "-c", READINESS_PROBE,
135
+ stdin=asyncio.subprocess.PIPE,
136
+ stdout=asyncio.subprocess.DEVNULL,
137
+ stderr=asyncio.subprocess.DEVNULL,
138
+ env=environment,
139
+ )
140
+ except OSError:
141
+ return False
142
+ assert process.stdin is not None
143
+ process.stdin.write(url.encode("utf-8") + b"\n")
144
+ await process.stdin.drain()
145
+ process.stdin.close()
146
+ try:
147
+ return_code = await asyncio.wait_for(process.wait(), timeout=2)
148
+ except TimeoutError:
149
+ process.kill()
150
+ await process.wait()
151
+ return False
152
+ return return_code == 0
153
+
154
+
155
+ class OriginGuard:
156
+ """Reject a present, non-allowlisted Origin before FastMCP auth runs."""
157
+
158
+ def __init__(self, app, allowed: str | None):
159
+ self.app = app
160
+ self.allowed = allowed
161
+
162
+ async def __call__(self, scope, receive, send):
163
+ if scope["type"] == "http":
164
+ origins = [value.decode("latin-1") for name, value in scope["headers"] if name.lower() == b"origin"]
165
+ if origins and (self.allowed is None or len(origins) != 1 or origins[0] != self.allowed):
166
+ await Response(status_code=403)(scope, receive, send)
167
+ return
168
+ await self.app(scope, receive, send)
169
+
170
+
171
+ def create_app(config: Config):
172
+ """Return the stateless Streamable HTTP ASGI app with an Origin guard."""
173
+ allowed_hosts = {config.bind_host, "127.0.0.1", "localhost", "::1"}
174
+ if config.public_origin is not None:
175
+ allowed_hosts.add(urlsplit(config.public_origin).hostname)
176
+ allowed_hosts = sorted(host for host in allowed_hosts if host)
177
+ metrics = Metrics()
178
+ app = create_mcp(config, metrics).http_app(
179
+ path="/mcp",
180
+ stateless_http=True,
181
+ allowed_hosts=allowed_hosts,
182
+ )
183
+ return HealthEndpoints(OriginGuard(app, config.public_origin), config, metrics)
agent_chat/mcp/auth.py ADDED
@@ -0,0 +1,67 @@
1
+ """Request-scoped authentication for the Agent Chat MCP service.
2
+
3
+ The MCP process holds no instance binding. Every MCP request presents the
4
+ caller's Agent Chat instance token; the verifier asks the local service whether
5
+ that token names a live instance. Tool calls then use the same token against the
6
+ service HTTP API. No token is cached, logged, or copied into claims.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import time
13
+ from typing import Any
14
+ from uuid import UUID
15
+
16
+ from fastmcp.server.auth import AccessToken, TokenVerifier
17
+
18
+ from ..client import Client
19
+ from ..models import ChatError
20
+
21
+ VERIFY_SECONDS = 5.0
22
+
23
+
24
+ def _canonical_uuid(value: Any) -> str | None:
25
+ if not isinstance(value, str):
26
+ return None
27
+ try:
28
+ parsed = UUID(value)
29
+ except ValueError:
30
+ return None
31
+ return str(parsed) if str(parsed) == value else None
32
+
33
+
34
+ class AgentChatTokenVerifier(TokenVerifier):
35
+ """Verify an Agent Chat instance token through GET /v1/instance/status."""
36
+
37
+ def __init__(self, agent_chat_origin: str, *, allow_service_http: bool = False):
38
+ super().__init__()
39
+ self._origin = agent_chat_origin
40
+ self._allow_service_http = allow_service_http
41
+
42
+ async def verify_token(self, token: str) -> AccessToken | None:
43
+ try:
44
+ status = await asyncio.to_thread(self._status, token)
45
+ except (ChatError, OSError, ValueError, TypeError):
46
+ return None
47
+ if not isinstance(status, dict):
48
+ return None
49
+ session_id = _canonical_uuid(status.get("session_id"))
50
+ instance_id = _canonical_uuid(status.get("instance_id"))
51
+ if session_id is None or instance_id is None or status.get("online") is not True:
52
+ return None
53
+ return AccessToken(
54
+ token=token,
55
+ client_id=session_id,
56
+ scopes=["chat:read"],
57
+ claims={"session_id": session_id, "instance_id": instance_id},
58
+ )
59
+
60
+ def _status(self, token: str) -> dict[str, Any]:
61
+ client = Client(
62
+ self._origin,
63
+ token,
64
+ deadline=time.monotonic() + VERIFY_SECONDS,
65
+ allow_service_http=self._allow_service_http,
66
+ )
67
+ return client.request("GET", "/v1/instance/status")
@@ -0,0 +1,55 @@
1
+ """Configuration for the optional Agent Chat MCP service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
9
+
10
+ from ..models import ChatError
11
+ from ..protocol import validate_origin
12
+
13
+ MAX_CONFIG_BYTES = 65536
14
+
15
+
16
+ class Config(BaseModel):
17
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
18
+
19
+ bind_host: str = Field(default="127.0.0.1", min_length=1, max_length=255)
20
+ port: int = Field(default=8951, ge=1024, le=65535)
21
+ # Internal origin of the Agent Chat service. Loopback HTTP is allowed.
22
+ agent_chat_origin: str
23
+ # Browser-origin allowlist. When unset, no browser origin is accepted.
24
+ public_origin: str | None = None
25
+ # Write tools are not registered unless this is explicitly enabled.
26
+ enable_writes: bool = False
27
+
28
+ @field_validator("agent_chat_origin")
29
+ @classmethod
30
+ def valid_service_origin(cls, value: str) -> str:
31
+ try:
32
+ validate_origin(value, allow_service_http=True)
33
+ except ChatError:
34
+ raise ValueError("agent_chat_origin must be a canonical origin") from None
35
+ return value
36
+
37
+ @field_validator("public_origin")
38
+ @classmethod
39
+ def valid_public_origin(cls, value: str | None) -> str | None:
40
+ if value is not None:
41
+ try:
42
+ validate_origin(value, https_only=True)
43
+ except ChatError:
44
+ raise ValueError("public_origin must be a canonical HTTPS origin") from None
45
+ return value
46
+
47
+
48
+ def load_config(path: str) -> Config:
49
+ raw = Path(path).read_bytes()
50
+ if len(raw) > MAX_CONFIG_BYTES:
51
+ raise ValueError("CONFIG_INVALID")
52
+ try:
53
+ return Config.model_validate(json.loads(raw.decode("utf-8")))
54
+ except (ValueError, UnicodeError, ValidationError):
55
+ raise ValueError("CONFIG_INVALID") from None