# WordNook Model Context Protocol (MCP) Server Specification

## 1. Executive Summary

WordNook's core mission is to provide a privacy-first, 100% offline-capable, zero-liability linguistic reference platform. By introducing a **Model Context Protocol (MCP)** server, WordNook expands its capabilities from a human-facing Progressive Web App (PWA) into an on-device linguistic intelligence service for local LLMs and AI agents (such as Ollama, Antigravity, Claude Desktop, Cursor, Zed, and Cline).

### Guiding Tenets:
1. **100% On-Device & Zero-Liability:** The MCP server operates entirely on the local machine over standard input/output (`stdio`). No prompts, queries, or dictionary data are ever transmitted to external servers.
2. **Zero Cloud Infrastructure or API Costs:** All lookups, typo corrections, lemmatizations, and thesaurus queries are executed against local data packs (`public/data/*.json.gz`).
3. **Code Reuse:** Direct reuse of WordNook's existing TypeScript engines:
   - Morphological lemmatizer (`src/services/lemmatizer.ts`)
   - High-performance binary search index (`src/services/trie.ts`)
   - Unicode tokenizer (`src/services/tokenizer.ts`)
   - Standard data schema (`src/types/dictionary.ts`)

---

## 2. Architecture & Communication Protocol

```mermaid
flowchart LR
    subgraph Client ["AI Host Client (Ollama / Claude Desktop / Cursor / Antigravity)"]
        LLM[LLM Agent]
    end

    subgraph MCP ["WordNook MCP Server (Node.js Process)"]
        Transport[stdio Transport / JSON-RPC]
        Router[MCP Server Core]
        Tools[MCP Tools Handler]
        Resources[MCP Resources Handler]
        Prompts[MCP Prompts Handler]
    end

    subgraph Engine ["WordNook Shared Core Engine"]
        SearchIndex[SearchIndex Binary Search]
        Lemmatizer[Morphological Lemmatizer]
        Tokenizer[Unicode Tokenizer]
    end

    subgraph Data ["Local Data Packs"]
        CorePack[public/data/en-core.json.gz]
        MobyPack[public/data/en-moby.json.gz]
        KaikkiPack[public/data/en-kaikki.json.gz]
    end

    LLM <-->|JSON-RPC 2.0 (stdio)| Transport
    Transport <--> Router
    Router --> Tools
    Router --> Resources
    Router --> Prompts

    Tools --> Engine
    Resources --> Engine
    Engine --> Data
```

### Protocol Transports:
- **Primary:** `stdio` (Standard I/O). The host application spawns the WordNook MCP server as a local child process. This provides maximum compatibility, zero port management, and instant process lifecycle binding.
- **Optional (Secondary):** Local Server-Sent Events (SSE / Streamable HTTP) on `localhost` for browser-based AI tooling and multi-client scenarios.

---

## 3. Protocol Surface Area

### 3.1 Tools

| Tool Name | Parameters | Description |
|---|---|---|
| `lookup_word` | `word: string` (required)<br>`packId?: string`<br>`includeEtymology?: boolean` | Looks up the unified definition, phonetic transcription, part-of-speech breakdowns, example sentences, synonyms, and source attribution. Automatically triggers lemmatization if an inflected form is queried (e.g. "quenched" -> "quench"). |
| `search_words` | `query: string` (required)<br>`limit?: number` (default 10)<br>`fuzzy?: boolean` (default true) | Provides instant prefix autocomplete suggestions and typo/fuzzy matches with Levenshtein distance scoring. |
| `find_synonyms` | `word: string` (required)<br>`partOfSpeech?: string`<br>`limit?: number` | Returns verified thesaurus synonyms and antonyms grouped by grammatical role, synthesizing Wordset and Moby Thesaurus datasets. |
| `lemmatize_word` | `word: string` (required) | Analyzes morphological affixes (-ing, -ed, -s, -ies, -ly, -er, -est) to return root lemmas and candidate grammatical forms. |
| `get_word_of_the_day` | `date?: string` (ISO format, optional) | Computes the deterministic, offline Word of the Day for the specified date (or current date), matching the exact web app algorithm. |
| `get_random_word` | `count?: number` (default 1)<br>`minDefinitions?: number` | Returns curated vocabulary words with definitions for creative writing, vocabulary enrichment, or testing. |
| `list_packs` | None | Returns metadata, entry counts, and license attributions for all installed and available data packs, highlighting the active pack. |
| `set_active_pack` | `packId: string` (required) | Switches the active dictionary pack (e.g. `en-kaikki` for comprehensive 380k+ word Wiktionary, or `en-core` for curated starter pack). |

---

### 3.2 Resources

The server exposes contextual data feeds via the custom `wordnook://` URI scheme:

- `wordnook://definitions/{word}`: Detailed markdown or JSON definition document for the requested word.
- `wordnook://thesaurus/{word}`: Full synonym and antonym hierarchy.
- `wordnook://word-of-the-day`: Today's curated word, phonetic guide, and primary definition.
- `wordnook://stats`: Summary of installed vocabulary counts, active pack versions, and engine status.

---

### 3.3 Prompts

WordNook provides curated prompt templates to guide language generation tasks:

1. `vocabulary_enhancer`:
   - Arguments: `text: string`, `tone?: "literary" | "academic" | "plain"`
   - Uses WordNook synonyms and definitions to elevate draft prose while strictly preserving intended meaning.
2. `etymology_and_nuance`:
   - Arguments: `wordA: string`, `wordB: string`
   - Compares subtle distinctions between near-synonyms based on classical etymology and dictionary examples.
3. `word_puzzle_assistant`:
   - Arguments: `pattern: string`, `clue?: string`
   - Helps solve crosswords, anagrams, or rhyme patterns against WordNook's headword vocabulary.

---

## 4. Data Storage & Runtime Memory Strategy

WordNook's existing data packs reside in `public/data/` as compressed `.json.gz` archives:

| Pack | Compressed Size | Uncompressed Size | Strategy in MCP Server |
|---|---|---|---|
| `en-core.json.gz` | ~5.7 MB | ~20 MB | **In-Memory Map & Trie:** Loaded into memory on startup (~40–60 MB RAM). Enables sub-millisecond lookups for 95% of standard queries. |
| `en-moby.json.gz` | ~9.3 MB | ~35 MB | **Lazy-Loaded Memory Map:** Loaded on first invocation of `find_synonyms` or thesaurus queries. |
| `en-kaikki.json.gz` | ~23 MB | ~150 MB | **Indexed SQLite / Seek-Index:** Stored in a lightweight local cache (`~/.cache/wordnook/kaikki.db` or using Node 22+ built-in `node:sqlite`) to avoid consuming >200MB RAM on modest developer machines. |

---

## 5. Directory Structure & File Layout

```
wordnook/
├── bin/
│   └── wordnook-mcp.js             # Executable CLI shebang entry point
├── src/
│   ├── mcp/
│   │   ├── index.ts                # Main MCP server initialization
│   │   ├── transport.ts            # Stdio and optional SSE transport setups
│   │   ├── tools.ts                # Tool handlers with Zod schema validation
│   │   ├── resources.ts            # Resource resolver (wordnook:// scheme)
│   │   ├── prompts.ts              # Prompt templates
│   │   ├── loader.ts               # Local pack reader & decompressor
│   │   └── types.ts                # MCP request/response type definitions
│   └── services/                   # Existing shared services (lemmatizer, trie, tokenizer)
└── tests/
    └── mcp.test.js                 # Automated unit tests for MCP tools and resources
```

---

## 6. Host Integration & Configuration

### 6.1 Claude Desktop (`claude_desktop_config.json`)
```json
{
  "mcpServers": {
    "wordnook": {
      "command": "node",
      "args": ["/path/to/wordnook/bin/wordnook-mcp.js"]
    }
  }
}
```

### 6.2 Antigravity / Cursor / Cline / Zed
```json
{
  "mcpServers": {
    "wordnook": {
      "command": "npx",
      "args": ["-y", "wordnook-mcp"]
    }
  }
}
```

### 6.3 Local LLMs with Ollama
Ollama and WordNook share the exact same philosophy: **100% on-device, zero-cloud, privacy-preserving execution**.

WordNook's MCP server can be wired to Ollama models (e.g. `llama3.1`, `qwen2.5`, `mistral`) through:
1. **Ollama MCP Clients / Bridges** (e.g. `ollama-mcp`, Continue.dev, Open WebUI, or LibreChat):
   ```json
   {
     "name": "wordnook",
     "command": "node",
     "args": ["/path/to/wordnook/bin/wordnook-mcp.js"]
   }
   ```
2. **Direct Ollama Function Calling / Scripting**:
   Calling WordNook MCP tools directly within local agentic Python/TypeScript pipelines using Ollama's native `/api/chat` tools array.
   
This creates a **completely air-gapped, zero-cost, private reference & writing stack** where both the language model and the dictionary intelligence run entirely offline.

---

## 7. Implementation Roadmap

### Phase 1: Foundation & Pack Loader
- Install `@modelcontextprotocol/sdk` and `zod`.
- Create `src/mcp/loader.ts` to decompress and parse `en-core.json.gz` in Node.js.
- Re-export `SearchIndex`, `getLemmas`, and `tokenizeText` for Node.js usage.

### Phase 2: Core Tools Implementation
- Implement `lookup_word` with automatic morphological lemmatization fallback.
- Implement `search_words` with prefix and typo tolerance.
- Implement `find_synonyms` combining Wordset and Moby entries.
- Wire up `stdio` transport in `src/mcp/index.ts` and `bin/wordnook-mcp.js`.

### Phase 3: Resources & Prompts
- Implement `wordnook://` resource schema handlers.
- Implement `vocabulary_enhancer` and `etymology_and_nuance` prompts.

### Phase 4: Testing & Quality Assurance
- Add end-to-end MCP protocol tests in `tests/mcp.test.js` using Node.js built-in test runner.
- Verify sub-10ms lookup benchmarks and memory consumption.

### Phase 5: Documentation & Release
- Update `docs/public/USER_MANUAL.md` with an "AI & MCP Integration" chapter covering Claude Desktop, Cursor, Antigravity, and Ollama.
- Provide ready-to-use Ollama local configuration recipes (for Open WebUI, Continue.dev, and native local tool calling).
- Add `npm run mcp` script to `package.json`.
- Document integration instructions and 100% offline air-gapped usage in `README.md`.
