-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_server.py
More file actions
1999 lines (1795 loc) · 77.1 KB
/
Copy pathmcp_server.py
File metadata and controls
1999 lines (1795 loc) · 77.1 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
"""
conductor MCP server — Live intelligence layer
================================================
Serves the tool ontology, routing, governance state, and session
awareness as MCP tools that Claude Code can query in real-time.
Tools:
conductor_route_to — Find routes between tool clusters
conductor_capability — Find tools by capability
conductor_wip_status — Current governance/WIP state
conductor_session_phase — What phase am I in, what's available?
conductor_suggest — Natural language → tool recommendation
Usage:
python3 mcp_server.py # Start MCP server on stdio
# Or register in ~/.claude/mcp.json:
# { "mcpServers": { "conductor": { "command": "python3", "args": ["mcp_server.py"] } } }
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
from typing import Any
MCP_IMPORT_ERROR: ImportError | None = None
try:
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import TextContent, Tool
except ImportError as exc:
MCP_IMPORT_ERROR = exc
Server = None # type: ignore[assignment]
stdio_server = None # type: ignore[assignment]
class TextContent: # type: ignore[no-redef]
def __init__(self, *, type: str, text: str):
self.type = type
self.text = text
class Tool: # type: ignore[no-redef]
def __init__(self, **kwargs: Any):
self.kwargs = kwargs
BASE = Path(__file__).parent
sys.path.insert(0, str(BASE))
from router import Ontology, RoutingEngine
from conductor.router_extensions import install as _install_router_extensions
_install_router_extensions()
from conductor.constants import (
ONTOLOGY_PATH,
PHASE_INSTRUMENTS,
PHASE_ROLES,
ROLE_ACTIONS,
ROUTING_PATH,
SESSION_STATE_FILE,
WORKFLOW_DSL_PATH,
get_phase_clusters,
)
from conductor.contracts import assert_contract
from conductor.executor import WorkflowExecutor
from conductor.governance import GovernanceRuntime
from conductor.handoff import (
cluster_health_metrics,
edge_health_report,
get_trace_bundle,
validate_handoff_payload,
)
from conductor.patchbay import Patchbay
from conductor.session import SessionEngine
def _ensure_mcp_available() -> None:
if MCP_IMPORT_ERROR is not None:
raise RuntimeError("MCP SDK required: pip install mcp")
# ---------------------------------------------------------------------------
# Lazy globals
# ---------------------------------------------------------------------------
_ontology: Ontology | None = None
_engine: RoutingEngine | None = None
def get_ontology() -> Ontology:
global _ontology
if _ontology is None:
_ontology = Ontology(ONTOLOGY_PATH)
return _ontology
def get_engine() -> RoutingEngine:
global _engine
if _engine is None:
_engine = RoutingEngine(ROUTING_PATH, get_ontology())
return _engine
def get_session() -> dict | None:
if SESSION_STATE_FILE.exists():
try:
return json.loads(SESSION_STATE_FILE.read_text())
except (json.JSONDecodeError, OSError):
return None
return None
def _encode_mcp_payload(payload: dict[str, Any]) -> str:
"""Validate and encode standard MCP JSON responses."""
try:
assert_contract("mcp_tool_response", payload)
return json.dumps(payload, indent=2)
except Exception as exc:
fallback: dict[str, Any] = {
"error": f"mcp_tool_response contract validation failed: {exc}",
}
if isinstance(payload, dict) and "error" in payload:
fallback["upstream_error"] = str(payload.get("error"))
return json.dumps(fallback, indent=2)
# ---------------------------------------------------------------------------
# Tool implementations
# ---------------------------------------------------------------------------
def _route_payload(route: Any) -> dict[str, Any]:
return {
"id": route.id,
"from": route.from_cluster,
"to": route.to_cluster,
"data_flow": route.data_flow,
"protocol": route.protocol,
"automatable": route.automatable,
"description": route.description,
}
def _path_legs(engine: RoutingEngine, path: list[str]) -> list[dict[str, Any]]:
legs: list[dict[str, Any]] = []
for source, target in zip(path, path[1:]):
matches = engine.find_routes(source, target)
if matches:
preferred = matches[0]
legs.append(_route_payload(preferred))
else:
legs.append(
{
"id": "",
"from": source,
"to": target,
"data_flow": "",
"protocol": "",
"automatable": False,
"description": "No direct route metadata available for this hop.",
}
)
return legs
def _fallback_sequence(engine: RoutingEngine, path: list[str]) -> list[dict[str, Any]]:
sequence: list[dict[str, Any]] = []
for cluster_id in path:
alternatives = engine.get_alternatives(cluster_id)
if alternatives:
sequence.append(
{
"cluster": cluster_id,
"tools_ranked": alternatives.tools_ranked,
}
)
return sequence
def route_to(from_cluster: str, to_cluster: str) -> str:
engine = get_engine()
ontology = get_ontology()
# Inject real-time health telemetry
try:
health = cluster_health_metrics(window=200)
engine.inject_health_metrics(health)
except Exception:
health = {}
source = ontology.clusters.get(from_cluster)
target = ontology.clusters.get(to_cluster)
if source is None or target is None:
return _encode_mcp_payload({"error": f"Unknown cluster(s): {from_cluster}, {to_cluster}"})
routes = engine.find_routes(from_cluster, to_cluster)
direct_routes = [_route_payload(route) for route in routes]
cluster_paths = engine.find_cluster_paths(from_cluster, to_cluster)
domain_paths = engine.find_path(source.domain, target.domain)
if not direct_routes and not cluster_paths and not domain_paths:
return _encode_mcp_payload({"error": f"No route found: {from_cluster} -> {to_cluster}"})
path_rows = []
for path in cluster_paths:
# Calculate path health
path_health = round(sum(engine.get_cluster_health(c) for c in path) / len(path), 4)
path_rows.append({
"clusters": path,
"hops": max(0, len(path) - 1),
"legs": _path_legs(engine, path),
"reliability_score": path_health,
})
fallback_sequences = _fallback_sequence(engine, cluster_paths[0]) if cluster_paths else []
return _encode_mcp_payload(
{
"from_cluster": from_cluster,
"to_cluster": to_cluster,
"direct_routes": direct_routes,
"multi_hop_paths": [path for path in cluster_paths if len(path) > 2] or domain_paths,
"pathfinding": {
"cluster_paths": path_rows,
"domain_paths": domain_paths,
},
"fallback_sequences": fallback_sequences,
"telemetry": {
"health_metrics_applied": bool(health),
"source_health": engine.get_cluster_health(from_cluster),
"target_health": engine.get_cluster_health(to_cluster),
}
}
)
def capability(cap: str) -> str:
ontology = get_ontology()
engine = get_engine()
clusters = ontology.by_capability(cap.upper())
if not clusters:
return _encode_mcp_payload({"error": f"No clusters with capability: {cap}"})
result = [{"id": c.id, "label": c.label, "domain": c.domain,
"tools_count": len(c.tools), "protocols": c.protocols}
for c in clusters]
preferred = engine.capability_tools(cap.upper())
return _encode_mcp_payload({"clusters": result, "routing_priority": preferred})
def wip_status() -> str:
try:
gov = GovernanceRuntime()
counts = {}
for organ_key, organ_data in gov.registry.get("organs", {}).items():
repos = organ_data.get("repositories", [])
status_counts = {}
for r in repos:
s = r.get("promotion_status", "UNKNOWN")
status_counts[s] = status_counts.get(s, 0) + 1
counts[organ_key] = status_counts
return _encode_mcp_payload({"wip_by_organ": counts})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def session_phase() -> str:
try:
session = get_session()
score = WorkflowExecutor(WORKFLOW_DSL_PATH).get_briefing()
if not session:
return _encode_mcp_payload({"active": False, "message": "No active session", "workflow_score": score})
phase = session.get("current_phase", "UNKNOWN")
return _encode_mcp_payload({
"active": True,
"session_id": session.get("session_id"),
"organ": session.get("organ"),
"repo": session.get("repo"),
"scope": session.get("scope"),
"current_phase": phase,
"ai_role": PHASE_ROLES.get(phase, "Unknown"),
"instrument": PHASE_INSTRUMENTS.get(phase, "Unknown"),
"allowed_actions": ROLE_ACTIONS.get(phase, {}).get("allowed", []),
"forbidden_actions": ROLE_ACTIONS.get(phase, {}).get("forbidden", []),
"active_clusters": get_phase_clusters().get(phase, []),
"warnings": session.get("warnings", []),
"workflow_score": score,
})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def orchestra_briefing() -> str:
try:
session = get_session()
score = WorkflowExecutor(WORKFLOW_DSL_PATH).get_briefing()
if not session:
return _encode_mcp_payload(
{
"active": False,
"message": "No active session",
"workflow_score": score,
}
)
phase = session.get("current_phase", "UNKNOWN")
return _encode_mcp_payload(
{
"active": True,
"session_id": session.get("session_id"),
"organ": session.get("organ"),
"repo": session.get("repo"),
"scope": session.get("scope"),
"phase": phase,
"role": PHASE_ROLES.get(phase, "Unknown"),
"instrument": PHASE_INSTRUMENTS.get(phase, "Unknown"),
"allowed_actions": ROLE_ACTIONS.get(phase, {}).get("allowed", []),
"forbidden_actions": ROLE_ACTIONS.get(phase, {}).get("forbidden", []),
"active_clusters": get_phase_clusters().get(phase, []),
"workflow_score": score,
}
)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def patch(organ: str | None = None) -> str:
"""Full system briefing from the patchbay."""
try:
ontology = get_ontology()
engine = SessionEngine(ontology)
pb = Patchbay(ontology=ontology, engine=engine)
organ_filter = None
if organ:
from conductor.constants import resolve_organ_key
organ_filter = resolve_organ_key(organ)
data = pb.briefing(organ_filter=organ_filter)
return _encode_mcp_payload(data)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def suggest(task_description: str) -> str:
ontology = get_ontology()
engine = get_engine()
task_lower = task_description.lower()
# Keyword → capability mapping
keyword_caps = {
"search": "SEARCH", "find": "SEARCH", "look up": "SEARCH",
"read": "READ", "view": "READ", "show": "READ",
"write": "WRITE", "create": "WRITE", "add": "WRITE",
"edit": "EDIT", "modify": "EDIT", "change": "EDIT", "update": "EDIT",
"run": "EXECUTE", "execute": "EXECUTE", "test": "TEST",
"deploy": "DEPLOY", "ship": "DEPLOY", "publish": "DEPLOY",
"analyze": "ANALYZE", "review": "ANALYZE", "audit": "ANALYZE",
"generate": "GENERATE", "build": "GENERATE",
"monitor": "MONITOR", "watch": "MONITOR",
"diagram": "VISUALIZE", "visualize": "VISUALIZE", "chart": "VISUALIZE",
}
matched_caps = []
for keyword, cap in keyword_caps.items():
if keyword in task_lower:
matched_caps.append(cap)
if not matched_caps:
matched_caps = ["SEARCH"] # Default
suggestions = []
seen = set()
for cap in matched_caps:
preferred = engine.capability_tools(cap)
for cid in preferred[:3]:
if cid not in seen:
seen.add(cid)
cluster = ontology.clusters.get(cid)
if cluster:
suggestions.append({
"cluster": cid,
"label": cluster.label,
"capability": cap,
"tools_count": len(cluster.tools),
})
# Check session context
session = get_session()
phase_note = None
if session:
phase = session.get("current_phase", "UNKNOWN")
phase_clusters = set(get_phase_clusters().get(phase, []))
for s in suggestions:
s["in_current_phase"] = s["cluster"] in phase_clusters
phase_note = f"Current phase: {phase}. Prefer tools from active clusters."
return _encode_mcp_payload({
"task": task_description,
"suggestions": suggestions,
"phase_context": phase_note,
})
def edge_health(window: int = 200) -> str:
try:
payload = edge_health_report(window=window)
return _encode_mcp_payload(payload)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def trace_get(trace_id: str) -> str:
try:
payload = get_trace_bundle(trace_id)
if not any(payload.get(key) for key in ("handoff", "trace", "route_decision")):
return _encode_mcp_payload({"error": f"Trace not found: {trace_id}"})
return _encode_mcp_payload(payload)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def handoff_validate(payload: dict[str, Any]) -> str:
try:
result = validate_handoff_payload(payload)
return _encode_mcp_payload(result)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def compose_mission(goal: str, from_cluster: str, to_cluster: str) -> str:
"""Synthesize a JIT workflow mission (Score) from a routing path."""
engine = get_engine()
ontology = get_ontology()
if not engine or not ontology:
return _encode_mcp_payload({"error": "Routing engine not initialized"})
try:
# Inject health for shadow tracing
health = cluster_health_metrics(window=200)
engine.inject_health_metrics(health)
except Exception:
pass
from conductor.compiler import WorkflowCompiler
compiler = WorkflowCompiler(engine, ontology)
try:
active = SessionEngine(ontology)._load_session()
session_id = active.session_id if active else "adhoc-compose-mcp"
except Exception:
session_id = "adhoc-compose-mcp"
try:
state = compiler.compile_mission(
goal=goal,
start_cluster=from_cluster,
end_cluster=to_cluster,
session_id=session_id
)
return _encode_mcp_payload({
"mission_id": state.workflow_name,
"session_id": state.session_id,
"hardened": state.metadata.get("hardened", False),
"shadow_trace_health": state.metadata.get("shadow_trace_health", 1.0),
"description": compiler.generate_description(state),
"next_action": "Call conductor_workflow_step to execute the first step."
})
except Exception as e:
return _encode_mcp_payload({"error": f"Failed to compile mission: {str(e)}"})
def oracle_consult(context: dict[str, Any] | None = None, include_narrative: bool = False) -> str:
"""Consult the Oracle for contextual advisories."""
try:
from conductor.oracle import Oracle, OracleContext
oracle = Oracle()
ctx = OracleContext.from_dict(context) if context else OracleContext(trigger="manual")
advisories = oracle.consult(ctx, include_narrative=include_narrative)
return _encode_mcp_payload({
"count": len(advisories),
"advisories": [a.to_dict() for a in advisories],
})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def oracle_gate(trigger: str, target: str = "", repo: str = "") -> str:
"""Decision-gate advisory for phase transitions and promotions."""
try:
from conductor.oracle import Oracle, OracleContext
oracle = Oracle()
session = get_session()
ctx = OracleContext(
trigger=trigger,
session_id=session.get("session_id", "") if session else "",
current_phase=session.get("current_phase", "") if session else "",
target_phase=target,
promotion_repo=repo,
organ=session.get("organ", "") if session else "",
)
advisories = oracle.consult(ctx, gate_mode=True)
gate_advisories = [a for a in advisories if a.gate_action]
return _encode_mcp_payload({
"trigger": trigger,
"target": target,
"gate_advisories": [a.to_dict() for a in gate_advisories],
"all_clear": len(gate_advisories) == 0,
})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def oracle_wisdom() -> str:
"""Rich narrative wisdom from the Oracle."""
try:
from conductor.oracle import Oracle, OracleContext
oracle = Oracle()
session = get_session()
ctx = OracleContext(
trigger="manual",
session_id=session.get("session_id", "") if session else "",
current_phase=session.get("current_phase", "") if session else "",
organ=session.get("organ", "") if session else "",
)
advisories = oracle.consult(ctx, max_advisories=3, include_narrative=True)
narrative_advs = [a for a in advisories if a.narrative]
return _encode_mcp_payload({
"count": len(narrative_advs),
"wisdom": [
{"narrative": a.narrative, "category": a.category, "detector": a.detector}
for a in narrative_advs
],
})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def oracle_profile() -> str:
"""Get the Oracle's behavioral profile for the current user."""
try:
from conductor.oracle import Oracle
oracle = Oracle()
profile = oracle.build_profile()
return _encode_mcp_payload(profile.to_dict())
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def oracle_detectors() -> str:
"""Get the full detector manifest with effectiveness scores."""
try:
from conductor.oracle import Oracle
oracle = Oracle()
manifest = oracle.get_detector_manifest()
return _encode_mcp_payload({
"count": len(manifest),
"detectors": manifest,
})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def oracle_trends() -> str:
"""Get trend summary: ship rate, duration over recent windows."""
try:
from conductor.oracle import Oracle
oracle = Oracle()
summary = oracle.get_trend_summary()
return _encode_mcp_payload(summary)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def oracle_diagnose() -> str:
"""Run Oracle self-diagnostics."""
try:
from conductor.oracle import Oracle
oracle = Oracle()
diag = oracle.diagnose()
return _encode_mcp_payload(diag)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def oracle_calibrate(detector: str, action: str = "reset") -> str:
"""Calibrate a detector's effectiveness score."""
try:
from conductor.oracle import Oracle
oracle = Oracle()
result = oracle.calibrate_detector(detector, action)
return _encode_mcp_payload(result)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
# ---------------------------------------------------------------------------
# Guardian Angel MCP handlers
# ---------------------------------------------------------------------------
def guardian_counsel(context: dict[str, Any] | None = None) -> str:
"""Guardian Angel enhanced consult with wisdom enrichment."""
try:
from conductor.guardian import GuardianAngel
from conductor.oracle import OracleContext
guardian = GuardianAngel()
ctx = OracleContext.from_dict(context) if context else None
advisories = guardian.counsel(ctx)
return _encode_mcp_payload({
"count": len(advisories),
"advisories": [a.to_dict() for a in advisories],
})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def guardian_whisper(action: str, context: dict[str, Any] | None = None) -> str:
"""Lightweight ambient guidance for a specific action."""
try:
from conductor.guardian import GuardianAngel
from conductor.oracle import OracleContext
guardian = GuardianAngel()
ctx = OracleContext.from_dict(context) if context else None
adv = guardian.whisper(action, ctx)
return _encode_mcp_payload(adv.to_dict() if adv else {"whisper": None})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def guardian_teach(topic: str) -> str:
"""On-demand pedagogical lookup of a principle."""
try:
from conductor.guardian import GuardianAngel
guardian = GuardianAngel()
result = guardian.teach(topic)
return _encode_mcp_payload(result)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def guardian_landscape(decision: str, context: dict[str, Any] | None = None) -> str:
"""Risk-reward landscape mapping for a decision."""
try:
from conductor.guardian import GuardianAngel
from conductor.oracle import OracleContext
guardian = GuardianAngel()
ctx = OracleContext.from_dict(context) if context else None
result = guardian.landscape(decision, ctx)
return _encode_mcp_payload(result)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def guardian_mastery() -> str:
"""Growth and mastery report."""
try:
from conductor.guardian import GuardianAngel
guardian = GuardianAngel()
report = guardian.growth_report()
return _encode_mcp_payload(report)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def mark_internalized(wisdom_id: str, evidence: str = "") -> str:
"""Mark a wisdom principle as internalized."""
try:
from conductor.oracle import Oracle
oracle = Oracle()
oracle._mark_internalized(wisdom_id, evidence)
report = oracle.get_mastery_report()
return _encode_mcp_payload(report)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def guardian_corpus(search: str | None = None) -> str:
"""Browse or search the Guardian wisdom corpus."""
try:
from conductor.guardian import GuardianAngel
guardian = GuardianAngel()
result = guardian.corpus_search(search)
return _encode_mcp_payload(result)
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def preflight(agent: str = "unknown", cwd: str | None = None) -> str:
"""Run preflight: infer context, build runway briefing, auto-start session."""
try:
from conductor.preflight import run_preflight
result = run_preflight(
agent=agent or "unknown",
cwd=cwd or str(Path.cwd()),
auto_start=True,
json_output=True,
)
return _encode_mcp_payload(result.to_dict())
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def active_sessions_list() -> str:
"""List all currently active sessions across all agents."""
try:
engine = SessionEngine()
sessions = engine.active_sessions()
return _encode_mcp_payload({
"count": len(sessions),
"sessions": [s.to_dict() for s in sessions],
})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def session_start(organ: str, repo: str, scope: str, agent: str = "unknown") -> str:
"""Start a new Conductor session with FRAME→SHAPE→BUILD→PROVE lifecycle."""
try:
ontology = get_ontology()
engine = SessionEngine(ontology)
session = engine.start(organ, repo, scope, git_branch=False, agent=agent)
phase = session.current_phase
return _encode_mcp_payload({
"session_id": session.session_id,
"organ": session.organ,
"repo": session.repo,
"scope": session.scope,
"current_phase": phase,
"ai_role": PHASE_ROLES.get(phase, "Unknown"),
"active_clusters": get_phase_clusters().get(phase, []),
"agent": session.agent,
"message": f"Session started in {phase} phase. Explore before building.",
})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def session_transition(target_phase: str, agent: str = "") -> str:
"""Transition to a new phase. Hard gate: FRAME→SHAPE→BUILD→PROVE only."""
try:
ontology = get_ontology()
engine = SessionEngine(ontology)
engine.phase(target_phase, agent=agent)
# Read back the session state after transition
session = engine._load_session()
if not session:
return _encode_mcp_payload({"error": "Session closed after transition"})
phase = session.current_phase
return _encode_mcp_payload({
"session_id": session.session_id,
"current_phase": phase,
"ai_role": PHASE_ROLES.get(phase, "Unknown"),
"active_clusters": get_phase_clusters().get(phase, []),
"duration_minutes": session.duration_minutes,
"message": f"Transitioned to {phase}.",
})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def gate_check() -> str:
"""Check for blocking advisories before major actions."""
try:
from conductor.guardian import GuardianAngel
from conductor.oracle import OracleContext
guardian = GuardianAngel()
session = get_session()
ctx = OracleContext(
trigger="gate_check",
session_id=session.get("session_id", "") if session else "",
current_phase=session.get("current_phase", "") if session else "",
organ=session.get("organ", "") if session else "",
)
advisories = guardian.counsel(ctx, gate_mode=True)
gate_advisories = [a for a in advisories if a.gate_action]
return _encode_mcp_payload({
"has_session": session is not None,
"current_phase": session.get("current_phase", "") if session else "NONE",
"gate_advisories": [a.to_dict() for a in gate_advisories],
"all_clear": len(gate_advisories) == 0,
"advisory_count": len(advisories),
"top_advisories": [a.to_dict() for a in advisories[:3]],
})
except Exception as e:
return _encode_mcp_payload({"error": str(e)})
def workflow_status() -> str:
from conductor.executor import WorkflowExecutor
from conductor.constants import WORKFLOW_DSL_PATH
executor = WorkflowExecutor(WORKFLOW_DSL_PATH)
briefing = executor.get_briefing()
return _encode_mcp_payload(briefing)
def workflow_step(tool_output: Any = None, checkpoint_action: str | None = None) -> str:
from conductor.executor import WorkflowExecutor
from conductor.constants import WORKFLOW_DSL_PATH
executor = WorkflowExecutor(WORKFLOW_DSL_PATH)
briefing = executor.get_briefing()
if not briefing.get("active"):
return _encode_mcp_payload({"error": "No active workflow. Start one using conductor_compose_mission or conductor CLI."})
current_step = briefing.get("current_step")
if not current_step:
return _encode_mcp_payload({"error": "Workflow is active but has no current step to execute.", "status": briefing.get("status")})
try:
result = executor.run_step(
step_name=current_step,
tool_output=tool_output,
checkpoint_action=checkpoint_action
)
return _encode_mcp_payload(result)
except Exception as e:
return _encode_mcp_payload({"error": f"Failed to run step '{current_step}': {str(e)}"})
# ---------------------------------------------------------------------------
# Directive ingestion
# ---------------------------------------------------------------------------
def ingest(content: str, source_agent: str, topic: str, tags: list[str] | None = None) -> str:
"""Ingest raw content from a directive, fan out to all targets.
Produces 4 artifacts:
1. Reference file in praxis-perpetua/research/
2. Alchemia intake artifact in alchemia-ingestvm/intake/ai-transcripts/
3. SOP stub in organvm-engine/.sops/ (if not already present)
4. Engine guidance in response JSON
"""
import hashlib
import os
import re
from datetime import datetime, timezone
workspace = Path(os.environ.get("ORGANVM_WORKSPACE_DIR", Path.home() / "Workspace"))
now = datetime.now(timezone.utc)
date_str = now.strftime("%Y-%m-%d")
slug = re.sub(r"[^a-z0-9]+", "-", topic.lower()).strip("-")
content_hash = hashlib.sha256(content.encode()).hexdigest()[:16]
tag_list = tags or []
artifacts: dict[str, Any] = {}
# 1. Reference file -> praxis-perpetua/research/
research_dir = workspace / "meta-organvm" / "praxis-perpetua" / "research"
research_dir.mkdir(parents=True, exist_ok=True)
ref_path = research_dir / f"{date_str}-{slug}.md"
# Avoid clobbering existing files
counter = 2
while ref_path.exists():
ref_path = research_dir / f"{date_str}-{slug}-v{counter}.md"
counter += 1
ref_content = (
f"---\n"
f"source: {source_agent}\n"
f"date: {date_str}\n"
f"topic: {topic}\n"
f"tags: {json.dumps(tag_list)}\n"
f"content_hash: {content_hash}\n"
f"ingested_via: conductor_ingest\n"
f"---\n"
f"# {topic.replace('-', ' ').title()}\n\n"
f"{content}\n"
)
ref_path.write_text(ref_content, encoding="utf-8")
artifacts["reference"] = str(ref_path)
# 2. Alchemia intake artifact
intake_dir = workspace / "alchemia-ingestvm" / "intake" / "ai-transcripts"
intake_dir.mkdir(parents=True, exist_ok=True)
intake_path = intake_dir / f"{date_str}-{slug}.json"
counter = 2
while intake_path.exists():
intake_path = intake_dir / f"{date_str}-{slug}-v{counter}.json"
counter += 1
intake_data = {
"schema_version": "1.0",
"source": source_agent,
"source_type": "ai_transcript",
"topic": topic,
"tags": tag_list,
"content_preview": content[:500],
"content_hash": content_hash,
"reference_path": str(ref_path),
"status": "intake",
"ingested_at": now.isoformat(),
}
intake_path.write_text(json.dumps(intake_data, indent=2), encoding="utf-8")
artifacts["intake"] = str(intake_path)
# 3. SOP stub (only if not already present)
sops_dir = workspace / "meta-organvm" / "organvm-engine" / ".sops"
sops_dir.mkdir(parents=True, exist_ok=True)
sop_path = sops_dir / f"{slug}.md"
if sop_path.exists():
artifacts["sop"] = str(sop_path)
artifacts["sop_status"] = "already_exists"
else:
title = topic.replace("-", " ").title()
sop_content = (
f"---\n"
f"sop: true\n"
f"name: {slug}\n"
f"scope: system\n"
f"phase: any\n"
f"triggers: []\n"
f"complements: []\n"
f"overrides: null\n"
f"---\n"
f"# {title}\n\n"
f"## Purpose\n\n"
f"Generated from {source_agent} transcript on {date_str}.\n"
f"Topic: {topic}\n\n"
f"## Key Findings\n\n"
f"<!-- Extract key findings from the ingested content -->\n\n"
f"## Procedure\n\n"
f"<!-- Define operational procedures based on findings -->\n\n"
f"## Verification\n\n"
f"<!-- How to confirm procedures are followed -->\n"
)
sop_path.write_text(sop_content, encoding="utf-8")
artifacts["sop"] = str(sop_path)
artifacts["sop_status"] = "created"
# 4. Engine guidance
artifacts["guidance"] = {
"next_steps": [
f"Review reference at {artifacts['reference']}",
f"Run 'alchemia intake' to process {artifacts['intake']}",
f"Run 'organvm sop discover --json | grep {slug}' to verify SOP",
"Update SOP with extracted findings from the transcript",
],
"prompting_module": "organvm_engine.prompting.standards" if "prompting" in slug else None,
}
return _encode_mcp_payload({
"status": "ingested",
"topic": topic,
"source_agent": source_agent,
"content_hash": content_hash,
"artifacts": artifacts,
})
# ---------------------------------------------------------------------------
# Fleet orchestration tools
# ---------------------------------------------------------------------------
def fleet_status() -> str:
from conductor.fleet import FleetRegistry
from conductor.fleet_usage import FleetUsageTracker
from datetime import date
registry = FleetRegistry()
tracker = FleetUsageTracker()
today = date.today()
daily = tracker.daily_snapshot(today)
agents = []
for agent in registry.active_agents():
usage = daily.get(agent.name, {})
agents.append({
"name": agent.name,
"display_name": agent.display_name,
"provider": agent.provider,
"tier": agent.subscription.tier,
"strengths": list(agent.capabilities.strengths),
"phase_affinity": agent.phase_affinity,
"today_sessions": usage.get("sessions", 0),
"today_tokens": usage.get("total_tokens", 0),
"today_cost": usage.get("total_cost_usd", 0.0),
})
return _encode_mcp_payload({
"date": today.isoformat(),
"active_agents": len(agents),
"agents": agents,
})
def fleet_recommend(phase: str, task_tags: list | None = None, sensitivity: dict | None = None, context_size: int = 0) -> str:
from conductor.fleet_router import FleetRouter
router = FleetRouter()
scores = router.recommend(
phase=phase,
task_tags=task_tags or [],
sensitivity_required=sensitivity or {},
context_size=context_size,
)
recommendations = []
for s in scores: