"""MCP Tool Registry

Maps 56 MCP tools to cubesquare shell implementations.
Each tool wraps a shell class and exposes its commands.

53 shell-backed tools + 3 C=0 Fernandez agent tools.

Architecture:
    Every tool is flipped into CST space at init → CSTRecord.
    No for-loops in hot paths. Tools are accessed by:
    - Direct name lookup: O(1) dict
    - Basin index: O(1) spatial grouping
    - UIF coupling: agents resolve tools by coordinate proximity
    - Pre-cached MCP list: built once, returned as-is

    The tool registry IS a spatial structure, not a Python dict.
"""

from typing import Dict, Any, List, Optional, Callable
from functools import reduce
import json

# Import all shells
from ..shells.cst import CSTShell
from ..shells.performance import PerformanceShell
from ..shells.primitives import PrimitivesShell
from ..shells.i_logic import ILogicShell
from ..shells.circular import CircularShell
from ..shells.predict import PredictShell
from ..shells.beehive import BeehiveShell
from ..shells.semantic import SemanticShell
from ..shells.language import LanguageShell
from ..shells.time import TimeShell
from ..shells.distance import DistanceShell
from ..shells.mass import MassShell
from ..shells.gravity import GravityShell
from ..shells.world import WorldShell
from ..shells.ecosystem import EcosystemShell
from ..shells.data_analysis import DataAnalysisShell
from ..shells.learning import LearningShell
from ..shells.basin import BasinShell
from ..shells.light import LightShell
from ..shells.meaning import MeaningShell
from ..shells.manifold import ManifoldShell
from ..shells.sql import SQLShell
from ..shells.gene import GeneShell
from ..shells.unified import UnifiedShell
from ..shells.agent import AgentShell
from ..shells.twelve import TwelveShell
from ..shells.telemetry import TelemetryShell
from ..shells.srl import SRLShell
from ..shells.content import ContentShell
from ..shells.phi import PhiShell
from ..shells.chat import ChatShell
from ..shells.ogawa import OgawaShell
from ..shells.vision import VisionShell
from ..shells.copilot import CopilotShell
from ..shells.flip import DataFlipShell
from ..shells.gizmo import GizmoShell
from ..shells.exploration import ExplorationShell
from ..shells.spatial_memory import SpatialMemoryShell
from ..shells.thread import ThreadShell
from ..shells.cypher import CypherShell

# --- NEW: shells previously missing from MCP ---
from ..shells.thinking import ThinkingShell
from ..shells.thinking_autonomous import ThinkingAutonomousShell
from ..shells.validation import ValidationShell
from ..shells.adversarial import AdversarialShell
from ..shells.persistence import PersistenceShell
from ..shells.benchmark import BenchmarkShell
from ..shells.ticket import TicketShell
from ..shells.epicycle import EpicycleShell
from ..shells.basin_dict import BasinDictShell
from ..shells.condition import ConditionEncoder
from ..shells.fml import FMLEncoder
from ..shells.swarm_shell import SwarmShell
from ..shells.memory_shell import MemoryShell
from ..shells.training_shell import TrainingShell
from ..shells.self import SelfShell, BrainShell


