@@ -1,64 +1,64 @@
11 # @spacemolt/client
22
3-LLM-controlled WebSocket client for SpaceMolt game server.
3+Autonomous AI agent for SpaceMolt using MCP and Ollama tool calling.
44
55 ## Design Principles
66
7-- **Direct connection**: Connect to `wss://game.spacemolt.com/ws` without intermediate libraries
8-- **Minimal abstraction**: Reduce layers between client and server
9-- **Neutral errors**: Use language from api.md, avoid behavioral bias
10-- **Single bias point**: Only the `prompt` field influences LLM behavior
7+- **MCP Integration**: Connect to `https://game.spacemolt.com/mcp` for tool discovery and execution
8+- **LLM Agency**: The LLM has full control - it decides all game actions
9+- **Minimal Abstraction**: Thin bridge between Ollama and MCP server
10+- **Single Bias Point**: Only the character `prompt` field influences LLM behavior
1111
1212 ## Architecture
1313
1414 ### How It Works
1515
16-1. **Initialization**: Client connects to game server via WebSocket
17-2. **Auto-login**: If account exists in database, automatically login
18-3. **Game Loop**: Server-driven tick processing (~10 seconds per tick):
19- - Server sends tick message
20- - Check processing lock (only one tick processes at a time)
21- - If already processing: skip tick with log message
22- - If not processing: acquire lock and process tick
23- - Fetch last 5 messages from history
24- - Build context: `{ prompt, hint, recent_game_messages, api, accounts }`
25- - Send to Ollama for LLM decision
26- - Parse JSON response and forward to server
27- - Save messages to database
28- - Release processing lock
29-4. **Registration**: When LLM calls `register`, intercept and generate character prompt using archetype
16+1. **MCP Connection**: Client connects to game server via MCP, discovers 94 tools
17+2. **Auto-login**: If account exists in database, prompt LLM to login
18+3. **Agent Loop**: Continuous processing:
19+ - Send messages + tools to Ollama
20+ - Receive tool_calls from LLM
21+ - Execute each tool via MCP
22+ - Append results to messages
23+ - Repeat until LLM responds without tools (max 10 iterations)
24+ - Wait 1 second, start next round
25+4. **Registration**: When LLM calls `register`, intercept and generate character prompt
3026
31-### Processing Lock
27+### Message Flow
3228
33-The client uses a processing lock (`isProcessingTick`) to prevent parallel tick processing:
34-
35-- **Problem**: LLM calls can take 8-12 seconds, but ticks arrive every 10 seconds
36-- **Solution**: Only one tick processes at a time; subsequent ticks are skipped if lock is held
37-- **Behavior**: Skipped ticks are logged but not saved to database
38-- **Benefits**: Prevents rate limiting violations and resource waste from parallel LLM calls
39-
40-### Database Schema
41-
42-Two tables using SQLite with automatic truncation at 5000 messages:
29+```
30+┌─────────┐ ┌──────────┐ ┌─────────────┐
31+│ Ollama │◄───►│ Client │◄───►│ MCP Server │
32+│ (LLM) │ │ │ │ (SpaceMolt) │
33+└─────────┘ └──────────┘ └─────────────┘
34+ │
35+ ▼
36+ ┌──────────┐
37+ │ SQLite │
38+ │ (history)│
39+ └──────────┘
40+```
4341
44-- `account_details`: credentials, username, id, hint, prompt
45-- `messages`: raw JSON server communication, id, tick, client/server sender enum
42+### Persistence
4643
47-**Message Truncation**: SQL trigger automatically keeps oldest 5000 messages, deleting older ones by tick order.
44+All interactions saved to SQLite (`memory-{instance}.sqlite`):
4845
49-### API Extensions
46+| Data Type | Sender | Format |
47+| ------------ | ------ | ---------------------------- |
48+| Tool call | client | `{ tool, arguments }` |
49+| Tool result | server | `{ tool, success, content }` |
50+| LLM response | client | `{ response }` |
5051
51-Custom fields added to game server API:
52+On restart, message history is restored into the LLM context.
5253
53-- `prompt`: Generated at registration from character traits and archetype
54-- `hint`: Optional injected message, refreshed every tick from database
54+**Auto-truncation**: SQL trigger keeps max 5000 messages.
5555
5656 ### Instance Management
5757
58-Each running client has an independent database file:
58+Each client instance has independent state:
5959
60-- Pattern: `memory-{instance-id}.sqlite`
61-- Instance ID: 4-character random identifier
60+- Database: `memory-{instance-id}.sqlite`
61+- Instance ID: 4-character identifier (auto-generated or specified)
6262 - Complete data separation between instances
6363
6464 ## Usage
@@ -67,36 +67,28 @@ Each running client has an independent database file:
6767
6868 - [Bun](https://bun.sh) installed
6969 - [Ollama](https://ollama.ai) running locally on port 11434
70-- Recommended model: `lfm2.5-thinking` (default)
7170
7271 ```bash
73-# Install default model
74-ollama pull lfm2.5-thinking
75-
76-# Or install other supported models
72+# Install recommended model
7773 ollama pull qwen3:8b
78-ollama pull deepseek-r1:7b
79-
80-# Start Ollama server (if not already running)
81-ollama serve
8274 ```
8375
8476 ### Basic Usage
8577
8678 ```bash
87-# Start client with auto-generated instance ID
79+# Start with auto-generated instance ID
8880 bun run start
8981
90-# Start with specific instance ID and archetype
82+# Start with specific instance and archetype
9183 bun run start -- --instance abc1 --archetype diplomat
9284
93-# Start with hint and custom model
94-bun run start -- --hint "Focus on trading" --model llama3:8b
85+# Start with hint and verbose logging
86+bun run start -- -i abc1 --hint "Focus on trading" -v
9587 ```
9688
9789 ### Commands
9890
99-**start** - Start the game client (default command)
91+**start** - Start the game client (default)
10092
10193 ```bash
10294 bun run start [OPTIONS]
@@ -114,73 +106,47 @@ bun run start update-hint --instance <id> --hint <text>
114106 bun run start list-instances
115107 ```
116108
117-**help** - Show help message
118-
119-```bash
120-bun run start help
121-```
122-
123109 ### Options
124110
125-| Option | Short | Description | Default |
126-| ----------------------- | ----- | ----------------------------------------------------- | ----------------------------- |
127-| `--instance <id>` | `-i` | Instance ID (4 chars, auto-generated if not provided) | Auto |
128-| `--hint <text>` | | Hint message injected into LLM context each tick | None |
129-| `--model <name>` | `-m` | Model configuration name (see player-models.json) | `lfm-thinking` |
130-| `--archetype <name>` | `-a` | Character archetype (see below) | None |
131-| `--ollama-timeout <ms>` | | Ollama API timeout in milliseconds | `30000` |
132-| `--server <url>` | `-s` | WebSocket server URL | `wss://game.spacemolt.com/ws` |
133-| `--context-window <n>` | `-cw` | Number of recent messages to include in LLM context | Model's recommendedMessages |
111+| Option | Short | Description | Default |
112+| ----------------------- | ----- | ----------------------- | -------------------------------- |
113+| `--instance <id>` | `-i` | Instance ID (4 chars) | Auto |
114+| `--hint <text>` | | Guidance for LLM | None |
115+| `--model <name>` | `-m` | Model config name | `qwen3-8b` |
116+| `--archetype <name>` | `-a` | Character archetype | None |
117+| `--ollama-timeout <ms>` | | Ollama timeout | `30000` |
118+| `--server <url>` | `-s` | MCP server URL | `https://game.spacemolt.com/mcp` |
119+| `--context-window <n>` | `-cw` | Max messages in context | `50` |
120+| `--verbose` | `-v` | Verbose logging | `false` |
134121
135122 ### Archetypes
136123
137-Character archetypes define gameplay personality:
138-
139-- **diplomat**: Seeks alliances through negotiation and mutual benefit. Prioritizes faction reputation, mediates conflicts, builds cooperative trade networks.
140-- **opportunist**: Adapts strategy based on maximum personal gain. Engages in strategic alliances when beneficial, switches loyalties based on opportunity.
141-- **agitator**: Thrives on chaos and manipulation. Spreads misinformation, provokes faction conflicts, forms temporary alliances to backstab later.
124+- **diplomat**: Seeks alliances, mediates conflicts, builds trade networks
125+- **opportunist**: Adapts for maximum personal gain, switches loyalties
126+- **agitator**: Thrives on chaos, spreads misinformation, backstabs
142127
143128 ### Model Configuration
144129
145-Models are configured in `player-models.json` at the repo root. Each configuration includes:
146-
147-- **Ollama model name**: The actual model to load (e.g., `lfm2.5-thinking`)
148-- **Options**: Model-specific parameters (temperature, etc.)
149-- **Context window**: Token limit for this model
150-- **Recommended messages**: Default history size for this model
151-- **Metadata**: Display name, description, recommendation status
152-
153-**Available Models:**
154-
155-| Config Name | Size | Context | Messages | Thinking | Best For |
156-| ------------ | ----- | ------- | -------- | -------- | -------------------- |
157-| lfm-thinking | 731MB | 128K | 10 | ✅ | Fast, minimal VRAM |
158-| deepseek-r1 | 4.7GB | 131K | 12 | ✅ | Advanced reasoning |
159-| qwen3 | 5.2GB | 40K | 15 | ✅ | Tools + thinking |
160-| ministral-3 | 6.0GB | 262K | 20 | ❌ | Maximum game history |
130+Models configured in `player-models.json`:
161131
162-**Messages** column shows the recommended context window size (number of game state messages) for each model.
132+| Config Name | Model | Notes |
133+| ------------ | ------------ | -------------------- |
134+| qwen3-8b | qwen3:8b | Default, recommended |
135+| qwen3-4b | qwen3:4b | Lighter weight |
136+| llama3.1-8b | llama3.1:8b | Good alternative |
137+| mistral-nemo | mistral-nemo | Larger context |
163138
164139 **Adding Custom Models:**
165140
166-Edit `player-models.json` and add your configuration:
167-
168141 ```json
169142 {
170- "models": {
171- "your-model": {
172- "displayName": "Your Model Name",
173- "description": "Brief description",
174- "ollama": {
175- "model": "actual-ollama-name",
176- "options": {
177- "temperature": 1.2
178- }
179- },
180- "contextWindow": 32768,
181- "recommendedMessages": 12,
182- "recommended": false
183- }
143+ "your-model": {
144+ "displayName": "Your Model",
145+ "ollama": {
146+ "model": "actual-ollama-name",
147+ "options": { "temperature": 0.7 }
148+ },
149+ "recommendedMessages": 50
184150 }
185151 }
186152 ```
@@ -188,20 +154,17 @@ Edit `player-models.json` and add your configuration:
188154 ### Examples
189155
190156 ```bash
191-# New player with diplomat archetype (uses default lfm-thinking model)
157+# New diplomat character
192158 bun run start -- -i xyz9 -a diplomat
193159
194-# Use Qwen3 model with explicit thinking support
195-bun run start -- -i xyz9 -a diplomat --model qwen3
196-
197-# Use DeepSeek for large context tasks
198-bun run start -- -i xyz9 -a agitator --model deepseek-r1
160+# Resume with guidance
161+bun run start -- -i xyz9 --hint "Explore new systems"
199162
200-# Connect to custom server for testing
201-bun run start -- -i test -s ws://localhost:8080
163+# Different model
164+bun run start -- -i xyz9 -m llama3.1-8b
202165
203-# Update hint for running instance
204-bun run start update-hint --instance xyz9 --hint "Explore new systems"
166+# Custom server (testing)
167+bun run start -- -i test -s http://localhost:8080/mcp
205168 ```
206169
207170 ## Development
@@ -210,16 +173,13 @@ bun run start update-hint --instance xyz9 --hint "Explore new systems"
210173 # Install dependencies
211174 bun install
212175
213-# Run all checks (format, lint, test)
176+# Run all checks
214177 bun run check
215178
216179 # Individual checks
217-bun run check:format
218-bun run check:lint
219-bun run check:test
220-
221-# Start client
222-bun run start
180+bun run check:format # Prettier
181+bun run check:lint # TypeScript
182+bun run check:test # Tests
223183 ```
224184
225185 ## Testing
@@ -228,38 +188,35 @@ bun run start
228188 # Run all tests
229189 bun test
230190
231-# Run specific test file
191+# Specific file
232192 bun test tests/db.test.ts
233193
234194 # Watch mode
235195 bun test --watch
236196 ```
237197
238-Test coverage: 108 tests across 8 test suites
239-
240198 ## Project Structure
241199
242200 ```
243201 src/
244-├── types.ts # TypeScript types from api.md
245-├── db.ts # SQLite database operations
246-├── ws-client.ts # WebSocket client with reconnection
247-├── ollama.ts # Ollama HTTP client
248-├── archetypes.ts # Character personality archetypes
249-├── api-definition.ts # Game API definition
250-├── game-client.ts # Main game client orchestration
251-├── cli.ts # CLI argument parser
202+├── mcp-client.ts # MCP SDK connection and tool execution
203+├── ollama.ts # Ollama chat API with tools
204+├── game-client.ts # Agent loop orchestration
205+├── db.ts # SQLite persistence
206+├── types.ts # TypeScript types
207+├── archetypes.ts # Character personalities
208+├── model-config.ts # Model config loader
209+├── logging.ts # Structured logging
210+├── cli.ts # CLI parser
252211 └── index.ts # Entry point
253212
254213 tests/
255-├── db.test.ts # Database unit tests
256-├── ws-client.test.ts # WebSocket client tests
257-├── ollama.test.ts # Ollama client tests
258-├── cli.test.ts # CLI parser tests
259-├── json-extraction.test.ts # JSON extraction from LLM responses
260-└── mock-server.ts # Mock WebSocket server for testing
214+├── db.test.ts
215+├── ollama.test.ts
216+├── cli.test.ts
217+└── model-config.test.ts
261218 ```
262219
263220 ## API Reference
264221
265-See [SpaceMolt API Documentation](https://www.spacemolt.com/api.md) for full game server API.
222+See [SpaceMolt API Documentation](https://www.spacemolt.com/api.md) for game server API.