================================================================================
  SindByte MCP Server -- OpenCode CLI Technical Reference
  For Developers and Power Users
================================================================================
Version: 1.9.09  |  Date: 2026-04-19

--------------------------------------------------------------------------------
 1. ARCHITECTURE OVERVIEW
--------------------------------------------------------------------------------
SindByte exposes TWO interfaces for OpenCode integration:

  INTERFACE A: OpenAI-Compatible API (Port 8091)
    Protocol:  HTTP REST (OpenAI / Anthropic compatible)
    Routes:    POST /v1/chat/completions
               POST /v1/messages
               GET  /v1/models
    Use case:  OpenCode treats SindByte as its AI provider.
               SindByte proxies to LM Studio and optionally runs the
               IQTools pipeline before returning results.

  INTERFACE B: Native MCP Server (Port 5555)
    Protocol:  Model Context Protocol (MCP) over HTTP/SSE
    Routes:    POST /mcp  (JSON-RPC 2.0)
    Use case:  OpenCode uses its own AI provider for chat.
               SindByte registers ~233 tools that OpenCode can call.

--------------------------------------------------------------------------------
 2. METHOD A: API ENDPOINT -- TECHNICAL DETAILS
--------------------------------------------------------------------------------

 2.1 Endpoint Configuration
    Base URL:  http://127.0.0.1:8091/v1
    Auth:      Not required (pass any string or "not-needed")

 2.2 Provider Config (opencode.json)
    {
      "sindbyte-mcp": {
        "npm": "@ai-sdk/openai-compatible",
        "name": "SindByte MCP Server (local)",
        "options": {
          "baseURL": "http://127.0.0.1:8091/v1",
          "apiKey": "not-needed"
        },
        "models": {
          "LMDirect":         { "name": "SindByte LMDirect" },
          "LMDirect_Tools":   { "name": "SindByte LMDirect + Tools" },
          "IQTools_Full":     { "name": "SindByte IQTools Full" },
          "IQTools_Research": { "name": "SindByte IQTools Research" },
          "IQTools_Trading":  { "name": "SindByte IQTools Trading" },
          "iq/full":          { "name": "SindByte IQ Full" },
          "iq/research":      { "name": "SindByte IQ Research" },
          "iq/trading":       { "name": "SindByte IQ Trading" },
          "iq/minimal":       { "name": "SindByte IQ Minimal" },
          "iq/off":           { "name": "SindByte IQ Off" }
        }
      }
    }

 2.3 Model Alias Resolution
    Aliases are resolved inside SindByte via INT_ApiProvider_ResolveModel().
    The alias determines which IQ profile (if any) is applied before the
    prompt is forwarded to LM Studio.

    Alias           IQ Profile      LM Studio Mode
    --------------------------------------------------
    LMDirect        None            Direct chat
    LMDirect_Tools  None            Direct chat + tools
    IQTools_Full    Full            CoT + MultiVote + Validate
    IQTools_Res.    Research        Web research + CoT
    IQTools_Trad.   Trading         Scanner + advisor + market data
    iq/full         Full            Same as IQTools_Full
    iq/research     Research        Same as IQTools_Research
    iq/trading      Trading         Same as IQTools_Trading
    iq/minimal      Minimal         Better-prompt only
    iq/off          None            Same as LMDirect

 2.4 IQ Pipeline Option Reference
    Pass these via request body JSON or header:

    Field                     Type    Default    Description
    ---------------------------------------------------------------------------
    soft_timeout_seconds      number  3600       Max wait for IQ chain (sec)
    chain_of_thought          number  0          Enable CoT
    multi_vote                number  0          Enable multi-vote
    consensus                 number  0          Enable validation
    web_research              number  0          Enable web research
    scanner                   number  0          Enable market scanner
    trading_advisor           number  0          Enable trading advisor
    market_data               number  0          Enable market data
    technical_analysis        number  0          Enable TA tools
    risk_manager              number  0          Enable risk manager
    paper_trading             number  0          Enable paper trading
    learning                  number  0          Enable learning mode
    memory                    number  0          Enable memory tools
    file_tools                number  0          Enable file tools
    decision_menu             number  0          Enable decision menu
    auto_expert               number  0          Enable better-prompt
    cot_steps                 number  3          CoT max steps
    multi_vote_votes          number  3          Multi-vote count
    multi_vote_temp           number  1          Multi-vote temperature
    consensus_threshold       number  75         Validation threshold %
    web_results               number  3          Web research result count
    scanner_topn              number  10         Scanner top-N
    scanner_timeframe         string  "M15"      Scanner timeframe
    trading_risk_level        number  2          Trading risk level
    ta_indicators             number  10         TA indicator count
    memory_slots              number  64         Memory slot count
    dm_options                number  8          Decision-menu options

 2.5 Timeout Chain Internals
    API Handler (OpenAI)
        |
        v
    LMChat_RunSharedIQExecutors()    <-- reads pIQ.T_SoftTimeoutSeconds
        |
        v
    MCP_IQExec_RunConfig()
        |
        v
    TT_RunPromptExecutors()
        |
        v
    TT_IQWaitForResult()             <-- polls until completed/failed
                                       or T_WaitMax expires

    T_WaitMax is derived from:
      1. ExecReq.T_WaitTimeoutSeconds (from pIQ.T_SoftTimeoutSeconds)
      2. MCP_IQExec_EffectiveWaitMax() (fallback to SoftTimeoutSeconds)

    The default was raised from 120 s to 3,600 s so API callers block
    synchronously until the IQ chain finishes.

 2.6 curl Example
    curl -X POST http://127.0.0.1:8091/v1/chat/completions \
         -H "Content-Type: application/json" \
         -d '{
           "model": "local-model",
           "messages": [{"role":"user","content":"Explain quantum computing"}],
           "options": {
             "chain_of_thought": 1,
             "cot_steps": 5,
             "soft_timeout_seconds": 600
           }
         }'

