-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_server.py
More file actions
1510 lines (1282 loc) · 55.2 KB
/
Copy pathmcp_server.py
File metadata and controls
1510 lines (1282 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
korg_mcp_server.py — korg MCP server v1
Exposes the korg ledger to any MCP-compatible agent (Claude Code, Codex,
korgex, etc.) over stdio transport using JSON-RPC 2.0.
Transport: stdio (newline-delimited JSON, one message per line).
Protocol: Model Context Protocol (MCP) 2024-11-05.
Auth: v1 local-only — trusts source_agent as provided (spec §7.7).
Tools exposed:
korg_append_event — write one AgentToolCall event, get back seq_id
korg_query_events — read events by tool_name or triggered_by
Design rules:
- No cleverness. Garbage in → append to ledger → seq_id out.
- No normalization across agents.
- No auto-detection of event types.
- source_agent is trusted as-is. Lying hurts the liar.
- If korg is unreachable, return a clear error — don't silently swallow.
- All errors are JSON-RPC error responses, never tracebacks to stdout.
Usage (in Claude Code's MCP config):
{
"mcpServers": {
"korg": {
"command": "python3",
"args": ["/path/to/korg_mcp_server.py"],
"env": {
"KORG_URL": "http://localhost:8080"
}
}
}
}
Or run directly for testing:
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}' | python3 korg_mcp_server.py
"""
from __future__ import annotations
import base64
import json
import logging
import os
import sys
import threading
import time as _time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable
from urllib.parse import parse_qs, urlparse
import requests
# ---------------------------------------------------------------------------
# Logging — stderr only. stdout is the MCP transport.
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.DEBUG if os.environ.get("KORG_MCP_DEBUG") else logging.INFO,
format="[korg-mcp] %(levelname)s %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
KORG_URL = os.environ.get("KORG_URL", "http://localhost:8080").rstrip("/")
HTTP_TIMEOUT = float(os.environ.get("KORG_MCP_TIMEOUT", "5"))
MCP_PROTOCOL_VERSION = "2024-11-05"
SERVER_NAME = "korg"
SERVER_VERSION = "1.0.0"
# v1 ledger ID — only valid value per agent_event_spec.md §8.1.
# Multi-tenancy in v2+ will expand the valid set.
LEDGER_ID = "local"
# Filesystem path to the spec document. Used by korg://local/schema/spec.
# Resolves relative to this file's location so the server works from any cwd.
SPEC_PATH = Path(__file__).parent / "agent_event_spec.md"
# Maximum blob size served through MCP JSON-RPC (§8.4.2).
# Larger blobs return blob_too_large with the HTTP URL as the escape hatch.
BLOB_MAX_BYTES = 10 * 1024 * 1024 # 10MB
# Background poller interval (§8.5.1). Subscriptions fire within ~POLL_INTERVAL seconds.
POLL_INTERVAL: float = float(os.environ.get("KORG_MCP_POLL_INTERVAL", "1.0"))
# ---------------------------------------------------------------------------
# Tool schemas
# ---------------------------------------------------------------------------
TOOLS = [
{
"name": "korg_append_event",
"description": (
"Append one AgentToolCall event to the korg audit ledger. "
"Returns the assigned seq_id. Use seq_id as triggered_by on your next call "
"to chain events into a causal tree.\n\n"
"Causal chain rules (agent_event_spec.md §2):\n"
"- Start each session with tool_name='user_prompt' and no triggered_by.\n"
"- Set triggered_by to the seq_id of the event that caused this call.\n"
"- Parallel tool calls from the same LLM response share triggered_by (siblings).\n"
"- Retry events point at the failure event, not the original call.\n"
"- Internal tool composition is not ledgered — only decision-boundary calls.\n"
"- For LLM rounds, see §2a: round-N's llm_inference chains to round-(N-1)'s\n"
" llm_inference, NOT to the most recent tool call.\n\n"
"Actor identity convention (§1.1):\n"
" agent:<name>@<version> (e.g. agent:claude-code@1.0)\n"
" human:<identifier> (e.g. human:dusk)\n"
" korg:<component> (korg internal events only)\n"
" mcp:<server-name> (MCP server clients)"
),
"annotations": {
"title": "Append AgentToolCall event",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": False,
"openWorldHint": False,
},
"inputSchema": {
"type": "object",
"properties": {
"source_agent": {
"type": "string",
"description": "Agent identity. Use agent:<name>@<version> convention.",
},
"tool_name": {
"type": "string",
"description": (
"Name of the tool or event type. "
"Use 'user_prompt' for session roots, 'llm_inference' for LLM calls, "
"or the actual tool name (Edit, Read, Bash, etc.)."
),
},
"args": {
"type": "object",
"description": (
"Tool arguments as a JSON object. "
"Values >1KB should be content-referenced — see payload_refs."
),
},
"result": {
"type": "object",
"description": (
"Tool result as a JSON object. "
"Values >1KB should be content-referenced — see payload_refs."
),
},
"success": {
"type": "boolean",
"description": "Whether the tool call succeeded.",
},
"duration_ms": {
"type": "integer",
"description": "Wall-clock duration of the tool call in milliseconds.",
},
"triggered_by": {
"type": "integer",
"description": (
"seq_id of the parent event in the causal chain. "
"Omit for root events (user_prompt). Required for all other events."
),
},
"payload_refs": {
"type": "array",
"description": (
"Content-addressed references for large payloads (>1KB). "
"Each ref: {sha256, size_bytes, label}. "
"Blobs must be written to .korg/blobs/<sha256[:2]>/<sha256> before "
"calling append (blob-first atomicity — spec §3)."
),
"items": {
"type": "object",
"properties": {
"sha256": {"type": "string"},
"size_bytes": {"type": "integer"},
"label": {"type": "string"},
},
"required": ["sha256", "size_bytes"],
},
"default": [],
},
},
"required": ["source_agent", "tool_name", "args", "result", "success", "duration_ms"],
},
},
{
"name": "korg_query_events",
"description": (
"Query recent AgentToolCall events from the korg ledger. "
"Use to find a session's root seq_id, walk the causal chain, "
"or check what events exist before appending.\n\n"
"Filters are applied client-side over the last N events. "
"For large ledgers this is O(n) — avoid in tight loops "
"(agent_event_spec.md §6.6)."
),
"annotations": {
"title": "Query Korg ledger events",
"readOnlyHint": True,
"openWorldHint": False,
},
"inputSchema": {
"type": "object",
"properties": {
"limit": {
"type": "integer",
"description": "Maximum number of events to return (default 20, max 200).",
"default": 20,
},
"tool_name": {
"type": "string",
"description": "Filter: only return events with this tool_name.",
},
"triggered_by": {
"type": "integer",
"description": "Filter: only return events triggered by this seq_id (forward walk).",
},
"source_agent": {
"type": "string",
"description": "Filter: only return events from this source_agent.",
},
},
"required": [],
},
},
]
# ---------------------------------------------------------------------------
# korg HTTP client
# ---------------------------------------------------------------------------
def _korg_append(body: dict) -> dict:
"""POST to korg's ingestion endpoint. Returns the response JSON."""
resp = requests.post(
f"{KORG_URL}/api/agent/tool-call",
json=body,
timeout=HTTP_TIMEOUT,
)
resp.raise_for_status()
return resp.json()
def _korg_journal(limit: int) -> list[dict]:
"""Fetch the last `limit` events from korg's journal endpoint."""
resp = requests.get(
f"{KORG_URL}/api/journal",
timeout=HTTP_TIMEOUT,
)
resp.raise_for_status()
events: list[dict] = []
for line in resp.text.splitlines():
line = line.strip()
if not line or line.startswith("//"):
continue
try:
events.append(json.loads(line))
except json.JSONDecodeError:
continue
# journal returns oldest-first; return the last `limit` in reverse (newest first)
return list(reversed(events[-limit:]))
def _korg_blob(sha256: str) -> tuple[bytes, str]:
"""Fetch a blob from korg's blob endpoint. Returns (raw_bytes, content_type)."""
resp = requests.get(
f"{KORG_URL}/api/blob/{sha256}",
timeout=HTTP_TIMEOUT,
)
resp.raise_for_status()
content_type = resp.headers.get("content-type", "application/octet-stream")
return resp.content, content_type
# ---------------------------------------------------------------------------
# Session walk helper
# ---------------------------------------------------------------------------
def _session_event_ids(all_events: list[dict], root_seq: int) -> set[int]:
"""BFS from root_seq through triggered_by edges. Returns all seq_ids in the session."""
children: dict[int, list[int]] = {}
for e in all_events:
tb = e.get("metadata", {}).get("triggered_by")
if tb is not None:
children.setdefault(tb, []).append(e["seq_id"])
# Check visited *before* enqueuing so duplicate children entries (which
# can appear when the same event is observed in multiple polls during a
# cascading root re-assignment) don't balloon the queue. The post-dequeue
# check is kept as defense in depth.
visited: set[int] = {root_seq}
queue = [root_seq]
while queue:
seq = queue.pop(0)
for child in children.get(seq, []):
if child in visited:
continue
visited.add(child)
queue.append(child)
return visited
# ---------------------------------------------------------------------------
# Tool handlers
# ---------------------------------------------------------------------------
def handle_korg_append_event(arguments: dict) -> dict:
"""
Translate an MCP tool call into a POST /api/agent/tool-call request.
No cleverness: forward args exactly as received, return seq_id.
Validation is done by the JSON schema above; anything that gets here
should have the required fields.
"""
# Build the HTTP body. Only include triggered_by if it was provided.
body: dict[str, Any] = {
"source_agent": arguments["source_agent"],
"tool_name": arguments["tool_name"],
"args": arguments.get("args", {}),
"result": arguments.get("result", {}),
"payload_refs": arguments.get("payload_refs", []),
"success": arguments["success"],
"duration_ms": arguments["duration_ms"],
}
if "triggered_by" in arguments and arguments["triggered_by"] is not None:
body["triggered_by"] = int(arguments["triggered_by"])
logger.debug("append_event: tool=%s triggered_by=%s", body["tool_name"], body.get("triggered_by"))
result = _korg_append(body)
seq_id: int = result["seq_id"]
logger.info("appended seq=%d tool=%s agent=%s", seq_id, body["tool_name"], body["source_agent"])
return {
"seq_id": seq_id,
"message": (
f"Event recorded at seq={seq_id}. "
f"Use triggered_by={seq_id} on your next event to continue the causal chain."
),
}
def handle_korg_query_events(arguments: dict) -> dict:
"""
Fetch and filter events from the korg journal.
Filters are applied client-side. This is intentionally simple for v1.
"""
raw_limit = arguments.get("limit", 20)
limit = max(1, min(int(raw_limit), 200))
# Fetch from korg (returns up to 100 by default; we cap at 200 and filter client-side)
fetch_limit = min(limit * 4, 200) # over-fetch to allow for filtering
all_events = _korg_journal(fetch_limit)
# Filter to AgentToolCall events only
agent_events = [
e for e in all_events
if e.get("event", {}).get("event_type") == "AgentToolCall"
]
# Apply filters
tool_name_filter = arguments.get("tool_name")
triggered_by_filter = arguments.get("triggered_by")
source_agent_filter = arguments.get("source_agent")
filtered = agent_events
if tool_name_filter:
filtered = [e for e in filtered if e.get("event", {}).get("tool_name") == tool_name_filter]
if triggered_by_filter is not None:
tb = int(triggered_by_filter)
filtered = [e for e in filtered if e.get("metadata", {}).get("triggered_by") == tb]
if source_agent_filter:
filtered = [e for e in filtered if e.get("event", {}).get("source_agent") == source_agent_filter]
# Trim to requested limit
filtered = filtered[:limit]
# Return a compact, readable summary
summary = []
for e in filtered:
ev = e.get("event", {})
md = e.get("metadata", {})
summary.append({
"seq_id": e.get("seq_id"),
"tool_name": ev.get("tool_name"),
"source_agent": ev.get("source_agent"),
"success": ev.get("success"),
"duration_ms": ev.get("duration_ms"),
"triggered_by": md.get("triggered_by"),
"schema_version": e.get("schema_version"),
})
return {
"count": len(summary),
"events": summary,
"note": (
"Showing newest-first. Use triggered_by=<seq_id> to find all children "
"of an event (forward walk). Use tool_name='user_prompt' to find session roots."
),
}
# ---------------------------------------------------------------------------
# MCP protocol dispatch
# ---------------------------------------------------------------------------
def handle_initialize(params: dict, req_id: Any) -> dict:
client_version = params.get("protocolVersion", "?")
logger.info("initialize from %s (protocol %s)", params.get("clientInfo", {}).get("name", "?"), client_version)
return {
"jsonrpc": "2.0",
"id": req_id,
"result": {
"protocolVersion": MCP_PROTOCOL_VERSION,
"capabilities": {
"tools": {},
# Resources capability per agent_event_spec.md §8.
# subscribe: true as of Phase D — poller thread + subscription registry.
# listChanged: false because the fixed resource list is static in v1.
"resources": {"subscribe": True, "listChanged": False},
},
"serverInfo": {
"name": SERVER_NAME,
"version": SERVER_VERSION,
},
},
}
def handle_tools_list(req_id: Any) -> dict:
return {
"jsonrpc": "2.0",
"id": req_id,
"result": {"tools": TOOLS},
}
def handle_tools_call(params: dict, req_id: Any) -> dict:
name = params.get("name")
arguments = params.get("arguments", {})
logger.debug("tools/call: %s", name)
try:
if name == "korg_append_event":
data = handle_korg_append_event(arguments)
elif name == "korg_query_events":
data = handle_korg_query_events(arguments)
else:
return _error(req_id, -32601, f"Unknown tool: {name!r}")
return {
"jsonrpc": "2.0",
"id": req_id,
"result": {
"content": [
{
"type": "text",
"text": json.dumps(data, indent=2),
}
],
"isError": False,
},
}
except requests.ConnectionError:
return _tool_error(req_id, f"korg is not reachable at {KORG_URL}. Start korg with: cargo run -- --web")
except requests.HTTPError as e:
return _tool_error(req_id, f"korg returned HTTP {e.response.status_code}: {e.response.text[:200]}")
except Exception as e:
logger.exception("Unexpected error in %s", name)
return _tool_error(req_id, f"Internal error: {type(e).__name__}: {e}")
def handle_ping(req_id: Any) -> dict:
return {"jsonrpc": "2.0", "id": req_id, "result": {}}
def _error(req_id: Any, code: int, message: str) -> dict:
return {
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": code, "message": message},
}
def _tool_error(req_id: Any, message: str) -> dict:
"""Return a tool-level error (isError=True in the result content)."""
return {
"jsonrpc": "2.0",
"id": req_id,
"result": {
"content": [{"type": "text", "text": f"Error: {message}"}],
"isError": True,
},
}
# ---------------------------------------------------------------------------
# Resources — agent_event_spec.md §8
# ---------------------------------------------------------------------------
#
# Phase A: 5 fixed resources, no subscriptions, no session/event/agent/blob
# templates (those land in Phase B/C). Resource URIs follow §8.1:
# korg://{ledger}/<path>
# where {ledger} == LEDGER_ID ("local") in v1.
# Fixed resources advertised via resources/list. URIs are concrete, no
# template substitution required. (Templates land in Phase B.)
RESOURCES = [
{
"uri": f"korg://{LEDGER_ID}/ledger/recent",
"name": "Recent ledger events",
"description": "Most recent N events across all agents, newest-first. Paginated via ?cursor=<seq_id>&limit=<n>.",
"mimeType": "application/json",
},
{
"uri": f"korg://{LEDGER_ID}/ledger/heads",
"name": "Session roots (active and recent)",
"description": "List of root user_prompt seq_ids — entry points for session reads.",
"mimeType": "application/json",
},
{
"uri": f"korg://{LEDGER_ID}/schema/event",
"name": "AgentToolCall JSON Schema",
"description": "Machine-readable schema for one ledger event (agent_event_spec.md §1).",
"mimeType": "application/json",
},
{
"uri": f"korg://{LEDGER_ID}/schema/spec",
"name": "Agent event spec",
"description": "Full agent_event_spec.md — schema, causal rules, rewind, dogfood checklist.",
"mimeType": "text/markdown",
},
{
"uri": f"korg://{LEDGER_ID}/stats/integrity",
"name": "Ledger integrity snapshot",
"description": "Quick health check: event counts, actor convention violations, schema_version distribution. Run korg_dogfood.py for the full §6 checklist.",
"mimeType": "application/json",
},
]
# Resource templates for URI patterns where the path includes parameters.
# Phase B: session, event, agent. Phase C adds the blob template.
# The list is the published advertisement of which URI shapes Korg supports.
RESOURCE_TEMPLATES: list[dict] = [
{
"uriTemplate": f"korg://{LEDGER_ID}/session/{{root_seq}}",
"name": "Session metadata",
"description": (
"Bounded metadata for one session: root event, event count, agents, "
"first/last seq_id. §8.3."
),
"mimeType": "application/json",
},
{
"uriTemplate": f"korg://{LEDGER_ID}/session/{{root_seq}}/summary",
"name": "Session structural skeleton",
"description": (
"Paginated lightweight summary of session events, oldest→newest (§8.3). "
"?cursor=<seq_id>&limit=<n>&source_agent=<id>."
),
"mimeType": "application/json",
},
{
"uriTemplate": f"korg://{LEDGER_ID}/session/{{root_seq}}/events",
"name": "Session full events",
"description": (
"Paginated full event bodies for a session, oldest→newest (§8.3). "
"?cursor=<seq_id>&limit=<n>&source_agent=<id>."
),
"mimeType": "application/json",
},
{
"uriTemplate": f"korg://{LEDGER_ID}/event/{{seq_id}}",
"name": "Single event",
"description": "Full journal envelope for one event by seq_id.",
"mimeType": "application/json",
},
{
"uriTemplate": f"korg://{LEDGER_ID}/agent/{{source_agent}}/recent",
"name": "Agent recent events",
"description": (
"Recent events from one agent across all sessions, newest→oldest (§8.3.1). "
"?cursor=<seq_id>&limit=<n>."
),
"mimeType": "application/json",
},
{
"uriTemplate": f"korg://{LEDGER_ID}/blob/{{sha256}}",
"name": "Content-addressed blob",
"description": (
"One blob by sha256. Max 10MB over JSON-RPC; larger blobs return "
"blob_too_large error with http_url escape hatch (§8.4)."
),
"mimeType": "application/octet-stream",
},
]
# The AgentToolCall JSON Schema, served at korg://local/schema/event.
# Derived from agent_event_spec.md §1.
EVENT_JSON_SCHEMA = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": f"korg://{LEDGER_ID}/schema/event",
"title": "AgentToolCall",
"description": "One event in the korg ledger. See agent_event_spec.md §1.",
"type": "object",
"properties": {
"source_agent": {
"type": "string",
"description": "Actor identity per §1.1: agent:<name>@<ver>, human:<id>, korg:<comp>, mcp:<server>.",
"pattern": "^(agent|human|korg|mcp):",
},
"tool_name": {
"type": "string",
"description": "Verbatim tool name; no normalization across agents.",
},
"args": {
"type": "object",
"description": "Tool arguments. Values >1KB content-referenced per §7.3.",
},
"result": {
"type": "object",
"description": "Tool output. Values >1KB content-referenced per §7.3.",
},
"success": {"type": "boolean"},
"duration_ms": {"type": "integer", "minimum": 0},
"triggered_by": {
"type": ["integer", "null"],
"description": "seq_id of parent event; null for roots (§2).",
},
"payload_refs": {
"type": "array",
"items": {
"type": "object",
"properties": {
"sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
"size_bytes": {"type": "integer", "minimum": 0},
"label": {"type": "string"},
},
"required": ["sha256", "size_bytes"],
},
},
},
"required": ["source_agent", "tool_name", "args", "result", "success", "duration_ms"],
"additionalProperties": False,
}
# ---------------------------------------------------------------------------
# URI parser — §8.1
# ---------------------------------------------------------------------------
class _UriError(Exception):
"""Raised for malformed or unsupported korg:// URIs.
reason — stable string reason code placed in the JSON-RPC error data dict.
message — human-readable description for the error message field.
code — JSON-RPC error code (default -32602 invalid params; -32603 for
transport-limit errors like blob_too_large).
extra — additional key/value pairs merged into the error data dict
(e.g. sha256, size_bytes, http_url for blob_too_large).
"""
def __init__(
self,
reason: str,
message: str,
code: int = -32602,
extra: dict | None = None,
) -> None:
super().__init__(message)
self.reason = reason
self.message = message
self.code = code
self.extra: dict = extra or {}
def _parse_korg_uri(uri: str) -> tuple[list[str], dict[str, str]]:
"""Parse a korg:// URI. Returns (path_parts, query_dict).
Raises _UriError on:
- Wrong scheme (not korg://)
- Missing or unsupported ledger ID (v1: only "local")
- Empty path
"""
parsed = urlparse(uri)
if parsed.scheme != "korg":
raise _UriError("bad_scheme", f"URI scheme must be korg://, got {parsed.scheme!r}")
if not parsed.netloc:
raise _UriError("missing_ledger", "URI must include a ledger ID: korg://{ledger}/...")
if parsed.netloc != LEDGER_ID:
raise _UriError(
"unknown_ledger",
f"Unknown ledger {parsed.netloc!r}; v1 supports only {LEDGER_ID!r} (§8.1).",
)
path = parsed.path.strip("/")
if not path:
raise _UriError("empty_path", "URI must include a resource path after the ledger ID")
parts = path.split("/")
query = {k: v[0] for k, v in parse_qs(parsed.query).items() if v}
return parts, query
# ---------------------------------------------------------------------------
# Fixed resource handlers
# ---------------------------------------------------------------------------
def _resource_ledger_recent(query: dict[str, str]) -> dict:
"""korg://local/ledger/recent — paginated recent events."""
limit = max(1, min(int(query.get("limit", "50")), 500))
cursor = query.get("cursor")
events = _korg_journal(limit * 4) # over-fetch for cursor filtering
# Cursor: return events with seq_id < cursor (i.e., older than cursor).
if cursor is not None:
cursor_seq = int(cursor)
events = [e for e in events if e.get("seq_id", 0) < cursor_seq]
# Already newest-first from _korg_journal; trim to limit
events = events[:limit]
next_cursor = events[-1]["seq_id"] if len(events) == limit else None
return {
"events": events,
"next_cursor": next_cursor,
"has_more": next_cursor is not None,
}
def _resource_ledger_heads(query: dict[str, str]) -> dict:
"""korg://local/ledger/heads — list of root user_prompt seq_ids."""
limit = max(1, min(int(query.get("limit", "50")), 200))
# Over-fetch enough to find root events
raw = _korg_journal(500)
roots = [
{
"seq_id": e["seq_id"],
"source_agent": e.get("event", {}).get("source_agent"),
"prompt_preview": str(
e.get("event", {}).get("args", {}).get("prompt", "")
)[:120],
}
for e in raw
if e.get("event", {}).get("event_type") == "AgentToolCall"
and e.get("event", {}).get("tool_name") == "user_prompt"
and e.get("metadata", {}).get("triggered_by") is None
][:limit]
return {"heads": roots, "count": len(roots)}
def _resource_schema_event(_query: dict[str, str]) -> dict:
"""korg://local/schema/event — the AgentToolCall JSON Schema."""
return EVENT_JSON_SCHEMA
def _resource_schema_spec(_query: dict[str, str]) -> str:
"""korg://local/schema/spec — the spec document. Returns text, not JSON."""
if not SPEC_PATH.exists():
raise _UriError(
"spec_not_found",
f"Spec file missing at {SPEC_PATH}. Ensure agent_event_spec.md is co-located with mcp_server.py.",
)
return SPEC_PATH.read_text(encoding="utf-8")
def _resource_stats_integrity(_query: dict[str, str]) -> dict:
"""korg://local/stats/integrity — quick health snapshot.
Phase A: counts + actor convention check. Full §6 dogfood checks are
heavy (causal chain walks, blob existence) and live in korg_dogfood.py.
"""
raw = _korg_journal(500) # bounded — don't scan the whole world
agent_events = [
e for e in raw
if e.get("event", {}).get("event_type") == "AgentToolCall"
]
# §1.1 actor convention prefixes
valid_prefixes = ("agent:", "human:", "korg:", "mcp:")
actor_counts: dict[str, int] = {}
violations: list[str] = []
schema_versions: dict[str, int] = {}
roots = 0
for e in agent_events:
ev = e.get("event", {})
src = ev.get("source_agent", "")
actor_counts[src] = actor_counts.get(src, 0) + 1
if not any(src.startswith(p) for p in valid_prefixes) and src not in violations:
violations.append(src)
sv = e.get("schema_version", "MISSING")
schema_versions[sv] = schema_versions.get(sv, 0) + 1
if (
ev.get("tool_name") == "user_prompt"
and e.get("metadata", {}).get("triggered_by") is None
):
roots += 1
return {
"sample_size": len(agent_events),
"sample_note": "Stats computed over the last 500 ledger events.",
"total_agents_seen": len(actor_counts),
"source_agent_counts": actor_counts,
"schema_version_distribution": schema_versions,
"root_sessions_in_sample": roots,
"actor_convention_violations": violations,
"actor_convention_ok": len(violations) == 0,
"note": "For the full §6 dogfood checklist, run scripts/korg_dogfood.py.",
}
# ---------------------------------------------------------------------------
# Phase B resource handlers — variable-segment URIs (§8.3)
# ---------------------------------------------------------------------------
def _resource_session_meta(root_seq: int, query: dict[str, str]) -> dict:
"""korg://local/session/{root_seq} — bounded session metadata."""
all_events = _korg_journal(10000)
by_seq = {e["seq_id"]: e for e in all_events}
if root_seq not in by_seq:
raise _UriError("not_found", f"No event at seq_id={root_seq}")
session_seqs = _session_event_ids(all_events, root_seq)
session_events = sorted(
[by_seq[s] for s in session_seqs if s in by_seq],
key=lambda e: e["seq_id"],
)
agents = sorted({e.get("event", {}).get("source_agent") for e in session_events} - {None})
last_event = session_events[-1] if session_events else by_seq[root_seq]
return {
"root_seq": root_seq,
"root_event": by_seq[root_seq],
"total_events": len(session_events),
"agent_count": len(agents),
"agents": agents,
"first_seq": session_events[0]["seq_id"] if session_events else root_seq,
"last_seq": last_event["seq_id"],
"last_event_at": last_event.get("metadata", {}).get("recorded_at"),
"last_event_seq": last_event["seq_id"],
"schema_version": by_seq[root_seq].get("schema_version", "1.0"),
}
def _resource_session_summary(root_seq: int, query: dict[str, str]) -> dict:
"""korg://local/session/{root_seq}/summary — paginated skeleton, oldest→newest."""
limit = max(1, min(int(query.get("limit", "100")), 1000))
cursor = int(query.get("cursor", "0"))
source_agent_filter = query.get("source_agent")
all_events = _korg_journal(10000)
by_seq = {e["seq_id"]: e for e in all_events}
if root_seq not in by_seq:
raise _UriError("not_found", f"No event at seq_id={root_seq}")
session_seqs = _session_event_ids(all_events, root_seq)
session_events = sorted(
[by_seq[s] for s in session_seqs if s in by_seq],
key=lambda e: e["seq_id"],
)
# head surface: cursor=N → return events with seq_id > N (oldest→newest)
if cursor > 0:
session_events = [e for e in session_events if e["seq_id"] > cursor]
if source_agent_filter:
session_events = [
e for e in session_events
if e.get("event", {}).get("source_agent") == source_agent_filter
]
page = session_events[:limit]
has_more = len(session_events) > limit
next_cursor = page[-1]["seq_id"] if has_more else None
skeleton = [
{
"seq_id": e["seq_id"],
"source_agent": e.get("event", {}).get("source_agent"),
"tool_name": e.get("event", {}).get("tool_name"),
"triggered_by": e.get("metadata", {}).get("triggered_by"),
"success": e.get("event", {}).get("success"),
"duration_ms": e.get("event", {}).get("duration_ms"),
"has_payload_refs": bool(e.get("metadata", {}).get("payload_refs")),
}
for e in page
]
return {"events": skeleton, "next_cursor": next_cursor, "has_more": has_more}
def _resource_session_events(root_seq: int, query: dict[str, str]) -> dict:
"""korg://local/session/{root_seq}/events — paginated full bodies, oldest→newest."""
limit = max(1, min(int(query.get("limit", "50")), 500))
cursor = int(query.get("cursor", "0"))
source_agent_filter = query.get("source_agent")
all_events = _korg_journal(10000)
by_seq = {e["seq_id"]: e for e in all_events}
if root_seq not in by_seq:
raise _UriError("not_found", f"No event at seq_id={root_seq}")
session_seqs = _session_event_ids(all_events, root_seq)
session_events = sorted(
[by_seq[s] for s in session_seqs if s in by_seq],
key=lambda e: e["seq_id"],
)
if cursor > 0:
session_events = [e for e in session_events if e["seq_id"] > cursor]
if source_agent_filter:
session_events = [
e for e in session_events
if e.get("event", {}).get("source_agent") == source_agent_filter
]
page = session_events[:limit]
has_more = len(session_events) > limit
next_cursor = page[-1]["seq_id"] if has_more else None
return {"events": page, "next_cursor": next_cursor, "has_more": has_more}
def _resource_event_read(seq_id: int, query: dict[str, str]) -> dict:
"""korg://local/event/{seq_id} — single event full body."""
all_events = _korg_journal(10000)
by_seq = {e["seq_id"]: e for e in all_events}
if seq_id not in by_seq:
raise _UriError("not_found", f"No event at seq_id={seq_id}")
return by_seq[seq_id]
def _resource_agent_recent(source_agent: str, query: dict[str, str]) -> dict:
"""korg://local/agent/{source_agent}/recent — newest→oldest, cursor paginated."""
limit = max(1, min(int(query.get("limit", "50")), 500))
cursor = query.get("cursor")
all_events = _korg_journal(limit * 8) # over-fetch before agent filter
filtered = [
e for e in all_events
if e.get("event", {}).get("source_agent") == source_agent
]
# tail surface: cursor=N → return events with seq_id < N (newest→oldest)
if cursor is not None:
cursor_seq = int(cursor)
filtered = [e for e in filtered if e.get("seq_id", 0) < cursor_seq]
page = filtered[:limit]
has_more = len(filtered) > limit
next_cursor = page[-1]["seq_id"] if has_more else None
return {
"source_agent": source_agent,
"events": page,
"next_cursor": next_cursor,
"has_more": has_more,
}
# ---------------------------------------------------------------------------
# Phase D — Subscription engine (§8.5)
# ---------------------------------------------------------------------------
@dataclass
class Subscription:
uri: str
predicate: Callable[[dict], bool]
# Registry: uri → list[Subscription]. Guarded by _subscription_lock.
_subscriptions: dict[str, list[Subscription]] = {}
_subscription_lock = threading.Lock()
# seq_id → root_seq_id lookup (§8.5.2). Built at startup + extended per tick.
# Guarded by _seq_to_root_lock.
_seq_to_root: dict[int, int] = {}