# SindByte MCP Server — Paperclip Integration Guide

**Version**: 1.9.36+  
**Last Updated**: 2026-04-21  
**Target Audience**: Developers setting up AI agent infrastructure with SindByte and Paperclip  
**Scope**: Technical setup, configuration, and operational details. Trading strategy advice is kept marginal.

---

## Table of Contents

1. [What You Are Building](#1-what-you-are-building)
2. [Architecture Overview](#2-architecture-overview)
3. [Prerequisites](#3-prerequisites)
4. [Step-by-Step Setup](#4-step-by-step-setup)
5. [SindByte MCP Server Configuration](#5-sindbyte-mcp-server-configuration)
6. [Paperclip Agent Configuration](#6-paperclip-agent-configuration)
7. [LM-Studio AI Provider Setup](#7-lm-studio-ai-provider-setup)
8. [Tool Categories Reference](#8-tool-categories-reference)
9. [JSON-RPC Protocol Details](#9-json-rpc-protocol-details)
10. [Verification & Testing](#10-verification--testing)
11. [Troubleshooting](#11-troubleshooting)
12. [Security Notes](#12-security-notes)

---

## 1. What You Are Building

You are constructing a local AI agent infrastructure stack consisting of three layers:

| Layer | Component | Purpose |
|-------|-----------|---------|
| **Orchestration** | Paperclip | Assigns tasks to agents, tracks state, manages the agent lifecycle |
| **AI Inference** | LM-Studio | Runs local LLMs that power agent reasoning |
| **Tool Execution** | SindByte MCP Server | Exposes hundreds of tools via the Model Context Protocol (MCP) |

Agents (CEO, CTO, Traders) are spawned by Paperclip. Each agent connects to LM-Studio for reasoning and to SindByte for tool execution. SindByte handles file operations, API calls (Kraken, OpenAI, etc.), math, system commands, and trading-specific tools.

---

## 2. Architecture Overview

```
┌─────────────────────────────────────────────────────────────┐
│  Paperclip Orchestrator                                      │
│  ├── Spawns agents (CEO, CTO, Trader-01, Trader-02)        │
│  ├── Assigns tasks (issues)                                │
│  └── Dashboard & heartbeat tracking                        │
└────────────────────────┬────────────────────────────────────┘
                         │ Agent adapter (OpenCode/Codex/Claude)
                         ▼
┌─────────────────────────────────────────────────────────────┐
│  LM-Studio Local AI Server                                 │
│  ├── Loaded model: e.g., Qwen 3.6 35B MoE                 │
│  ├── OpenAI-compatible API (/v1/chat/completions)          │
│  └── Optional: API token auth (can be disabled)            │
└────────────────────────┬────────────────────────────────────┘
                         │ HTTP + Bearer token (if required)
                         ▼
┌─────────────────────────────────────────────────────────────┐
│  SindByte MCP Server                                       │
│  ├── Built into SindByte executable — auto-starts          │
│  ├── JSON-RPC 2.0 over HTTP (/mcp)                         │
│  ├── Built-in API Provider → forwards to LM-Studio        │
│  └── Hundreds of tools across 20+ categories              │
└─────────────────────────────────────────────────────────────┘
```

**Data Flow for a Single Agent Action**:
1. Paperclip assigns a task to an agent
2. Agent adapter (e.g., OpenCode) sends the prompt to LM-Studio
3. LM-Studio reasons and decides a tool is needed
4. Agent sends a JSON-RPC `tools/call` request to SindByte MCP
5. SindByte executes the tool (e.g., fetches Kraken price, reads a file)
6. Result returns to agent → LM-Studio → agent produces final output
7. Agent reports completion to Paperclip

---

## 3. Prerequisites

### Hardware
- **RAM**: 32 GB recommended (LM-Studio loads large models into RAM/VRAM)
- **Disk**: 10 GB free for model files + SindByte binaries
- **GPU**: Optional but strongly recommended for LLM inference (CUDA or ROCm)

### Software
| Component | Version | Download / Source |
|-----------|---------|-------------------|
| Windows 10/11 | 21H2+ | Required for SindByte (PowerBASIC binary) |
| Node.js | 18.x+ | https://nodejs.org (for Paperclip & OpenCode) |
| Paperclip | Latest | `npm install -g paperclipai` |
| OpenCode | Latest | `npm install -g opencode-ai` |
| LM-Studio | 0.3.x+ | https://lmstudio.ai |
| SindByte | 1.9.36+ | Distributed with this package |

### Network Ports (must be free)
You will assign four consecutive localhost ports. The defaults used in this guide are:

| Port | Service | Direction |
|------|---------|-----------|
| `<PAPERCLIP_PORT>` | Paperclip API | Inbound (localhost) |
| `<MCP_PORT>` | SindByte MCP | Inbound (localhost) |
| `<API_PROVIDER_PORT>` | SindByte API Provider | Inbound (localhost) |
| `<LMSTUDIO_PORT>` | LM-Studio REST API | Inbound (localhost) |

> **Note**: Throughout this guide, angle brackets denote values you must choose and configure consistently. Do not copy literal port numbers from any example without verifying they match your setup.

---

## 4. Step-by-Step Setup

### 4.1 Install Paperclip

```powershell
npm install -g paperclipai
paperclip --version
```

Start Paperclip:
```powershell
paperclip run
# or, to see the console window:
cmd /c start "Paperclip Server" paperclip run
```

Default URL: `http://127.0.0.1:<PAPERCLIP_PORT>`

### 4.2 Install OpenCode

```powershell
npm install -g opencode-ai
opencode --version
```

### 4.3 Install LM-Studio

1. Download from https://lmstudio.ai
2. Install and launch
3. Download a model (recommended: Qwen 3.6 35B A3B Q4_K_S for speed/quality balance)
4. Go to **Developer** → **Local Server** → Enable
5. Set port to `<LMSTUDIO_PORT>`, enable CORS
6. **Auth setting**: Either disable API token auth or note the token for later

> **Note**: If you disable auth (set `tokenMode` to `none` in LM-Studio's internal permissions store), OpenCode and SindByte can connect without tokens. This is acceptable for localhost-only setups.

### 4.4 Install SindByte

1. Extract the SindByte distribution to your desired location
2. The executable is the main SindByte binary
3. Configuration is in `mcp_config.json` (see Section 5)

**Start SindByte**:

Simply run the SindByte executable. The MCP server auto-starts on the configured port. No separate MCP startup is required.

Verify it is running:
```powershell
Test-NetConnection -ComputerName 127.0.0.1 -Port <MCP_PORT>
# Expected: TcpTestSucceeded = True
```

---

## 5. SindByte MCP Server Configuration

The primary configuration file is `mcp_config.json` in the SindByte directory.

### 5.1 Minimal Working Config

```json
{
  "port": <MCP_PORT>,
  "ApiProviderAddress": "127.0.0.1",
  "ApiProviderPort": <API_PROVIDER_PORT>,
  "local_only": true,
  "log_level": 2,
  "session_timeout_sec": 300,

  "EndpointSettings": {
    "BuiltinApiServer": {
      "Enabled": true,
      "BindPort": <API_PROVIDER_PORT>,
      "BindAddress": "127.0.0.1",
      "OpenAIEnabled": true,
      "OpenAIBasePath": "/v1",
      "OpenAIChatPath": "/v1/chat/completions",
      "OpenAIModelsPath": "/v1/models"
    },
    "LMStudio": {
      "Enabled": true,
      "Host": "127.0.0.1",
      "Port": <LMSTUDIO_PORT>,
      "Protocol": "http",
      "Mode": "openai_v1",
      "BasePath": "/v1",
      "ChatPath": "/chat/completions",
      "ModelsPath": "/models",
      "Token": ""
    }
  },

  "CloudToolsEnabled": true,
  "CloudToolsKrakenTradingEnabled": false,

  "tool_registration_mode": 1,
  "tool_registration_categories": {
    "FileTools": 1,
    "CloudTools": 2,
    "TradingIQ": 2,
    "TradingAI": 2
  }
}
```

### 5.2 Key Configuration Fields

| Field | Type | Description |
|-------|------|-------------|
| `port` | int | MCP JSON-RPC server port |
| `ApiProviderPort` | int | OpenAI-compatible proxy port |
| `local_only` | bool | If true, binds to 127.0.0.1 only |
| `log_level` | int | 0=off, 1=errors, 2=info, 3=debug |
| `session_timeout_sec` | int | MCP session timeout |
| `CloudToolsEnabled` | bool | Enable/disable cloud API tools (Kraken, Binance, etc.) |
| `CloudToolsKrakenTradingEnabled` | bool | **CRITICAL**: Must be `true` to place live orders. Set `false` for paper-only mode. |
| `tool_registration_mode` | int | 0=all tools, 1=categories, 2=whitelist |
| `tool_registration_categories` | object | Category visibility: 0=hidden, 1=read-only, 2=full, 4=interactive, 5=trading |

### 5.3 API Keys

SindByte stores encrypted API keys in `mcp_config.json` under fields like:
- `KrakenAPIKey` / `KrakenAPISecret`
- `OpenAIAPIKey`
- `BinanceAPIKey` / `BinanceAPISecret`

These are encrypted at rest. Set them via the `MCP_ConfigEditor.EXE` tool or by editing the JSON directly (values must be in the encrypted bundle format).

> **Security**: Never commit `mcp_config.json` with live API keys to a public repository.

---

## 6. Paperclip Agent Configuration

### 6.1 Create the Company and Agents

1. Open Paperclip UI: `http://127.0.0.1:<PAPERCLIP_PORT>`
2. Create a company (e.g., "MyTradingDesk")
3. Create agents with roles:
   - `ceo` — Capital allocation & governance
   - `cto` — Technical operations & evolution
   - `general` — Traders (momentum, mean-reversion, etc.)
4. Set adapter type to `opencode_local` (or `codex`, `claude`)

### 6.2 Agent Adapter Config

In Paperclip UI → Agent Settings → Adapter Config, paste the JSON that points the agent to LM-Studio and SindByte MCP.

**Method A: External AI Provider (recommended)**

The agent uses LM-Studio directly for AI and SindByte for tools:

```json
{
  "model": "lmstudio/<YOUR_MODEL_NAME>",
  "provider": {
    "lmstudio": {
      "options": {
        "baseURL": "http://127.0.0.1:<LMSTUDIO_PORT>/v1"
      }
    }
  },
  "mcp": {
    "sindbyte": {
      "type": "remote",
      "url": "http://127.0.0.1:<MCP_PORT>/mcp",
      "enabled": true
    }
  }
}
```

**Method B: Via SindByte API Provider**

The agent sends AI requests to SindByte's built-in API provider, which forwards to LM-Studio:

```json
{
  "model": "LMDirect",
  "provider": {
    "lmstudio": {
      "options": {
        "baseURL": "http://127.0.0.1:<API_PROVIDER_PORT>/v1"
      }
    }
  },
  "mcp": {
    "sindbyte": {
      "type": "remote",
      "url": "http://127.0.0.1:<MCP_PORT>/mcp",
      "enabled": true
    }
  }
}
```

> **Note**: Method B allows SindByte to add IQ layers (BetterPrompt, ensemble voting, etc.) to agent reasoning. Method A is simpler and slightly faster.

### 6.3 Worktree Isolation

Paperclip clones agents into isolated git worktrees. By default, untracked files like `.mcp.json` are **not** visible to the agent.

**Recommended**: Disable worktree isolation for single-agent projects:

```json
{
  "adapterConfig": {
    "worktreeIsolation": false
  }
}
```

If you need worktree isolation, commit `.mcp.json` to git or pass the config path via `extraArgs`.

### 6.4 Deploy .mcp.json to Projects

Copy the provided `.mcp.json` to your project root:

```powershell
Copy-Item ".mcp.json" "<Project_Root>\.mcp.json"
```

Or run the included `setup-mcp.ps1` script to deploy to multiple projects.

---

## 7. LM-Studio AI Provider Setup

### 7.1 Model Loading

1. Open LM-Studio → **Developer** tab
2. Click **Load Model** → Select your model
3. Wait for "Model loaded" status
4. Enable **Local Server** on port `<LMSTUDIO_PORT>`

### 7.2 Authentication Options

**Option 1: No Auth (Localhost Only)**

Edit LM-Studio's internal permissions store (location depends on OS, typically under the user's home directory in `.lmstudio/.internal/permissions-store.json`):

```json
{
  "json": {
    "tokenMode": "none",
    "tokens": [],
    "serverPermissions": { ... }
  }
}
```

**Option 2: Token Required**

If `tokenMode` is `required`, generate a token in LM-Studio UI and copy it to:
- SindByte `mcp_config.json` → `EndpointSettings.LMStudio.Token`
- OpenCode config if connecting directly

### 7.3 Model Recommendations for Agents

| Use Case | Model Family | Size | Quantization | Reasoning |
|----------|-------------|------|--------------|-----------|
| General coding | Qwen 3.6 A3B | 35B | Q4_K_S | Yes (thinking mode) |
| Fast inference | Nemotron 3 Nano | 4B | Q4_K_M | No |
| Code-heavy | Qwen 3 Coder | 30B | Q4_K_XL | Limited |

> **Note**: Reasoning models return empty `content` if `max_tokens` is too small, because they consume tokens in the thinking process. Ensure your agent framework requests at least 4096 `max_tokens`.

---

## 8. Tool Categories Reference

SindByte exposes hundreds of tools organized into categories. Visibility is controlled by `tool_registration_categories` in `mcp_config.json`.

### Category Permission Levels

| Level | Meaning |
|-------|---------|
| 0 | Hidden — not registered |
| 1 | Read-only — safe for untrusted agents |
| 2 | Full — read/write |
| 4 | Interactive — may prompt user |
| 5 | Trading — financial risk |

### Key Categories

| Category | Example Tools | Typical Level |
|----------|--------------|---------------|
| `FileTools` | ReadFile, WriteFile, GetDirectoryListing | 1 (read-only for safety) |
| `CloudTools` | KrakenRequest, OpenAITextToSpeech | 5 (trading enabled) |
| `TradingIQ` | Scanner, Consensus, MultiVote, Learning | 5 |
| `TradingAI` | DecisionMenu, CalculateIndicator | 5 |
| `SystemTools` | ExecuteCommand, ListProcesses | 0 (disabled for agents) |
| `MathTools` | ResolveFormula, Optimizer, MonteCarlo | 4 |
| `DataTools` | JsonSelect, RegexSearch, Split | 4 |
| `MemoryTools` | Store, Recall, ListKeys | 4 |
| `WebTools` | FetchText, Search | 0 |
| `IQTools` | BetterPrompt, Validate, ChainOfThought | 0 (often hang) |

### Trading-Specific Tools

| Tool | Purpose |
|------|---------|
| `CloudTools::KrakenRequest` | Direct Kraken API (public + private). Use `endpoint=Balance`, `AddOrder`, `CancelOrder`, etc. |
| `TradingIQ::Scanner` | Scans markets for opportunities. Async — returns task ID, poll for results. |
| `TradingIQ::Consensus` | Aggregates multiple analysis methods into a structured decision |
| `TradingIQ::MultiVote` | Runs 3 expert voters and returns combined recommendation |
| `TradingIQ::Learning` | Reads/writes paper trading state and performance metrics |
| `TradingAI::DecisionMenu` | Multi-option strategy menu (some branches may be demo-only) |
| `TradingAI::CalculateIndicator` | Technical indicators (verify live vs. simulated data) |

---

## 9. JSON-RPC Protocol Details

SindByte speaks **JSON-RPC 2.0 over HTTP POST**.

### 9.1 Endpoint

```
POST http://127.0.0.1:<MCP_PORT>/mcp
Content-Type: application/json
```

### 9.2 Tool Listing

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list"
}
```

Response: Array of tool definitions with `name`, `description`, and `inputSchema`.

### 9.3 Tool Invocation

```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "CloudTools::KrakenRequest",
    "arguments": {
      "endpoint": "Ticker",
      "params": "pair=XLMEUR"
    }
  }
}
```

Response structure:
```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"result\":{\"XXLMZEUR\":{...}}}"
      }
    ],
    "isError": false
  }
}
```

### 9.4 Important: ToolCatalog.CallTool vs. Direct Tool Calls

Some agent frameworks use a generic `ToolCatalog.CallTool` wrapper. **This wrapper can corrupt certain parameters** (confirmed: `ordertype` in Kraken AddOrder is mangled).

**Workaround**: Call tools by their direct name (`CloudTools::KrakenRequest`) with a flat `arguments` object. Do not route through `ToolCatalog.CallTool` for trading operations.

---

## 10. Verification & Testing

### 10.1 SindByte Health Check

```powershell
# Test MCP endpoint
$body = @{
    jsonrpc = "2.0"
    id      = 1
    method  = "tools/list"
} | ConvertTo-Json -Depth 3

Invoke-RestMethod -Uri "http://127.0.0.1:<MCP_PORT>/mcp" -Method POST `
    -ContentType "application/json" -Body $body

# Expected: Tools array depending on registration mode
```

### 10.2 API Provider Check

```powershell
Invoke-RestMethod -Uri "http://127.0.0.1:<API_PROVIDER_PORT>/v1/models" -Method GET
# Expected: List of model aliases (LMDirect, IQTools_Trading, etc.)
```

### 10.3 LM-Studio Check

```powershell
Invoke-RestMethod -Uri "http://127.0.0.1:<LMSTUDIO_PORT>/v1/models" -Method GET
# Expected: List of loaded models
```

### 10.4 Kraken Connectivity (via SindByte)

```powershell
$body = @{
    jsonrpc = "2.0"
    id      = 1
    method  = "tools/call"
    params  = @{
        name      = "CloudTools::KrakenRequest"
        arguments = @{
            endpoint = "Time"
            params   = ""
        }
    }
} | ConvertTo-Json -Depth 5

Invoke-RestMethod -Uri "http://127.0.0.1:<MCP_PORT>/mcp" -Method POST `
    -ContentType "application/json" -Body $body
# Expected: {"result": {"unixtime": ..., "rfc1123": "..."}}
```

### 10.5 Paperclip Dashboard

Open in browser: `http://127.0.0.1:<PAPERCLIP_PORT>/<COMPANY_SLUG>/dashboard`

Verify:
- Agents show as "active"
- No errors in agent status
- Issues/tasks are visible

---

## 11. Troubleshooting

| Symptom | Cause | Fix |
|---------|-------|-----|
| `Connection refused` on MCP port | SindByte not running | Start SindByte executable |
| `401 Unauthorized` from LM-Studio | Token required but missing/invalid | Disable auth in LM-Studio permissions or set correct token |
| `GET /mcp` returns error | Known issue — GET is not supported | Always use **POST** with JSON-RPC body |
| Agent sees 0 tools | `.mcp.json` not in project or worktree isolation active | Disable `worktreeIsolation` or commit `.mcp.json` |
| `ToolCatalog.CallTool` mangles params | Wrapper corrupts certain keys | Use direct tool name in `tools/call` |
| Kraken AddOrder rejected (`EGeneral:Invalid arguments`) | `ordertype` param corrupted by ToolCatalog | Use direct `CloudTools::KrakenRequest` call |
| Model returns empty content | Reasoning model consumed all tokens in thinking | Increase `max_tokens` to 4096+ |
| Paperclip agents not waking | `heartbeat.enabled: false` + no assigned tasks | Assign tasks via Paperclip UI or API |
| Paperclip API returns NullReferenceException | Process corrupted state | Restart Paperclip: stop `node` process, run `paperclip run` |
| SindByte crashes (Access Violation) | Memory corruption or heavy load | Restart SindByte; consider watchdog script |

---

## 12. Security Notes

1. **Localhost Only**: All services bind to `127.0.0.1` by default. Do not expose Paperclip, SindByte, or LM-Studio ports to the internet without authentication.
2. **API Keys**: Kraken, OpenAI, and other keys are encrypted in `mcp_config.json` but are decrypted in memory at runtime.
3. **Trading Safety**: Set `CloudToolsKrakenTradingEnabled: false` until you are ready for live trading. This blocks all order placement endpoints even if the agent requests them.
4. **Agent Permissions**: `SystemTools::ExecuteCommand` and `SystemTools::RunPowerShell` can execute arbitrary code. Keep these disabled (`level: 0`) for autonomous agents.
5. **LM-Studio Auth**: If you disable token auth, anyone on your local machine can use the LM-Studio API. This is acceptable for single-user workstations.

---

## Related Files in This Distribution

| File | Purpose |
|------|---------|
| `README.txt` | Quick-start summary |
| `.mcp.json` | MCP client config for Paperclip agents |
| `setup-mcp.ps1` | PowerShell deploy script for .mcp.json |
| `Paperclip-Agent-Config.txt` | Agent adapter JSON snippets |
| `CHANGELOG.md` | Version history and repair notes |
| `Trading-Firm-Technical-Guide.md` | Architecture guide for building trading desks |

---

*Document maintained by SindByte Distribution Team*