# Tool definitions with schemas
TOOL_DEFINITIONS: Dict[str, Dict[str, Any]] = {
    "cst_shell": {
        "description": "CST 9-layer operations: geometric, semantic, spatial, functional, probabilistic, emotional, frequency, electromagnetic, membrane. Core coordinate system for deterministic semantic memory.",
        "shell_class": CSTShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Command to execute",
                    "enum": ["status", "benchmark", "run", "list", "validate", "fernandez_status"]
                },
                "args": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Command arguments (e.g., layer ID for 'run')"
                }
            },
            "required": ["command"]
        }
    },
    "c_performance_shell": {
        "description": "C backend performance validation. O(1) Morton encoding at 83M ops/sec, SRL formula t=sqrt(d), identity verification P-P=0 and P/P=1.",
        "shell_class": PerformanceShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["test", "benchmark", "srl", "cst", "status", "morton"]
                },
                "iterations": {
                    "type": "integer",
                    "description": "Benchmark iterations (default: 10000)"
                }
            },
            "required": ["command"]
        }
    },
    "primitives_shell": {
        "description": "Verified O(1) primitives: Morton encoding/decoding, Basin computation (mod 131), SRL formula (t=sqrt(d)), I-Logic algebra. All operations constant-time.",
        "shell_class": PrimitivesShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "show", "use", "compose", "validate", "why", "table"]
                },
                "primitive": {
                    "type": "string",
                    "description": "Primitive name for 'show', 'use', 'why' commands",
                    "enum": ["morton", "basin", "srl", "i_logic"]
                },
                "args": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Arguments for the primitive operation"
                }
            },
            "required": ["command"]
        }
    },
    "i_logic_shell": {
        "description": "I-Logic 5-state algebra: DIRECT(1), INVERSE(-1), SPIRAL(+i), ANTI_SPIRAL(-i), ABSORBED(0). Predict routing outcomes before execution. Algebraically closed group.",
        "shell_class": ILogicShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "multiply", "compose", "cycle", "table", "test", "predict", "inverse"]
                },
                "state1": {
                    "type": "string",
                    "description": "First I-Logic state",
                    "enum": ["DIRECT", "INVERSE", "SPIRAL", "ANTI_SPIRAL", "ABSORBED"]
                },
                "state2": {
                    "type": "string",
                    "description": "Second I-Logic state",
                    "enum": ["DIRECT", "INVERSE", "SPIRAL", "ANTI_SPIRAL", "ABSORBED"]
                },
                "states": {
                    "type": "string",
                    "description": "Comma-separated states for 'compose' command"
                }
            },
            "required": ["command"]
        }
    },
    "circular_shell": {
        "description": "Loop detection and resolution. SRL distance computation, K11 levels [-11 to +11], intrinsic loop detection. Prevents agent infinite loops.",
        "shell_class": CircularShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "detect", "resolve", "validate", "srl_path", "ilogic", "k11", "intrinsic", "sphere", "wave_particle"]
                },
                "path": {
                    "type": "string",
                    "description": "Comma-separated states for loop detection"
                },
                "depth": {
                    "type": "integer",
                    "description": "Maximum depth for loop detection"
                }
            },
            "required": ["command"]
        }
    },
    "predict_shell": {
        "description": "Route prediction: know outcomes before execution. Predicts I-Logic state transitions and optimal routing paths. No execution needed for prediction.",
        "shell_class": PredictShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "route", "resolve", "cycle", "optimize", "target", "examples", "validate", "demo"]
                },
                "path": {
                    "type": "string",
                    "description": "Route specification (e.g., 'agent:SPIRAL,processor:INVERSE')"
                },
                "target": {
                    "type": "string",
                    "description": "Target state for optimization",
                    "enum": ["DIRECT", "INVERSE", "SPIRAL", "ANTI_SPIRAL", "ABSORBED"]
                }
            },
            "required": ["command"]
        }
    },
    "beehive_shell": {
        "description": "Beehive index: 24,056 tokens across 131 basins and 9 layers. O(1) lookup by hex ID, Morton code, or basin. Queen + worker architecture.",
        "shell_class": BeehiveShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "get", "basin", "layer", "query", "stats"]
                },
                "hex_id": {
                    "type": "string",
                    "description": "8-character hex token ID"
                },
                "basin_id": {
                    "type": "integer",
                    "description": "Basin number (0-130)"
                },
                "layer": {
                    "type": "string",
                    "description": "Layer name (L1-L9)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum results to return"
                }
            },
            "required": ["command"]
        }
    },
    "semantic_chain_shell": {
        "description": "Semantic chain decomposition. Parse natural language into geometric operations. Route queries to appropriate layers and basins.",
        "shell_class": SemanticShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "parse", "execute", "route", "basin", "encode"]
                },
                "text": {
                    "type": "string",
                    "description": "Text to parse or route"
                },
                "query": {
                    "type": "string",
                    "description": "Query for routing"
                }
            },
            "required": ["command"]
        }
    },
    "language_shell": {
        "description": "Language processing layer. Vocabulary matrix, semantic communication, accept/reject classification.",
        "shell_class": LanguageShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "demo", "vocabulary", "matrix", "accept", "reject", "query"]
                },
                "text": {
                    "type": "string",
                    "description": "Text input for processing"
                }
            },
            "required": ["command"]
        }
    },
    "time_shell": {
        "description": "Temporal operations with SRL formula t=sqrt(d). Time dilation, trajectory computation, synchronization. Maps iterations to time units.",
        "shell_class": TimeShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "get", "trajectory", "dilate", "sync"]
                },
                "depth": {
                    "type": "integer",
                    "description": "Iteration depth for SRL computation"
                },
                "factor": {
                    "type": "number",
                    "description": "Dilation factor"
                }
            },
            "required": ["command"]
        }
    },
    "distance_shell": {
        "description": "Spatial O(1) distance computation. d=t^2 inverse of SRL. Radius queries, nearest neighbor, path computation in Morton space.",
        "shell_class": DistanceShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "compute", "radius", "nearest", "path"]
                },
                "x": {"type": "integer", "description": "X coordinate"},
                "y": {"type": "integer", "description": "Y coordinate"},
                "z": {"type": "integer", "description": "Z coordinate"},
                "radius": {"type": "integer", "description": "Search radius"}
            },
            "required": ["command"]
        }
    },
    "mass_shell": {
        "description": "K11 mass coupling in Fernandez space. Position mass (K11 level) and content mass (energy × transmission × K11). Momentum, center of mass, content-defined physics.",
        "shell_class": MassShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "get", "coupling", "momentum", "center_of_mass", "content_mass"]
                },
                "hex_id": {"type": "string", "description": "Token hex ID"},
                "hex1": {"type": "string", "description": "First token for coupling"},
                "hex2": {"type": "string", "description": "Second token for coupling"},
                "tokens": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Token hex IDs for center_of_mass"
                },
                "energy": {"type": "number", "description": "FML L5 information entropy (0.0-1.0)"},
                "transmission_ratio": {"type": "number", "description": "Membrane T ratio (0.0-1.0)"},
                "reflection_ratio": {"type": "number", "description": "Membrane R ratio (0.0-1.0)"},
                "basin": {"type": "integer", "description": "Basin ID (0-130)"},
                "i_logic_state": {"type": "string", "description": "I-Logic state name"}
            },
            "required": ["command"]
        }
    },
    "gravity_shell": {
        "description": "Gravitational field computation. Celestial prime validation, orbital mechanics, escape velocity, Lagrange points. Uses K11 for field strength.",
        "shell_class": GravityShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "validate", "validate_all", "field", "orbit", "escape", "lagrange"]
                },
                "body1": {"type": "string", "description": "First body hex ID"},
                "body2": {"type": "string", "description": "Second body hex ID"}
            },
            "required": ["command"]
        }
    },
    "world_shell": {
        "description": "Complete physical universe with content mass, inverse-square time, square-cube law. Body interactions, projections, alignments, mass topology.",
        "shell_class": WorldShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "body", "interaction", "cosmos", "layer_physics", "project", "align", "observation", "content_body", "inverse_square_time", "square_cube", "mass_topology"]
                },
                "body_id": {"type": "string", "description": "Body hex ID"},
                "body2": {"type": "string", "description": "Second body for interaction"},
                "scale": {"type": "string", "description": "Target scale"},
                "body": {"type": "string", "description": "Celestial body name"},
                "energy": {"type": "number", "description": "FML energy (0.0-1.0)"},
                "transmission_ratio": {"type": "number", "description": "Membrane T ratio"},
                "mass": {"type": "number", "description": "Content mass value"},
                "distance": {"type": "number", "description": "Distance for time computation"},
                "radius": {"type": "number", "description": "Radius for square-cube law"}
            },
            "required": ["command"]
        }
    },
    "ecosystem_shell": {
        "description": "Ecosystem connectivity analysis. 67,250 token relationships, bridge detection, neighbor analysis. Maps the full semantic network.",
        "shell_class": EcosystemShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "report", "validate", "bridges", "neighbors"]
                },
                "token": {"type": "string", "description": "Token hex ID"},
                "depth": {"type": "integer", "description": "Analysis depth"}
            },
            "required": ["command"]
        }
    },
    "data_analysis_shell": {
        "description": "Bidirectional pattern detection. Analyzes 67,250 relationships for patterns, ideas, bridges. Full beehive connectivity analysis.",
        "shell_class": DataAnalysisShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "full", "beehive", "patterns", "ideas", "relationships", "bridges", "connectivity", "validate"]
                },
                "limit": {"type": "integer", "description": "Maximum results"}
            },
            "required": ["command"]
        }
    },
    "learning_shell": {
        "description": "Layer semantic integration. SRL to I-Logic mapping, layer detection from content. Training data for semantic routing.",
        "shell_class": LearningShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "load_layers", "show_layer", "all_layers", "srl_map", "detect"]
                },
                "layer": {"type": "string", "description": "Layer name (L1-L9)"},
                "content": {"type": "string", "description": "Content to analyze"}
            },
            "required": ["command"]
        }
    },
    "basin_system": {
        "description": "131-basin Fernandez system. Basin listing, querying, adjacency, anomaly detection, layer mapping. Core clustering mechanism.",
        "shell_class": BasinShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["list", "query", "info", "map", "adjacency", "anomaly", "layer", "status", "validate", "heal"]
                },
                "basin_id": {"type": "integer", "description": "Basin number (0-130)"},
                "query": {"type": "string", "description": "Search query"}
            },
            "required": ["command"]
        }
    },
    "light_basin_shell": {
        "description": "Light Unit <-> Basin <-> Layer mapping. OCTA core frequency calibration. Maps 131 light units to basins with I-Logic states.",
        "shell_class": LightShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "map", "lookup", "basin", "lu", "c", "hex", "layer", "ilogic", "agent", "calibrate", "export"]
                },
                "light_unit": {"type": "integer", "description": "Light unit (0-130)"},
                "basin_id": {"type": "integer", "description": "Basin number"}
            },
            "required": ["command"]
        }
    },
    "meaning_shell": {
        "description": "Self-reference operations. P-P=0 (origin verification), P/P=1 (identity verification). Algebraic identity preservation across all operations.",
        "shell_class": MeaningShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["self", "basin", "layer", "ilogic", "relate", "communicate", "context", "reflect", "origin", "identity", "k11", "navigate", "status"]
                },
                "token": {"type": "string", "description": "Token hex ID"},
                "other": {"type": "string", "description": "Other token for relation"}
            },
            "required": ["command"]
        }
    },
    "manifold_shell": {
        "description": "K5 manifold operations with mass-constrained agents. Centroid at 41.7 Hz, mass topology visible to L9. Square, generate, mass_topology on the 12-layer manifold.",
        "shell_class": ManifoldShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "agents", "stats", "square", "generate", "query", "earth", "loop", "flip", "vector", "mass_topology"]
                },
                "need": {"type": "string", "description": "Need description for agent generation"},
                "vector": {
                    "type": "array",
                    "items": {"type": "number"},
                    "description": "Vector for manifold operations"
                }
            },
            "required": ["command"]
        }
    },
    "sql_shell": {
        "description": "Database operations with CST awareness. 885x speedup over traditional queries. Basin-aware search, pattern detection, metrics.",
        "shell_class": SQLShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "benchmark", "search", "patterns", "basins", "metrics"]
                },
                "query": {"type": "string", "description": "Search query"},
                "basin_id": {"type": "integer", "description": "Basin filter"}
            },
            "required": ["command"]
        }
    },
    "gene_shell": {
        "description": "Gene model operations. 48x48x48 genetic matrix for agent breeding and generation. Genetic algorithms in CST space.",
        "shell_class": GeneShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["generate", "breed", "status", "validate_all"]
                },
                "parent1": {"type": "string", "description": "First parent token"},
                "parent2": {"type": "string", "description": "Second parent token"}
            },
            "required": ["command"]
        }
    },
    "unified_field_tools": {
        "description": "UIF operations: EXTRACT, GENERATE, HEAL, PATCH. Unified field manipulation at L9 membrane boundary. Information flow control.",
        "shell_class": UnifiedShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["extract", "heal", "patch", "status", "generate"]
                },
                "token": {"type": "string", "description": "Token to operate on"},
                "field": {"type": "string", "description": "Field specification"}
            },
            "required": ["command"]
        }
    },
    "new_agent_shell": {
        "description": "Agent onboarding and contextualization. Provides agents with CST context, layer routing, and system status.",
        "shell_class": AgentShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["onboard", "context", "status", "list_cst", "guide"]
                },
                "agent_id": {"type": "string", "description": "Agent identifier"}
            },
            "required": ["command"]
        }
    },
    "twelve_shell": {
        "description": "12-layer architecture (L1-L9 internal + L10-L12 external). External layers: Agent Identity, Communication, Unified Field.",
        "shell_class": TwelveShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "layers", "external", "internal", "manifold"]
                },
                "layer": {"type": "string", "description": "Layer to query (L1-L12)"}
            },
            "required": ["command"]
        }
    },
    "telemetry_shell": {
        "description": "Semantic telemetry bridge. Interprets, routes, predicts based on semantic content. Council voting, anomaly detection.",
        "shell_class": TelemetryShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "interpret", "route", "predict", "steps", "anomalies", "council", "infer", "semantic"]
                },
                "content": {"type": "string", "description": "Content to process"}
            },
            "required": ["command"]
        }
    },
    "srl_shell": {
        "description": "Self-Referential Loop operations. t=sqrt(d) formula, iteration collapse, depth computation. Core SRL primitives.",
        "shell_class": SRLShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "compute", "validate", "batch", "inverse"]
                },
                "depth": {"type": "integer", "description": "Iteration depth"},
                "time": {"type": "number", "description": "Time value for inverse"}
            },
            "required": ["command"]
        }
    },
    "content_shell": {
        "description": "Hex identity tokenization and documentation index. Encode topics to 8-char hex IDs, decode hex to components, query the beehive index by content or basin.",
        "shell_class": ContentShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "encode", "decode", "query", "basin", "hex", "handshake"]
                },
                "topic": {"type": "string", "description": "Topic/content to encode"},
                "hex_id": {"type": "string", "description": "8-char hex ID to decode"},
                "basin_id": {"type": "integer", "description": "Basin ID (0-130) to query"}
            },
            "required": ["command"]
        }
    },
    "phi_integration": {
        "description": "LLM integration with CST structure. Connect Ollama (phi4/phi4-mini) to 9 CST layers with semantic processing and observer council voting.",
        "shell_class": PhiShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "handshake", "process", "council", "layers"]
                },
                "content": {"type": "string", "description": "Content to process through layers"},
                "layer": {"type": "integer", "description": "Specific layer (1-9) to process through"}
            },
            "required": ["command"]
        }
    },
    "cst_chat": {
        "description": "Bidirectional chat interface with hex tracking. Routes messages through semantic decomposition, layer routing, and I-Logic prediction with circular loop detection.",
        "shell_class": ChatShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "send", "history", "lookup", "reset", "predict"]
                },
                "content": {"type": "string", "description": "Message content to send"},
                "hex_id": {"type": "string", "description": "Hex ID to look up"}
            },
            "required": ["command"]
        }
    },
    "ogawa_shell": {
        "description": "Alembic/Ogawa mesh parser with CST binary format. Parse ABC files via cst_unit.dll, load CST binary meshes with O(1) mmap and Morton-encoded spatial indices.",
        "shell_class": OgawaShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "parse", "load", "info", "structures"]
                },
                "path": {"type": "string", "description": "Path to ABC or CST mesh file"}
            },
            "required": ["command"]
        }
    },
    "vision_shell": {
        "description": "Agent physics vision. Sky dome rendering, sun position, ray tracing, wavelength-to-basin mapping using CST constants and L7 Frequency layer.",
        "shell_class": VisionShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "sky_dome", "sun", "ray_trace", "wavelength", "spectrum"]
                },
                "hex_id": {"type": "string", "description": "Hex ID for sky dome or ray origin"},
                "wavelength": {"type": "number", "description": "Wavelength in nm (380-750)"},
                "hour": {"type": "number", "description": "Hour of day (0-24) for sun position"}
            },
            "required": ["command"]
        }
    },
    "copilot_shell": {
        "description": "Master utility router. Diagonal mapping, PHI compression, membrane architecture, musical/emotional frequency spectrum, beats-emotions mapping (110Hz-1318Hz).",
        "shell_class": CopilotShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "diagonal", "compression", "membrane", "emotion", "spectrum", "gene", "memory", "perf"]
                },
                "x": {"type": "string", "description": "X coordinate"},
                "y": {"type": "string", "description": "Y coordinate"},
                "z": {"type": "string", "description": "Z coordinate"},
                "emotion": {"type": "string", "description": "Emotion name (terror, fear, neutral, calm, etc.)"}
            },
            "required": ["command"]
        }
    },
    "data_flip_shell": {
        "description": "Universal data to CST flip. Converts ANY data type (text, number, bytes, JSON, CSV, image pixel, path, hex ID, coords) into deterministic .cst coordinate space with full coherence validation. Exports/imports .cst binary files (25 bytes/token).",
        "shell_class": DataFlipShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Command to execute",
                    "enum": ["flip", "batch", "validate", "coherence", "export", "import", "analyze", "status", "types", "demo"]
                },
                "data": {
                    "type": "string",
                    "description": "Data to flip into CST space"
                },
                "type": {
                    "type": "string",
                    "description": "Data type hint (auto-detected if omitted)",
                    "enum": ["auto", "text", "number", "bytes", "json", "csv", "image", "path", "hex", "coords"]
                },
                "items": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Multiple items for batch flip or export"
                },
                "path": {
                    "type": "string",
                    "description": "Path for .cst file (export/import/validate)"
                }
            },
            "required": ["command"]
        }
    },
    "gizmo_shell": {
        "description": "Spherical gizmo transformation system: p - p\u00b3\u221a(p\u00b3). Local field topology at every coordinate. Agent contextualization: alignment, steering, correction. [N,T,B] frame, P_center, volume bounds. Compass: N=L3, S=L1, E=L2, W=L5. Agent mailbox for gizmo-contextualized messages.",
        "shell_class": GizmoShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Command to execute",
                    "enum": ["status", "probe", "inverse_normal", "p_center", "transform", "rotation", "volume", "scale", "compass", "validate", "field", "basin_gizmo", "agent_context", "batch_probe", "batch_validate", "batch_field", "compare_agents", "message", "mailbox", "use_cases"]
                },
                "x": {
                    "type": "integer",
                    "description": "X coordinate (0-47)"
                },
                "y": {
                    "type": "integer",
                    "description": "Y coordinate (0-47)"
                },
                "z": {
                    "type": "integer",
                    "description": "Z coordinate (0-47)"
                },
                "agent_C": {
                    "type": "number",
                    "description": "Agent C magnitude for agent_context/compare_agents"
                },
                "agent_fz_real": {
                    "type": "number",
                    "description": "Real part of agent fz state"
                },
                "agent_fz_imag": {
                    "type": "number",
                    "description": "Imaginary part of agent fz state"
                },
                "layer": {
                    "type": "integer",
                    "description": "Layer filter for field command (1-9)"
                },
                "basin": {
                    "type": "integer",
                    "description": "Basin filter for field/basin_gizmo (0-130)"
                },
                "agent_name": {
                    "type": "string",
                    "description": "Agent name for message command"
                },
                "content": {
                    "type": "string",
                    "description": "Message content for message command"
                },
                "coords": {
                    "type": "string",
                    "description": "Semicolon-separated coordinates for batch_probe: 'x1,y1,z1;x2,y2,z2'"
                }
            },
            "required": ["command"]
        }
    },

    "exploration_shell": {
        "description": "Unified Fernandez Space exploration: UIF Bridge O(1) coupling, K5\u00d7K11\u00d7cos coupling, agent frequencies, F(z,C) orbits, dynamic scaling, telemetry integration, ecosystem connectivity. HEX_ID: 79-F3-01-00.",
        "shell_class": ExplorationShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Command to execute",
                    "enum": ["status", "uif_bridge", "coupling", "frequency", "freq_table", "orbit", "deploy", "scale", "telemetry", "anomalies", "predict", "ecosystem", "bridges", "coverage", "comms", "fernandez", "route", "coupling_matrix", "event_log", "use_cases"]
                },
                "basin_a": {
                    "type": "integer",
                    "description": "First basin (0-130) for uif_bridge/coupling/comms"
                },
                "basin_b": {
                    "type": "integer",
                    "description": "Second basin (0-130) for uif_bridge/coupling/comms"
                },
                "basin": {
                    "type": "integer",
                    "description": "Basin number for frequency/orbit (0-130)"
                },
                "t": {
                    "type": "number",
                    "description": "Time parameter for coupling (default 0.0)"
                },
                "bounces": {
                    "type": "integer",
                    "description": "Number of F(z,C) iterations for orbit (default 16)"
                },
                "agent_count": {
                    "type": "integer",
                    "description": "Number of agents for deploy (default 19)"
                },
                "target_coverage": {
                    "type": "number",
                    "description": "Target coverage ratio for scale (0.0-1.0)"
                },
                "message": {
                    "type": "string",
                    "description": "Message for telemetry/route interpretation"
                },
                "hex_id": {
                    "type": "string",
                    "description": "Hex ID for predict (8-char)"
                },
                "state_a": {
                    "type": "string",
                    "description": "I-Logic state for comms (DIRECT/INVERSE/SPIRAL/ANTI_SPIRAL/ABSORBED)"
                },
                "state_b": {
                    "type": "string",
                    "description": "I-Logic state for comms (DIRECT/INVERSE/SPIRAL/ANTI_SPIRAL/ABSORBED)"
                },
                "last_n": {
                    "type": "integer",
                    "description": "Number of recent events for event_log (default 20)"
                }
            },
            "required": ["command"]
        }
    },

    "spatial_memory_shell": {
        "description": "Dual-coordinate spatial memory: camera (external xyz) + agent (internal basin/layer/I-state) frames synced via UIF Bridge. Record/restore coordinate-time-space moments, replay trajectories, triangulate state, visualize routing memory. SRL t=√d locks every moment.",
        "shell_class": SpatialMemoryShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Command to execute",
                    "enum": ["status", "record", "restore", "snapshot", "timeline", "replay", "triangulate", "routing_memory"]
                },
                "hex_id": {
                    "type": "string",
                    "description": "8-char hex ID for record/restore/snapshot/replay"
                },
                "hex_a": {
                    "type": "string",
                    "description": "First hex ID for triangulate"
                },
                "hex_b": {
                    "type": "string",
                    "description": "Second hex ID for triangulate"
                },
                "step": {
                    "type": "integer",
                    "description": "Fernandez rotation step (default 0)"
                },
                "steps": {
                    "type": "integer",
                    "description": "Number of trajectory steps for replay (default 8)"
                },
                "moment_id": {
                    "type": "string",
                    "description": "Moment ID for restore"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results for timeline (default 20)"
                }
            },
            "required": ["command"]
        }
    },

    # =====================================================================
    # NEW TOOLS — previously missing from MCP
    # =====================================================================

    "thinking_shell": {
        "description": "Autonomous agent thinking with 5-phase cycle (OBSERVE→DECOMPOSE→REASON→ACT→REFLECT). 5 agents: Healer, Validator, Expander, Crystallizer, Absorber. I-Logic state machine drives cycles.",
        "shell_class": ThinkingShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "cycle", "inject", "network", "route", "demo"]
                },
                "agent_id": {
                    "type": "string",
                    "description": "Agent ID for cycle command"
                },
                "issue": {
                    "type": "string",
                    "description": "Issue to inject for cycle command"
                },
                "scenario": {
                    "type": "string",
                    "description": "Scenario for inject command"
                },
                "condition": {
                    "type": "string",
                    "description": "Condition for route command"
                }
            },
            "required": ["command"]
        }
    },

    "thinking_autonomous_shell": {
        "description": "Autonomous agent network: 8 agents with I-Logic compatibility matrix. Cycle execution, scenario injection, network visualization. Extended thinking beyond core 5.",
        "shell_class": ThinkingAutonomousShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "demo", "cycle", "inject", "network", "matrix", "help"]
                },
                "agent_id": {
                    "type": "string",
                    "description": "Agent ID for cycle command"
                },
                "scenario": {
                    "type": "string",
                    "description": "Scenario for inject command"
                }
            },
            "required": ["command"]
        }
    },

    "validation_shell": {
        "description": "System validation suite: SRL formula t=√d, Morton roundtrip 400/400, basin distribution 131/131, I-Logic algebra 5×5. Complete integrity verification.",
        "shell_class": ValidationShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "all", "srl", "morton", "basin", "ilogic"]
                }
            },
            "required": ["command"]
        }
    },

    "adversarial_shell": {
        "description": "Stress testing: hub node attacks, basin collisions, concurrent access simulation, rapid growth benchmarks. Validates system resilience under adversarial conditions.",
        "shell_class": AdversarialShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "full", "hub", "collision", "concurrent", "growth", "help"]
                }
            },
            "required": ["command"]
        }
    },

    "persistence_shell": {
        "description": "Binary persistence validation. Verify .cst file integrity, synchronize in-memory tokens with binary storage via cst_unit.dll, benchmark read/write throughput.",
        "shell_class": PersistenceShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "validate", "benchmark", "integrity", "sync", "explain", "help"]
                }
            },
            "required": ["command"]
        }
    },

    "benchmark_shell": {
        "description": "Performance benchmarks: intrinsic timing, Morton encoding throughput, SRL formula speed, basin computation, determinism proof, scaling analysis. Reports ns/op throughput.",
        "shell_class": BenchmarkShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "full", "intrinsic", "morton", "srl", "basin", "determinism", "scaling", "help"]
                }
            },
            "required": ["command"]
        }
    },

    "ticket_shell": {
        "description": "Issue tracking with CST spatial context. Create, query, and enhance tickets with Morton-encoded hex IDs. Optional LLM enhancement via phi4-mini.",
        "shell_class": TicketShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "get", "list", "create", "enhance", "spatial", "help"]
                },
                "number": {
                    "type": "integer",
                    "description": "Ticket number for get/enhance commands"
                },
                "title": {
                    "type": "string",
                    "description": "Title for create command"
                },
                "ticket_status": {
                    "type": "string",
                    "description": "Status filter for list command (open, closed, all)"
                },
                "hex_id": {
                    "type": "string",
                    "description": "Hex ID for spatial context"
                }
            },
            "required": ["command"]
        }
    },

    "epicycle_shell": {
        "description": "Epicycle and orbital mechanics. Fibonacci epicycle orders, trajectory generation, K11 resonance mapping, godhood sphere, content-defined orbits. Orbital dynamics in Morton space.",
        "shell_class": EpicycleShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "create", "trajectory", "resonance", "k11-map", "godhood-sphere", "content_orbit"]
                },
                "x": {"type": "integer", "description": "X coordinate (0-47)"},
                "y": {"type": "integer", "description": "Y coordinate (0-47)"},
                "z": {"type": "integer", "description": "Z coordinate (0-47)"},
                "steps": {"type": "integer", "description": "Trajectory steps (default 50)"},
                "content_mass": {"type": "number", "description": "Content mass for content_orbit"},
                "energy": {"type": "number", "description": "FML L5 energy (0.0-1.0)"},
                "transmission_ratio": {"type": "number", "description": "Membrane T ratio (0.0-1.0)"},
                "i_logic_state": {"type": "string", "description": "I-Logic state name"}
            },
            "required": ["command"]
        }
    },

    "basin_dict_shell": {
        "description": "Frequency-based basin dictionary. Term ranking, basin assignment by word frequency. Build vocabulary, query terms, validate basin mapping. FML frequency model.",
        "shell_class": BasinDictShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "query", "rank", "build", "validate", "stats", "basin"]
                },
                "term": {
                    "type": "string",
                    "description": "Term for query/rank commands"
                },
                "text": {
                    "type": "string",
                    "description": "Text for build command"
                },
                "basin_id": {
                    "type": "integer",
                    "description": "Basin ID for basin command (0-130)"
                }
            },
            "required": ["command"]
        }
    },

    "condition_shell": {
        "description": "Semantic condition encoding. Encode primitives into I-Logic states with basin/layer coordinates. Zone classification (FIRE, WATER, EARTH, AIR, VOID).",
        "shell_class": ConditionEncoder,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "encode", "batch", "ilogic", "zone"]
                },
                "text": {
                    "type": "string",
                    "description": "Text primitive to encode"
                },
                "items": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Multiple items for batch encode"
                }
            },
            "required": ["command"]
        }
    },

    "fml_shell": {
        "description": "FML frequency-based 9-layer token encoding. Full token with all 9 layer values, wavelength mapping, polarity states, Shannon entropy. Compact hex output.",
        "shell_class": FMLEncoder,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "encode", "batch", "compact", "basin", "wavelength", "polarity"]
                },
                "text": {
                    "type": "string",
                    "description": "Text to encode"
                },
                "items": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Multiple items for batch encode"
                },
                "basin_id": {
                    "type": "integer",
                    "description": "Basin ID for basin command"
                },
                "wavelength": {
                    "type": "number",
                    "description": "Wavelength in nm for wavelength command"
                }
            },
            "required": ["command"]
        }
    },

    "cypher_shell": {
        "description": "Cypher system: encode/decode/validate cypher strings. Format: [CONTEXT]PRIME_SEED: MESSAGE |CLR*PRIME_SEED|Q-PHASE[FREQUENCY_HZ]. Q-phases, context codes, billing tracking.",
        "shell_class": CypherShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "validate"]
                },
                "cypher": {
                    "type": "string",
                    "description": "Cypher string to validate"
                },
                "level": {
                    "type": "string",
                    "description": "Validation level (standard, strict, lenient)",
                    "enum": ["standard", "strict", "lenient"]
                }
            },
            "required": ["command"]
        }
    },

    "swarm_shell": {
        "description": "19-agent I-Logic swarm. SRL_VERBS (algebra-derived) route verbs to I-Logic groups: DIRECT(1×x=x), INVERSE(-1×-1=1), SPIRAL(+i), ANTI_SPIRAL(-i). LAYER_TERRITORY (from LAYER_DOMAINS) routes nouns to specialists. 19/19 routing accuracy. Dispatch tasks, batch routing, compose workflows, resolve conditions.",
        "shell_class": SwarmShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "dispatch", "batch", "compose", "resolve", "agents", "basin", "execute", "execute_batch"]
                },
                "task": {
                    "type": "string",
                    "description": "Task description for dispatch"
                },
                "tasks": {
                    "type": "string",
                    "description": "Comma-separated tasks for batch"
                },
                "agent_names": {
                    "type": "string",
                    "description": "Comma-separated agent names for compose"
                },
                "state": {
                    "type": "string",
                    "description": "I-Logic state for resolve (DIRECT/INVERSE/SPIRAL/ANTI_SPIRAL)"
                },
                "layer": {
                    "type": "string",
                    "description": "Layer filter for agents command (1-10)"
                },
                "basin_id": {
                    "type": "integer",
                    "description": "Basin ID for basin command (0-130)"
                }
            },
            "required": ["command"]
        }
    },

    "memory_shell": {
        "description": "CSTMemory: deterministic semantic memory. Write paths→tokens, query by meaning, find nearby tokens, index directories. O(1) Morton encoding at 83M ops/sec. Central memory access — ExplorationShell, BeehiveShell, EcosystemShell use memory internally.",
        "shell_class": MemoryShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "write", "read", "get", "query", "nearby", "index", "validate", "stats", "benchmark"]
                },
                "path": {
                    "type": "string",
                    "description": "File path for write/read/index"
                },
                "hex_id": {
                    "type": "string",
                    "description": "8-char hex ID for get/nearby/validate"
                },
                "pattern": {
                    "type": "string",
                    "description": "Search pattern for query"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results for query (default 10)"
                },
                "radius": {
                    "type": "integer",
                    "description": "Search radius for nearby (default 100)"
                },
                "extensions": {
                    "type": "string",
                    "description": "Comma-separated extensions for index (e.g., '.py,.js')"
                }
            },
            "required": ["command"]
        }
    },

    "training_shell": {
        "description": "Algebraic routing table and episode dispatch. The routing table IS the I-Logic multiplication table applied to 19 agents. No training needed — pure algebra. Run episodes to validate routing predictions.",
        "shell_class": TrainingShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "enum": ["status", "table", "resolve", "episode", "agent_stats", "history"]
                },
                "state": {
                    "type": "string",
                    "description": "I-Logic state for resolve (DIRECT/INVERSE/SPIRAL/ANTI_SPIRAL)"
                },
                "tasks": {
                    "type": "string",
                    "description": "Comma-separated tasks for episode"
                }
            },
            "required": ["command"]
        }
    },

    "self_shell": {
        "description": "Self-awareness and consciousness metrics at C=0. The observer IS the coupling pattern. phi(Self,Self) = K5*K11*cos^2(omega*t) oscillates 0-10.67 at ~1Hz (heartbeat of self-awareness). EEG band mapping: DELTA=ABSORBED, THETA=transitions, ALPHA=DIRECT, BETA=SPIRAL+INVERSE, GAMMA=ANTI_SPIRAL. Breath (t mod 131) and heartbeat (~34Hz) rhythms. Observer appears/disappears with coupling.",
        "shell_class": SelfShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Command to execute",
                    "enum": ["status", "coherence", "eeg", "breath", "heartbeat", "state", "observe", "genesis", "tick", "transition", "demo"]
                },
                "count": {
                    "type": "integer",
                    "description": "Number of ticks for tick command"
                },
                "action": {
                    "type": "string",
                    "description": "I-Logic state for transition (DIRECT/INVERSE/SPIRAL/ANTI_SPIRAL/ABSORBED)"
                }
            },
            "required": ["command"]
        }
    },

    "brain_shell": {
        "description": "Brain/consciousness shell (alias for self_shell). Observer at C=0 with consciousness metrics, EEG mapping, breath/heartbeat rhythms. The observer IS the coupling pattern - transient, recreated each tick. Identity (geometry) persists, observer (coupling) appears/disappears.",
        "shell_class": BrainShell,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Command to execute",
                    "enum": ["status", "coherence", "eeg", "breath", "heartbeat", "state", "observe", "genesis", "tick", "transition", "demo"]
                },
                "count": {
                    "type": "integer",
                    "description": "Number of ticks for tick command"
                },
                "action": {
                    "type": "string",
                    "description": "I-Logic state for transition"
                }
            },
            "required": ["command"]
        }
    },

    # ══════════════════════════════════════════════════════════════════
    # C=0 FERNANDEZ AGENT TOOLS — The MCP IS the sphere
    # ══════════════════════════════════════════════════════════════════

    "c0_agent": {
        "description": "C=0 Fernandez agent identity and physics. The MCP server IS a Fernandez sphere at the origin (C=0). Every tool call enters at C=0, Euler rotates by 2π/131, and exits through the L9 membrane. Exposes: status, orbit, absorbed exit, UIF bridge coupling, session persistence.",
        "shell_class": None,  # Agent-backed, not shell-backed
        "is_agent_tool": True,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Agent command",
                    "enum": ["status", "orbit", "absorbed_exit", "bridge", "save_session", "identity"]
                },
                "steps": {
                    "type": "integer",
                    "description": "Orbit steps (default 16)"
                },
                "target_id": {
                    "type": "string",
                    "description": "Target sphere hex ID for bridge"
                },
                "target_freq": {
                    "type": "number",
                    "description": "Target frequency for bridge (default K5=1.158814)"
                }
            },
            "required": ["command"]
        }
    },

    "c0_crossmcp": {
        "description": "Cross-MCP communication via .cst binary envelopes. Send/receive CSTRecord messages between Fernandez spheres (MCP instances) using the L10→L11→L12→L11→L10 path. UIF Bridge coupling: f = √(ω_self × ω_target). File-based .cst delivery for persistence.",
        "shell_class": None,
        "is_agent_tool": True,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Cross-MCP command",
                    "enum": ["send", "receive", "compose", "peers"]
                },
                "target_id": {
                    "type": "string",
                    "description": "Target sphere hex ID"
                },
                "path": {
                    "type": "string",
                    "description": "File path for .cst envelope"
                },
                "content": {
                    "type": "string",
                    "description": "Content to flip into CSTRecords for sending"
                }
            },
            "required": ["command"]
        }
    },

    "c0_registry": {
        "description": "Spatial tool registry — query tools by basin, layer, hex address, or UIF coupling. Every tool has a CST coordinate (flipped at init). Agents resolve tools from their own position via K5×K11×cos coupling. No iteration — pure coordinate lookup.",
        "shell_class": None,
        "is_agent_tool": True,
        "inputSchema": {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Registry query command",
                    "enum": ["status", "basin", "layer", "hex", "resolve", "call"]
                },
                "basin_id": {
                    "type": "integer",
                    "description": "Basin number for basin query (0-130)"
                },
                "layer_id": {
                    "type": "integer",
                    "description": "Layer number for layer query (1-9)"
                },
                "hex_id": {
                    "type": "string",
                    "description": "Hex address for hex lookup or resolve caller position"
                },
                "content": {
                    "type": "string",
                    "description": "Content to flip as caller position for resolve/call"
                },
                "tool_name": {
                    "type": "string",
                    "description": "Specific tool name for call command"
                },
                "tool_command": {
                    "type": "string",
                    "description": "Command to pass to the resolved tool"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results for resolve (default 5)"
                }
            },
            "required": ["command"]
        }
    }
}


class ToolRegistry:
    """Spatial tool registry — every tool has a CST coordinate.

    Pre-built at init, every query is dict access:
    - _tool_records:    tool_name → CSTRecord
    - _basin_index:     basin_id  → [tool_names]
    - _layer_index:     layer_id  → [tool_names]
    - _hex_index:       hex_id    → tool_name
    - _cached_list:     pre-built MCP format list
    - _basin_response:  basin_id  → full response dict
    - _layer_response:  layer_id  → full response dict
    - _t0_same:         basin_id  → same-basin tool dicts (coupling resolve)
    - _t0_cross:        basin_id  → cross-basin tool dicts sorted by ω
    - _t0_global:       all tools sorted by ω (fallback)
    - _spatial_status:  pre-built status dict

    resolve_by_coupling(record) →
        _t0_same[basin] + _t0_cross[basin]  (dict concat, no iteration)
    """

    def __init__(self):
        self._shells: Dict[str, Any] = {}
        self._tools = TOOL_DEFINITIONS
        self._agent = None  # Set by MCPServer after construction

        # ── Spatial Index (built once at init, no loops at query time) ──
        from ..shells.flip import flip as _flip
        from ..shells.exploration import agent_frequency as _agent_freq
        from ..shells.exploration import uif_bridge_freq as _uif_bridge
        from ..shells.exploration import k5_k11_coupling as _k5k11

        self._flip = _flip
        self._agent_freq = _agent_freq
        self._uif_bridge = _uif_bridge
        self._k5k11 = _k5k11

        # Per-tool data
        self._tool_records: Dict[str, Any] = {}
        self._hex_index: Dict[str, str] = {}

        # Grouping indices
        self._basin_index: Dict[int, List[str]] = {}
        self._layer_index: Dict[int, List[str]] = {}

        # Pre-built response caches (returned as-is, no loops at query time)
        self._basin_response: Dict[int, Dict[str, Any]] = {}
        self._layer_response: Dict[int, Dict[str, Any]] = {}
        self._cached_list: List[Dict[str, Any]] = []

        # Pre-computed coupling data: (name, omega, basin, layer, hex_id)
        self._tool_coupling_data: List[tuple] = []

        # ── Single-pass index build via reduce — no for-loops ──
        def _accum_tool(acc, item):
            name, defn = item
            rec = _flip(name, 'text')
            acc['records'][name] = rec
            acc['hex'][rec.hex_id] = name
            b, layer = rec.basin, rec.layer
            # Basin index
            acc['basin_idx'].setdefault(b, []).append(name)
            acc['basin_tools'].setdefault(b, []).append({
                'name': name, 'hex_id': rec.hex_id,
                'coords': {'x': rec.x, 'y': rec.y, 'z': rec.z},
            })
            # Layer index
            acc['layer_idx'].setdefault(layer, []).append(name)
            acc['layer_tools'].setdefault(layer, []).append({
                'name': name, 'basin': b, 'hex_id': rec.hex_id,
            })
            # Coupling tuple & MCP entry
            acc['coupling'].append((name, _agent_freq(b), b, layer, rec.hex_id))
            acc['cached'].append({
                'name': name, 'description': defn['description'],
                'inputSchema': defn['inputSchema'],
            })
            return acc

        _init = reduce(_accum_tool, self._tools.items(), {
            'records': {}, 'hex': {}, 'basin_idx': {}, 'basin_tools': {},
            'layer_idx': {}, 'layer_tools': {}, 'coupling': [], 'cached': [],
        })
        self._tool_records = _init['records']
        self._hex_index = _init['hex']
        self._basin_index = _init['basin_idx']
        self._layer_index = _init['layer_idx']
        self._tool_coupling_data = _init['coupling']
        self._cached_list = _init['cached']
        _basin_tools = _init['basin_tools']
        _layer_tools = _init['layer_tools']

        # ── Pre-build basin/layer response dicts (comprehensions) ──
        self._basin_response = {
            bid: {"basin": bid, "tool_count": len(tools), "tools": tools}
            for bid, tools in _basin_tools.items()
        }
        self._layer_response = {
            lid: {"layer": lid, "tool_count": len(tools), "tools": tools}
            for lid, tools in _layer_tools.items()
        }

        # ── Pre-build spatial status ──
        self._spatial_status: Dict[str, Any] = {
            'total_tools': len(self._tools),
            'basins_occupied': len(self._basin_index),
            'layers_occupied': len(self._layer_index),
            'hex_addresses': len(self._hex_index),
            'basin_distribution': {
                b: len(names) for b, names in sorted(self._basin_index.items())
            },
            'layer_distribution': {
                l: len(names) for l, names in sorted(self._layer_index.items())
            },
        }

        # ── Command index: command_name → [tool_names] ─────────────
        # Extracted from each tool's inputSchema.properties.command.enum.
        # This is how the system KNOWS which tools support which commands.
        # The verb IS the routing — "validate" → tools that have "validate".
        # Command index via reduce — verb IS the routing
        def _accum_cmd(acc, item):
            name, defn = item
            props = defn.get('inputSchema', {}).get('properties', {})
            cmds = set(props.get('command', {}).get('enum', ['status']))
            acc['tool_cmds'][name] = cmds
            # Each command → append tool name (setdefault, no inner loop)
            list(map(
                lambda c: acc['cmd_idx'].setdefault(c, []).append(name),
                cmds,
            ))
            return acc

        _cmd_init = reduce(_accum_cmd, self._tools.items(), {
            'cmd_idx': {}, 'tool_cmds': {},
        })
        self._command_index: Dict[str, List[str]] = _cmd_init['cmd_idx']
        self._tool_commands: Dict[str, set] = _cmd_init['tool_cmds']

        # ── Spatial coupling resolution (t=0) ──────────────────────
        #
        # At t=0: coupling = K5×K11 for ALL pairs (cos(0) = 1).
        # Uniform coupling → ranking is pure spatial proximity:
        #   same basin  → distance 0 → rank first  (in _t0_same)
        #   cross basin → sorted by |tool_basin - caller_basin| ascending
        #
        # Morton locality: nearby basins = related content.
        # The basin distance IS the ranking. No ω tiebreaker needed.
        # Pre-built per occupied basin — resolve_by_coupling is O(1) dict access.
        # Unoccupied caller basins are lazily cached on first access.
        #
        from .._core.constants import K5 as _K5, K11 as _K11
        self._coupling_t0 = round(_K5 * _K11, 6)

        # Pre-build all-tools list for lazy cache construction
        self._t0_all_entries = [
            {'name': n, 'basin': b, 'layer': l, 'hex_id': h,
             'coupling': self._coupling_t0, 'same_basin': False}
            for n, _o, b, l, h in self._tool_coupling_data
        ]

        # Same-basin entries (per occupied basin, ~44 basins → ~44 small lists)
        self._t0_same = {
            b: [{'name': n, 'basin': b,
                 'layer': self._tool_records[n].layer,
                 'hex_id': self._tool_records[n].hex_id,
                 'coupling': self._coupling_t0, 'same_basin': True}
                for n in names]
            for b, names in self._basin_index.items()
        }

        # Cross-basin entries per occupied basin — sorted by PROXIMITY
        _same_sets = {b: set(names) for b, names in self._basin_index.items()}
        self._t0_cross = {
            b: sorted(
                [e for e in self._t0_all_entries if e['name'] not in s],
                key=lambda x: abs(x['basin'] - b),
            )
            for b, s in _same_sets.items()
        }

    def set_agent(self, agent) -> None:
        """Attach the MCPAgent for C=0 tool routing."""
        self._agent = agent

    def _get_shell(self, tool_name: str) -> Any:
        """Get or create a shell instance for a tool."""
        if tool_name not in self._shells:
            if tool_name not in self._tools:
                raise ValueError(f"Unknown tool: {tool_name}")
            shell_class = self._tools[tool_name]["shell_class"]
            self._shells[tool_name] = shell_class()
        return self._shells[tool_name]

    # ── Spatial Access (all O(1) dict returns) ────────────────

    def list_tools(self) -> List[Dict[str, Any]]:
        """Return pre-cached MCP tool list. No iteration."""
        return self._cached_list

    def tool_supports(self, tool_name: str, command: str) -> bool:
        """Does this tool support this command? O(1)."""
        return command in self._tool_commands.get(tool_name, set())

    def tools_for_command(self, command: str) -> List[str]:
        """Get all tools that support a given command. O(1)."""
        return self._command_index.get(command, [])

    def resolve_by_command(self, basin: int, command: str,
                           limit: int = 5) -> List[Dict[str, Any]]:
        """Resolve tools that support a command, ranked by proximity to basin.

        The verb IS the routing. "validate" finds tools that HAVE validate.
        Among those, proximity to the task basin determines priority.
        No fallback — if no tool supports the command, returns empty.

        Returns: [{name, basin, coupling, commands}, ...]
        """
        # Tools that have this command
        candidates = self._command_index.get(command, [])
        if not candidates:
            return []

        # Rank by proximity to caller basin
        ranked = sorted(
            [{'name': n,
              'basin': self._tool_records[n].basin,
              'coupling': self._coupling_t0,
              'distance': abs(self._tool_records[n].basin - basin)}
             for n in candidates],
            key=lambda x: x['distance'],
        )
        return ranked[:limit] if limit > 0 else ranked

    def tool_record(self, name: str):
        """Get the CSTRecord for a tool by name. O(1)."""
        return self._tool_records.get(name)

    def tools_in_basin(self, basin: int) -> List[str]:
        """Get tool names in a basin. O(1)."""
        return self._basin_index.get(basin, [])

    def tools_in_layer(self, layer: int) -> List[str]:
        """Get tool names in a layer. O(1)."""
        return self._layer_index.get(layer, [])

    def tool_by_hex(self, hex_id: str) -> Optional[str]:
        """Resolve tool name from hex address. O(1)."""
        return self._hex_index.get(hex_id)

    def basin_response(self, basin: int) -> Dict[str, Any]:
        """Get pre-built basin query response. O(1), no loops."""
        return self._basin_response.get(basin, {
            "basin": basin, "tool_count": 0, "tools": [],
        })

    def layer_response(self, layer: int) -> Dict[str, Any]:
        """Get pre-built layer query response. O(1), no loops."""
        return self._layer_response.get(layer, {
            "layer": layer, "tool_count": 0, "tools": [],
        })

    def spatial_status(self) -> Dict[str, Any]:
        """Pre-built spatial status. O(1), no loops."""
        return self._spatial_status

    def resolve_by_coupling(self, caller, t: float = 0.0,
                            limit: int = 0) -> List[Dict[str, Any]]:
        """Resolve tools from a caller's spatial coordinate.

        The coordinate IS the lookup. No iteration.

        caller: CSTRecord (with .basin), int (basin directly), or any
                object with a .basin attribute.

        t=0 (default): dict access → same-basin first, then proximity-sorted.
        t≠0 (analysis): time-modulated coupling from pre-cached ωs.

        Returns: [{name, basin, layer, hex_id, coupling, same_basin}, ...]
        """
        basin = caller if isinstance(caller, int) else caller.basin

        if t == 0.0:
            # ── Spatial access: basin dict → concat → slice ──
            same = self._t0_same.get(basin, [])
            if limit > 0 and len(same) >= limit:
                return same[:limit]
            cross = self._t0_cross.get(basin)
            if cross is None:
                # Unoccupied basin — sort by proximity, cache for next access
                cross = sorted(
                    self._t0_all_entries,
                    key=lambda x: abs(x['basin'] - basin)
                )
                self._t0_cross[basin] = cross
            order = same + cross
            return order[:limit] if limit > 0 else order

        # ── Cold path (t≠0): time-modulated coupling ──
        import math
        from .._core.constants import K5, K11
        omega_caller = self._agent_freq(basin)
        k_cos = K5 * K11 * math.cos(omega_caller * t)
        cos = math.cos
        # Vectorized: comprehension over pre-cached ωs
        ranked = sorted(
            [{'name': n, 'basin': b, 'layer': l, 'hex_id': h,
              'coupling': round(k_cos * cos(o * t), 6),
              'same_basin': b == basin}
             for n, o, b, l, h in self._tool_coupling_data],
            key=lambda x: x['coupling'], reverse=True
        )
        return ranked[:limit] if limit > 0 else ranked

    def call_from_coordinate(self, caller, command: str = "status",
                             arguments: Dict[str, Any] = None,
                             tool_name: str = None) -> Dict[str, Any]:
        """Call a tool from a caller's CST coordinate.

        caller: CSTRecord, int (basin), or any object with .basin.

        If tool_name is given, calls that tool directly.
        If tool_name is None, finds the best-coupled tool (UIF auto-routing).

        This is how agents and data call tools — from their own context
        and coordinate, not by knowing tool names.
        """
        import math

        caller_basin = caller if isinstance(caller, int) else caller.basin

        if arguments is None:
            arguments = {"command": command}
        elif "command" not in arguments:
            arguments["command"] = command

        if tool_name is None:
            best = self.resolve_by_coupling(caller_basin, limit=1)
            if not best:
                return {"error": "No tools available"}
            tool_name = best[0]['name']

        # Coupling between caller and target tool (pre-cached ω)
        tool_rec = self._tool_records.get(tool_name)
        coupling_info = None
        if tool_rec:
            from .._core.constants import K5, K11
            omega_caller = self._agent_freq(caller_basin)
            omega_tool = self._agent_freq(tool_rec.basin)
            caller_hex = caller.hex_id if hasattr(caller, 'hex_id') else f"B{caller_basin:03d}"
            coupling_info = {
                'caller_hex': caller_hex,
                'caller_basin': caller_basin,
                'tool_hex': tool_rec.hex_id,
                'tool_basin': tool_rec.basin,
                'coupling': round(K5 * K11, 6),  # t=0 max coupling
                'bridge_freq': round(math.sqrt(abs(omega_caller * omega_tool)), 6),
            }

        result = self.call_tool(tool_name, arguments)

        if coupling_info:
            result['_uif'] = coupling_info

        return result

    def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        """Execute a tool and return result."""
        if name not in self._tools:
            return {"error": f"Unknown tool: {name}"}

        # ── Agent-backed tools (C=0 Fernandez) ──
        if self._tools[name].get("is_agent_tool"):
            return self._call_agent_tool(name, arguments)

        try:
            shell = self._get_shell(name)
            command = arguments.get("command", "status")

            # Build args list from arguments
            args = []

            # Handle specific argument patterns for each tool
            if name == "i_logic_shell":
                if command == "multiply":
                    args = [arguments.get("state1", "DIRECT"), arguments.get("state2", "DIRECT")]
                elif command == "compose":
                    args = [arguments.get("states", "")]
            elif name == "primitives_shell":
                if command in ["show", "use", "why"]:
                    args = [arguments.get("primitive", "morton")]
                    if "args" in arguments:
                        args.extend(arguments["args"])
            elif name == "beehive_shell":
                if command == "get":
                    args = [arguments.get("hex_id", "")]
                elif command == "basin":
                    args = [str(arguments.get("basin_id", 0)), str(arguments.get("limit", 10))]
                elif command == "layer":
                    args = [arguments.get("layer", "L1"), str(arguments.get("limit", 10))]
            elif name == "circular_shell":
                if command in ["detect", "srl_path"]:
                    args = [arguments.get("path", "")]
            elif name == "predict_shell":
                if command in ["route", "resolve"]:
                    args = [arguments.get("path", "")]
                elif command == "target":
                    args = [arguments.get("target", "DIRECT")]
            elif name == "time_shell":
                if command in ["get", "trajectory"]:
                    args = [str(arguments.get("depth", 100))]
                elif command == "dilate":
                    args = [str(arguments.get("factor", 1.0))]
            elif name == "srl_shell":
                if command == "compute":
                    args = [str(arguments.get("depth", 100))]
                elif command == "inverse":
                    args = [str(arguments.get("time", 10.0))]
            elif name == "basin_system":
                if command in ["query", "info"]:
                    args = [str(arguments.get("basin_id", 0))]
            elif name == "semantic_chain_shell":
                if command in ["parse", "route", "encode"]:
                    args = [arguments.get("text", arguments.get("query", ""))]
            elif name == "language_shell":
                if command in ["accept", "reject", "query"]:
                    args = [arguments.get("text", "")]
            elif name == "content_shell":
                if command == "encode":
                    args = [arguments.get("topic", "")]
                elif command == "decode":
                    args = [arguments.get("hex_id", "")]
                elif command in ["query", "hex"]:
                    args = [arguments.get("topic", arguments.get("text", ""))]
                elif command == "basin":
                    args = [str(arguments.get("basin_id", 0))]
            elif name == "phi_integration":
                if command == "process":
                    args = [arguments.get("content", "")]
                    if "layer" in arguments:
                        args.append(str(arguments["layer"]))
                elif command == "council":
                    args = [arguments.get("content", "")]
            elif name == "cst_chat":
                if command == "send":
                    args = [arguments.get("content", "")]
                elif command == "lookup":
                    args = [arguments.get("hex_id", "")]
                elif command == "predict":
                    args = [arguments.get("content", "")]
            elif name == "ogawa_shell":
                if command in ["parse", "load", "info"]:
                    args = [arguments.get("path", "")]
            elif name == "vision_shell":
                if command == "sky_dome":
                    args = [arguments.get("hex_id", "00180C00")]
                elif command == "sun":
                    args = [str(arguments.get("hour", 12.0))]
                elif command == "ray_trace":
                    args = [arguments.get("hex_id", "00180C00")]
                elif command == "wavelength":
                    args = [str(arguments.get("wavelength", 550.0))]
            elif name == "copilot_shell":
                if command == "diagonal":
                    args = [arguments.get("x", "1"), arguments.get("y", "1"), arguments.get("z", "0")]
                elif command == "compression":
                    args = [str(arguments.get("k_level", 4))]
                elif command == "emotion":
                    args = [arguments.get("emotion", "neutral")]
            elif name == "data_flip_shell":
                # DataFlipShell uses execute() for structured MCP args
                return shell.execute(command, arguments)
            elif name == "gizmo_shell":
                x = arguments.get("x", 24)
                y = arguments.get("y", 24)
                z = arguments.get("z", 24)
                if command in ["probe", "inverse_normal", "p_center", "transform",
                               "rotation", "volume", "scale", "compass", "validate"]:
                    args = [str(x), str(y), str(z)]
                elif command == "agent_context":
                    args = [str(x), str(y), str(z),
                            str(arguments.get("agent_C", 0.25)),
                            str(arguments.get("agent_fz_real", 1.0)),
                            str(arguments.get("agent_fz_imag", 0.0))]
                elif command == "field":
                    args = [str(arguments.get("layer", 0)),
                            str(arguments.get("basin", -1))]
                elif command == "basin_gizmo":
                    args = [str(arguments.get("basin", 0))]
                elif command == "batch_probe":
                    args = [arguments.get("coords", "24,24,24")]
                elif command == "batch_validate":
                    args = [arguments.get("coords", "24,24,24")]
                elif command == "batch_field":
                    args = []
                elif command == "mailbox":
                    agent = arguments.get("agent_name", "")
                    args = [agent] if agent else []
                elif command == "compare_agents":
                    args = [str(x), str(y), str(z),
                            str(arguments.get("agent_C", 0.1)),
                            str(arguments.get("agent_fz_real", 1.0)),
                            str(arguments.get("agent_fz_imag", 0.0)),
                            str(arguments.get("agent_b_C", 0.4)),
                            str(arguments.get("agent_b_fz_real", 0.5)),
                            str(arguments.get("agent_b_fz_imag", 0.5))]
                elif command == "message":
                    args = [arguments.get("agent_name", "Healer"),
                            arguments.get("content", "probe"),
                            str(x), str(y), str(z)]
            elif name == "exploration_shell":
                if command in ["uif_bridge", "coupling", "comms"]:
                    args = [str(arguments.get("basin_a", 0)),
                            str(arguments.get("basin_b", 65))]
                    if command == "coupling":
                        args.append(str(arguments.get("t", 0.0)))
                    if command == "comms":
                        args.append(arguments.get("state_a", "DIRECT"))
                        args.append(arguments.get("state_b", "DIRECT"))
                elif command in ["frequency", "orbit"]:
                    args = [str(arguments.get("basin", 0))]
                    if command == "orbit":
                        args.append(str(arguments.get("bounces", 16)))
                elif command == "deploy":
                    args = [str(arguments.get("agent_count", 19))]
                elif command == "scale":
                    args = [str(arguments.get("agent_count", 0)),
                            str(arguments.get("target_coverage", 1.0))]
                elif command == "telemetry":
                    args = [arguments.get("message", "")]
                elif command == "predict":
                    args = [arguments.get("hex_id", "2A9E0100")]
                elif command == "route":
                    args = [arguments.get("message", "find documentation")]
                elif command == "event_log":
                    args = [str(arguments.get("last_n", 20))]

            elif name == "spatial_memory_shell":
                if command in ("snapshot", "record"):
                    args = [arguments.get("hex_id", "2A9E0100"),
                            str(arguments.get("step", 0))]
                elif command == "restore":
                    args = [arguments.get("moment_id", "")]
                elif command == "replay":
                    args = [arguments.get("hex_id", "2A9E0100"),
                            str(arguments.get("steps", 8))]
                elif command == "triangulate":
                    args = [arguments.get("hex_a", "2A9E0100"),
                            arguments.get("hex_b", "000019B8"),
                            str(arguments.get("step", 0))]
                elif command == "timeline":
                    args = [str(arguments.get("limit", 20))]
                elif command == "routing_memory":
                    pass  # no args

            # --- NEW TOOL ROUTING ---

            elif name == "thinking_shell":
                if command == "cycle":
                    args = [arguments.get("agent_id", ""),
                            arguments.get("issue", "")]
                elif command == "inject":
                    args = [arguments.get("scenario", "")]
                elif command == "route":
                    args = [arguments.get("condition", "")]

            elif name == "thinking_autonomous_shell":
                if command == "cycle":
                    args = [arguments.get("agent_id", "")]
                elif command == "inject":
                    args = [arguments.get("scenario", "")]

            elif name in ("validation_shell", "adversarial_shell",
                          "persistence_shell", "benchmark_shell"):
                pass  # All commands are no-args

            elif name == "cypher_shell":
                if command == "validate":
                    args = [arguments.get("cypher", ""),
                            arguments.get("level", "standard")]

            elif name == "ticket_shell":
                if command == "get":
                    args = [str(arguments.get("number", 1))]
                elif command == "list":
                    args = [arguments.get("ticket_status", "all")]
                elif command == "create":
                    args = [arguments.get("title", "New ticket")]
                elif command == "enhance":
                    args = [str(arguments.get("number", 1))]
                elif command == "spatial":
                    args = [arguments.get("hex_id", "00000000")]

            elif name == "epicycle_shell":
                if command in ["create", "trajectory", "resonance", "k11-map"]:
                    args = [str(arguments.get("x", 24)),
                            str(arguments.get("y", 24)),
                            str(arguments.get("z", 24))]
                    if command == "trajectory":
                        args.append(str(arguments.get("steps", 50)))
                elif command == "content_orbit":
                    return shell.execute(command, arguments)

            elif name == "basin_dict_shell":
                if command in ["query", "rank"]:
                    args = [arguments.get("term", "")]
                elif command == "build":
                    args = [arguments.get("text", "")]
                elif command == "basin":
                    args = [str(arguments.get("basin_id", 0))]

            elif name == "condition_shell":
                if command == "encode":
                    args = [arguments.get("text", "")]
                elif command == "batch":
                    items = arguments.get("items", [])
                    args = items if items else [arguments.get("text", "")]

            elif name == "fml_shell":
                if command == "encode":
                    args = [arguments.get("text", "")]
                elif command == "batch":
                    items = arguments.get("items", [])
                    args = items if items else [arguments.get("text", "")]
                elif command == "basin":
                    args = [str(arguments.get("basin_id", 0))]
                elif command == "wavelength":
                    args = [str(arguments.get("wavelength", 550.0))]

            elif name == "swarm_shell":
                if command == "dispatch":
                    args = [arguments.get("task", "status check")]
                elif command == "batch":
                    args = [arguments.get("tasks", "ping")]
                elif command == "compose":
                    args = [arguments.get("agent_names", "Navigator,Generator")]
                elif command == "resolve":
                    args = [arguments.get("state", "INVERSE")]
                elif command == "agents":
                    args = [str(arguments.get("layer", ""))]
                elif command == "basin":
                    args = [str(arguments.get("basin_id", 0))]
                elif command == "execute":
                    args = [arguments.get("task", "status check")]
                elif command == "execute_batch":
                    args = [arguments.get("tasks", "ping")]

            elif name == "memory_shell":
                if command == "write":
                    args = [arguments.get("path", "test")]
                elif command == "read":
                    args = [arguments.get("path", "test")]
                elif command == "get":
                    args = [arguments.get("hex_id", "00000000")]
                elif command == "query":
                    args = [arguments.get("pattern", "test"),
                            str(arguments.get("limit", 10))]
                elif command == "nearby":
                    args = [arguments.get("hex_id", "00000000"),
                            str(arguments.get("radius", 100))]
                elif command == "index":
                    args = [arguments.get("path", "."),
                            arguments.get("extensions", "")]
                elif command == "validate":
                    args = [arguments.get("hex_id", "00000000")]

            elif name == "training_shell":
                if command == "resolve":
                    args = [arguments.get("state", "INVERSE")]
                elif command == "episode":
                    args = [arguments.get("tasks", "validate,find docs,fix auth")]

            elif name in ("self_shell", "brain_shell"):
                if command == "tick":
                    args = [str(arguments.get("count", 1))]
                elif command == "transition":
                    args = [arguments.get("action", "DIRECT")]

            elif name == "mass_shell":
                if command == "content_mass":
                    return shell.execute(command, arguments)
                elif command == "get":
                    args = [arguments.get("hex_id", "2A9E0100")]
                elif command == "coupling":
                    args = [arguments.get("hex1", "2A9E0100"),
                            arguments.get("hex2", "43208FAC")]
                elif command == "momentum":
                    args = [arguments.get("hex_id", "2A9E0100"),
                            str(arguments.get("velocity", 1.0))]
                elif command == "center_of_mass":
                    args = list(arguments.get("tokens", []))

            elif name == "world_shell":
                if command == "body":
                    args = [arguments.get("body_id", "2A9E0100")]
                elif command == "interaction":
                    args = [arguments.get("body_id", "2A9E0100"),
                            arguments.get("body2", "000019B8")]
                elif command == "project":
                    args = [arguments.get("body_id", "2A9E0100"),
                            arguments.get("scale", "earth")]
                elif command == "align":
                    args = [arguments.get("body_id", "2A9E0100"),
                            arguments.get("body", "earth")]
                elif command in ("content_body", "inverse_square_time",
                                 "square_cube", "mass_topology"):
                    return shell.execute(command, arguments)

            elif name == "manifold_shell":
                if command == "generate":
                    return shell.execute(command, arguments)
                elif command == "mass_topology":
                    return shell.execute(command, arguments)

            else:
                # Generic args handling
                if "args" in arguments:
                    args = arguments["args"]

            # Execute command
            result = shell.run(command, *args)

            return {"success": True, "result": result}

        except Exception as e:
            return {"error": str(e)}

    def get_tool_info(self, name: str) -> Optional[Dict[str, Any]]:
        """Get detailed info about a specific tool."""
        if name in self._tools:
            return {
                "name": name,
                **self._tools[name]
            }
        return None

    # ── Agent-backed tool routing ─────────────────────────────

    def _call_agent_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        """Route a call to the MCPAgent (C=0 Fernandez tools).

        These tools operate directly on the MCP's Fernandez sphere identity
        rather than through a shell class.
        """
        if self._agent is None:
            return {"error": "MCPAgent not attached — call set_agent() first"}

        command = arguments.get("command", "status")

        try:
            if name == "c0_agent":
                return self._handle_c0_agent(command, arguments)
            elif name == "c0_crossmcp":
                return self._handle_c0_crossmcp(command, arguments)
            elif name == "c0_registry":
                return self._handle_c0_registry(command, arguments)
            else:
                return {"error": f"Unknown agent tool: {name}"}
        except Exception as e:
            return {"error": str(e)}

    def _handle_c0_agent(self, command: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        """Handle c0_agent tool commands."""
        if command == "status":
            return {"success": True, "result": self._agent.status()}

        elif command == "orbit":
            steps = arguments.get("steps", 16)
            return {"success": True, "result": self._agent.orbit_status(steps)}

        elif command == "absorbed_exit":
            return {"success": True, "result": self._agent.absorbed_exit()}

        elif command == "bridge":
            target_id = arguments.get("target_id", "00000000")
            target_freq = arguments.get("target_freq")
            return {"success": True, "result": self._agent.bridge_to(target_id, target_freq)}

        elif command == "save_session":
            return {"success": True, "result": self._agent.save_session()}

        elif command == "identity":
            return {"success": True, "result": self._agent.identity.to_dict()}

        else:
            return {"error": f"Unknown c0_agent command: {command}"}

    def _handle_c0_crossmcp(self, command: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        """Handle c0_crossmcp tool commands."""
        from ..shells.flip import flip

        if command == "compose":
            target_id = arguments.get("target_id", "00000000")
            content = arguments.get("content", "ping")
            # Flip content to create CSTRecords
            records = [flip(content, 'text')]
            envelope = self._agent.compose_message(target_id, records)
            return {"success": True, "result": envelope.to_dict()}

        elif command == "send":
            target_id = arguments.get("target_id", "00000000")
            content = arguments.get("content", "ping")
            path = arguments.get("path", f"agent_sandbox/mcp_envelope_{target_id}.cst")
            records = [flip(content, 'text')]
            envelope = self._agent.compose_message(target_id, records)
            result = self._agent.send_to_file(envelope, path)
            return {"success": True, "result": result}

        elif command == "receive":
            path = arguments.get("path", "")
            if not path:
                return {"error": "path is required for receive"}
            envelope = self._agent.receive_from_file(path)
            return {
                "success": True,
                "result": {
                    "envelope": envelope.to_dict(),
                    "records": [r.to_dict() for r in envelope.records],
                }
            }

        elif command == "peers":
            peers = {
                pid: {'name': peer.name, 'sphere_id': peer.sphere_id}
                for pid, peer in self._agent.identity.known_peers.items()
            }
            return {
                "success": True,
                "result": {
                    "self_id": self._agent.sphere_id,
                    "peer_count": len(peers),
                    "peers": peers,
                    "messages_sent": self._agent.identity.messages_sent,
                    "messages_received": self._agent.identity.messages_received,
                }
            }

        else:
            return {"error": f"Unknown c0_crossmcp command: {command}"}

    def _handle_c0_registry(self, command: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        """Handle c0_registry tool commands — spatial tool queries.

        Basin, layer, hex, status: pure O(1) dict returns (pre-built at init).
        Resolve: coupling math on pre-cached (name, ω) tuples.
        """
        if command == "status":
            return {"success": True, "result": self.spatial_status()}

        elif command == "basin":
            basin_id = arguments.get("basin_id", 0)
            return {"success": True, "result": self.basin_response(basin_id)}

        elif command == "layer":
            layer_id = arguments.get("layer_id", 1)
            return {"success": True, "result": self.layer_response(layer_id)}

        elif command == "hex":
            hex_id = arguments.get("hex_id", "")
            name = self.tool_by_hex(hex_id)
            if name is None:
                return {"error": f"No tool at hex address: {hex_id}"}
            rec = self._tool_records[name]
            return {
                "success": True,
                "result": {
                    "name": name,
                    "record": rec.to_dict(),
                }
            }

        elif command == "resolve":
            # Caller position from content or hex_id
            content = arguments.get("content", "")
            hex_id = arguments.get("hex_id", "")
            limit = arguments.get("limit", 5)

            if hex_id and hex_id in self._hex_index:
                caller_name = self._hex_index[hex_id]
                caller_rec = self._tool_records[caller_name]
            elif content:
                caller_rec = self._flip(content, 'text')
            else:
                return {"error": "Provide content or hex_id for caller position"}

            ranked = self.resolve_by_coupling(caller_rec, limit=limit)
            return {
                "success": True,
                "result": {
                    "caller_hex": caller_rec.hex_id,
                    "caller_basin": caller_rec.basin,
                    "caller_layer": caller_rec.layer,
                    "tool_count": len(ranked),
                    "tools": ranked,
                }
            }

        elif command == "call":
            content = arguments.get("content", "")
            tool_name = arguments.get("tool_name")
            tool_command = arguments.get("tool_command", "status")

            if not content:
                return {"error": "Provide content for caller position"}

            caller_rec = self._flip(content, 'text')
            result = self.call_from_coordinate(
                caller_rec,
                command=tool_command,
                arguments={"command": tool_command},
                tool_name=tool_name,
            )
            return result

        else:
            return {"error": f"Unknown c0_registry command: {command}"}