--------------------------------------------------------------------------------
 3. METHOD B: NATIVE MCP SERVER -- TECHNICAL DETAILS
--------------------------------------------------------------------------------

 3.1 MCP Protocol Configuration
    Type:      remote
    URL:       http://127.0.0.1:5555/mcp
    Protocol:  JSON-RPC 2.0 over HTTP/SSE
    Auth:      Session-based (initialize handshake required)

 3.2 Provider Config (opencode.json)
    {
      "mcp": {
        "sindbyte": {
          "type": "remote",
          "url": "http://127.0.0.1:5555/mcp",
          "enabled": true
        }
      }
    }

 3.3 Tool Governance
    OpenCode loads SindByte's tool catalog (~233 tools) after the MCP
    initialize handshake. Tools are namespaced by category:

      FileTools::*, SystemTools::*, MemoryTools::*,
      WebTools::*, TradingAI::*, IQTools::*, etc.

    Disable individual tools or patterns:
      opencode config set tools.FileTools::* false
      opencode config set tools.TradingAI::* false

    Disable entire MCP globally:
      opencode config set tools.sindbyte* false

 3.4 Per-Agent Tool Control
    {
      "tools": { "sindbyte*": false },
      "agent": {
        "my-trading-agent": {
          "tools": { "sindbyte*": true }
        }
      }
    }

 3.5 MCP Health Check
    Inside OpenCode:
      opencode mcp list

    Expected output:
      sindbyte  --  connected  --  http://127.0.0.1:5555/mcp

    If disconnected, verify SindByte is running and port 5555 is open.

--------------------------------------------------------------------------------
 4. COMPARISON MATRIX
--------------------------------------------------------------------------------

  Feature                  Method A (Endpoint)      Method B (MCP)
  ---------------------------------------------------------------------------
  Protocol                 OpenAI REST              MCP (JSON-RPC/SSE)
  Port                     8091                     5555
  AI Provider              SindByte -> LM Studio    User's own provider
  Tool Source              Built-in endpoint        SindByte MCP server
  IQ Pipeline              Yes (full control)       No
  Tool Count               ~233                     ~233
  Latency                  Higher (IQ overhead)     Lower (direct AI chat)
  Setup Complexity         Low                      Medium
  Use Case                 Research / IQ chains     Fast coding with tools

--------------------------------------------------------------------------------
 5. DEBUGGING AND LOGS
--------------------------------------------------------------------------------

  SindByte log location:   MCP_Server.log (in SindByte directory)
  OpenCode debug:          opencode --debug
  MCP connection test:     opencode mcp list
  MCP auth debug:          opencode mcp debug sindbyte

  Common error codes in MCP_Server.log:
    SESSION_REQUIRED    -- Client did not send initialize handshake
    UNKNOWN_TOOL        -- Tool name does not exist in registry
    FEATURE_DISABLED    -- Feature flag is set to 0 for that tool

--------------------------------------------------------------------------------
 6. RELATED SOURCE FILES
--------------------------------------------------------------------------------

  Server/MCP_Server_Split/MCP_Server_08_ApiProviderPaths.inc
    -- OpenAI/Anthropic API route handlers

  Server/MCP_Server.inc
    -- HTTP/SSE server and MCP JSON-RPC dispatcher

  GUI/LMChat/Actions/MCP_LMChat_Actions_IQ.inc
    -- Shared IQ executor entry point

  MCP_Components/IQTools/Core/MCP_IQTools_Execution.inc
    -- IQ facade and config builder

  Tools/TimerTools/MCP_TimerTools_Orchestrator.inc
    -- Prompt executor orchestration

  Tools/TimerTools/MCP_TimerTools_IQHelpers.inc
    -- Wait-for-result polling helper

  GUI/LMChat/MCP_LMChat_Settings.inc
    -- Chat timeout and IQ profile UI settings

--------------------------------------------------------------------------------
 7. ENVIRONMENT VARIABLES (for CI/automation)
--------------------------------------------------------------------------------

  OPENCODE_CONFIG_DIR     -- Override config directory path
  OPENCODE_CONFIG         -- Path to specific config file
  OPENCODE_CONFIG_CONTENT -- Inline JSON config (highest priority)

================================================================================
  END OF TECHNICAL REFERENCE
================================================================================
