MoContext Human Guide

Use this page to help an AI client remember and use MoContext. Copy the short bootstrap into persistent custom instructions, or copy the longer session prompt into a single chat when you want to steer that session.

Custom Instructions Bootstrap

Paste this into an AI client's custom instructions so new sessions know to check for MoContext.

One-Session Prompt

Paste this into a chat when you want the current session to actively use MoContext.

Appendix: how MoContext works

Audience: Technical users and admins. Covers architecture, data flows, HTTP endpoints, and MCP tools. For internal codebase detail (service layer, file map, WinForms threading, startup sequence) see MoContext_Codebase.html.

1. What Is MoContext?

MoContext is a single-executable, local-loopback server that gives AI agents (and developers) grounded source retrieval from the MoSearch full-text index, a lightweight activity journal, explicit SaveContext/LoadContext digests, durable indexed memory files, and a recent working-set signal from MoSearch UriHistory. It exposes the same surface over two parallel entry points — a classic REST HTTP API and a Model Context Protocol (MCP) endpoint — and ships a WinForms system-tray dashboard for monitoring.

Key design answers up-front:
What layer reads the DB?MoContextRepository owns all MoContext.db access. EvidencePackService opens MoSl.db directly (read-only). No other service touches a database.
Does MCP build on top of HTTP? — No. MCP tools and HTTP handlers are parallel entry points wired into the same DI container. Both call the same services; neither uses the other as a transport layer.
Is MoSearch the base layer? — Yes. MoSl.db is the read-only FTS database that MoSearch builds and owns. MoContext.db lives beside it in the same AppData folder as MoContext's own write-side store.
Where does SaveContext live? — Saved digests are Markdown files under MoContext\weeklyDigest\. MoSearch indexes them, so LoadContext <keyword> uses the same index path as normal source retrieval.

2. System Overview

MoContext sits between AI clients and the local filesystem. MoSearch's indexer is a fully separate process that writes MoSl.db; MoContext only reads it. The MoSearch Search UI is the original user-facing query tool — it reads the same MoSl.db and opens source files directly; HTTP and MCP are two new avenues into that same underlying index.

Diagram 1 — Top-level system
AI Clients Windsurf · VS Code Codex · custom agents Human Browser wwwroot Test UI localhost:43210 MoSearch Search UI (human users) queries FTS index · browses / opens files original primary interface to MoSearch MoContext.Server.exe (net10-windows, WinExe) HTTP /v1/... (Minimal API) health · capabilities · evidence-pack browse · search · full-file · file-window session · activity · saved-pack · events Program.cs (route handlers) MCP /mcp (Streamable HTTP) initialize · tools/list · tools/call 15 auto-discovered tools Stateful sessions via Mcp-Session-Id MoContextMcpTools.cs WinForms Tray UI STA thread (separate) 3s refresh timer HTTP + MCP cards Recent activity list MoContextStatusForm.cs MoSearch AutoIndexer (background process) crawls · normalises · tokenises builds FTS index into MoSl.db reads/writes Local Source Files MoContext.db (Activity / Events) READ + WRITE by MoContext Local Source Files read by MoContext · read/write by MoSearch MoSl.db (MoSearch FTS) READ ONLY from MoContext · WRITE by AutoIndexer HTTP / MCP HTTP /v1/ read/write reads EvidencePackService reads DashboardService builds/writes reads/writes files queries FTS views / opens files

3. HTTP vs MCP — Parallel Entry Points

This is the most important structural point. MCP is not layered on top of HTTP. Both entry points call the same service singletons through ASP.NET Core DI. The MCP SDK registers a handler at /mcp alongside the /v1/ route handlers — they are peers, not stacked.

Diagram 2 — Entry point architecture
ASP.NET Core Middleware Pipeline Body size guard → Exception→JSON mapper → API call tracker (fire-and-forget events) → Static files → Route dispatcher HTTP /v1/ route handlers Program.cs (lambda handlers, minimal API) Records api_call events via middleware Optional Bearer token auth on write endpoints MCP /mcp tool handlers MoContextMcpTools.cs (static methods, [McpServerTool]) Records mcp_transport events via middleware Records mcp_tool_call events inside each tool ↓ both call the same singletons via DI ↓ Service Layer (ASP.NET Core DI singletons) MoContextRepository Sessions, activity, saved packs, events EvidencePackService FTS search, browse, evidence windows FileWindowService Reads source files from disk RetrievalService Validation only (no DB access) DashboardService Builds DashboardSnapshot for WinForms UI only

4. Database Architecture

MoContext works with two SQLite databases. They typically live in the same %LOCALAPPDATA%\Meauxsoft\Mo-Search<ver>\ AppData folder but are structurally independent. MoSearch owns and writes MoSl.db; MoContext only reads it. MoContext owns and reads/writes MoContext.db.

MoSl.db = the base layer. MoSearch's indexer built this. It contains the full-text search tables (ftsWord_, fwc), file Uri/Extension metadata, and FTS loader type flags. MoContext uses these to execute ranked evidence-pack queries. It never writes a single byte here.

MoContext.db = the side layer. MoContext creates this from scratch on first run. It persists the activity journal, sessions, saved packs, and telemetry events. It has no dependency on MoSearch's schema.
Diagram 3 — Database ownership and access
MoSl.db (MoSearch FTS Index) READ ONLY — written by MoSearch.exe indexer ftsWord_ · fwc (full-text search partitions) Uri (FileID → path, loader type, flags) Extension (ext → ExtID) FtsApp (application metadata) Accessed by: EvidencePackService (evidence-pack · search · browse) Also health-probed by: MoContextRepository (read-only connectivity test only) MoContext.db (Activity Store) READ + WRITE — owned entirely by MoContext session (session_id, started_at, client_name) activity_log (id, session_id, topic_key, summary_text) saved_pack (id, title, topic_key, query_text) event (timestamp, event_type, event_key, data) schema_version (version, applied_at) Accessed exclusively by: MoContextRepository WAL mode enabled — concurrent readers don't block writer Location: %LOCALAPPDATA%\Meauxsoft\<ProductFolder>\MoContext.db

5. HTTP Endpoints GET/POST /v1/...

Read (no auth required)

Method + PathDescription / ParametersExample
GET /v1/health Returns compact liveness/readiness: server version, status, database readiness, indexed-extension count, and warnings. Safe to poll at any time. Use diagnostics when you need runtime paths or deployment provenance.
GET /v1/capabilities Returns all configured budgets: max_files, max_windows_per_file, context_lines, max_total_lines, max_total_chars, and supported search modes. Call once at session start to understand server limits before querying.
GET /v1/activity/recent Activity log entries newest-first. Params: days, session_id, topic_key, q (substring search within summary_text), limit. All params optional and combinable.
GET /v1/activity/briefing Plain-text summary of recent activity formatted for AI context injection. Params: days, max_chars, topic_key.
GET /v1/activity/topics Lists active topic_key slugs with entry counts — useful for discovering ongoing work threads. Params: days, q, limit.
GET /v1/context/search Ranked file search without reading source text — faster than evidence-pack when you only need to discover which files contain a query. mode: keyword (any word) or phrase (exact order). Returns files[]{path, rank, loader_family}. Params: query, mode, max_files, path_filter, filename, working_dir (scopes results to that directory; echoed back as scope_applied).
GET /v1/context/browse Lists recently indexed files ordered by recency — no query required, good for project discovery. Returns files[]{path, indexed_at, loader_family, word_count}. Params: limit, path_filter (e.g. src\Services), filename (e.g. .cs), working_dir (scopes results to that directory; echoed back as scope_applied).
GET /v1/context/find-files Canonical file-discovery route (2026-07 redesign; /v1/context/search and /v1/context/browse remain as aliases). With query: ranked search. Without: recently indexed browse. With hot_hours/warm_days: the hot/warm working set. Also accepts mode, max_files, path_filter, filename, working_dir. The response mode field says which form was returned. -
GET /v1/context/evidence-pack Retrieves bounded source-code windows for a query. Returns files[]{path, windows[]{lines[]{line_number, text}, hit_line}}. Params: query, mode (keyword/phrase/all), max_files, max_windows_per_file, context_lines, path_filter, filename, working_dir (scopes results to that directory; echoed back as scope_applied).
POST /v1/context/file-window Reads a focused line window from a file by path and center line. Body: { path, line, before?, after? }. Returns the surrounding lines with line numbers.
POST /v1/context/full-file Reads a full file or a specific line range. Body: { path, start_line?, end_line? }. Gated by AllowedRoots config. Truncates at max_total_lines.
POST /v1/context/read-file Canonical file-read route (2026-07 redesign; file-window and full-file remain as aliases). Body: { path, start_line?, end_line?, line?, before?, after? } — whole file, range, or focused window around line. -
GET /v1/events Raw event log (api_call, mcp_transport, mcp_tool_call, service_lifecycle entries). Params: days, event_type, event_key, limit.
GET /v1/events/summary Aggregated event counts grouped by event_key. Useful for usage analytics and auditing which endpoints or tools are called most.
GET /v1/saved-pack Lists saved pack metadata (title, topic_key, query_text, created_at) newest first. Params: topic_key (optional filter), limit.
GET /v1/saved-pack/{id} Retrieves one saved pack entry by numeric ID.
GET /v1/context/working-set Returns compact MoSearch UriHistory hot/warm metadata for recently active files. This is path metadata only; use follow-up retrieval tools for file content. -
GET /v1/context/digest Loads recent saved context digests, or searches digest Markdown with q. Plain recent loads include a compact working-set section; keyword search stays focused on digest matches. Params include max_chars and max_matches; responses report truncation and omitted counts. -
GET /v1/context/digest/{id} Retrieves one full saved context digest by id. -

Write (optional Bearer auth)

Method + PathDescription / ParametersExample
POST /v1/session/start Creates a new session and returns its session_id. Body: { client_name? }. Kept for one release for old scripts — new callers should omit it and pass client_name on /v1/activity instead (folds into the ad-hoc session id).
POST /v1/activity Records a work-checkpoint note. Body: { session_id?, summary_text, topic_key?, next_step_text?, query_hint?, client_name? }. session_id is optional; if omitted, an ad-hoc session is auto-generated and returned, and client_name (if given) folds into the ad-hoc id (e.g. sess-adhoc-windsurf). summary_text is 1–3 sentences of completed work (not what comes next).
POST /v1/context/digest Saves a structured SaveContext digest as one Markdown file under MoContext\weeklyDigest. Body (schema v2): { summary, major_work?, decisions_v2?, findings?, pending_work?, files?, tags?, decisions?, open_questions?, session_id? }. Thin digests (summary under 200 chars with no major_work and no decisions) are rejected. Use only for explicit long-term memory saves. -
POST /v1/saved-pack Saves pack metadata. Source excerpts are never stored — always re-retrieved fresh from the index. Body: { title (required), topic_key?, summary_text?, query_text? }. Saved-pack routes are kept for one release; prefer record_activity with a query_hint.
POST /v1/context/evidence-pack Write variant of the evidence-pack endpoint. Accepts a JSON body with all evidence-pack params, plus an optional activity_note field to record a checkpoint in the same call.
POST /v1/admin/shutdown Gracefully stops the MoContext server process. Protected by Bearer token if AuthToken is configured.
POST /v1/admin/show-window Brings the WinForms dashboard to foreground. Also used by the single-instance check at startup to surface an already-running instance.

Every /v1/ request records an api_call event (fire-and-forget). Every /mcp request records an mcp_transport event. Individual MCP tools also record mcp_tool_call events.

6. MCP Tools (auto-discovered from MoContextMcpTools.cs)

MoContext exposes 15 MCP tools after the 2026-07 redesign (tool merges and deletions). Orientation and context-file tools: get_server_summary (embeds capabilities and context paths), get_usage_guide, get_health, get_diagnostics, list_context_files, read_context_file, and write_memory_file. Retrieval: find_files (search / browse / working set), get_evidence_pack, and read_file. Continuity and long-term memory: record_activity, get_recent_activity, get_activity_briefing, save_context_digest, and load_context_digest. MCP clients should trust tools/list for the exact current schema. The former saved-pack and start_session tools were removed; their REST routes remain for one release.

Read / retrieval tools

Tool nameDescription / ParametersExample
get_health Return compact MoContext liveness, version, database readiness, indexed-extension count, and warnings. No parameters required. Use get_diagnostics for runtime paths, deployment provenance, database paths, and the full indexed-extension inventory.
get_server_summary One-call orientation: status, version, endpoints, data-source readiness, suggested next calls, plus embedded capabilities (budgets, search modes, recommended flows) and context_paths (sys-doc and memory folder locations). No parameters. Replaces the former get_capabilities and get_context_paths tools.
find_files The one tool for file discovery — replaces search_context, browse_context, and get_working_set. With query: ranked FTS search (mode keyword or phrase). Without query: recently indexed files in index-recency order. With hot_hours/warm_days (no query): the UriHistory hot/warm working-set grouping. All forms accept working_dir (echoed as scope_applied), path_filter, filename, max_files. Paths and metadata only, no snippets; the response mode field says which form was returned.
get_evidence_pack Retrieve bounded source-code windows for a query. mode: keyword, phrase, or all (recent files, no query filter). working_dir scopes results to files under your working directory (recommended; the response echoes scope_applied; omit to search all indexed roots). context_lines overrides the server default lines before/after each hit. Returns: files[]{path, windows[]{lines[]{line_number, text}, hit_line}}. Example: {query:'session token validation', mode:'phrase', working_dir:'D:\repos\MyApp', path_filter:'Services', max_files:5}.
read_file Read a local file over HTTP-safe MCP transport — replaces get_full_file and get_file_window. Three forms: path alone (whole file), path + start_line/end_line (range), or path + line with optional before/after radii (focused window). Gated by AllowedRoots config. Truncates at max_total_lines.
get_recent_activity Return activity log entries newest-first. All params optional and combinable: days, session_id, topic_key (exact-match slug), q (substring search within summary_text), limit (default 50, max 200), group_by: "topic" (returns a topics[] aggregation with entry counts instead of individual entries — replaces the former get_activity_topics tool). Examples: {days:7, limit:20} for a week recap; {topic_key:'auth-refactor'} for topic history; {group_by:'topic'} for the active-topic overview.
get_activity_briefing Build a plain-text briefing from recent activity for AI context injection. Params: days, max_chars (200–8000, default 2000), topic_key.
load_context_digest Load MoContext long-term memory. With no query, returns recent saved digest records plus a compact working set. With q, searches saved digest Markdown through MoSearch and returns matches/snippets. With id (from a search match), returns that single full digest record — replaces the former get_context_digest tool. Use when the user says LoadContext or LoadContext <keyword>. Budget-capped by max_chars; reports truncation and omitted counts. -

Continuity / write tools

Tool nameDescription / ParametersExample
record_activity Save a work-checkpoint note. session_id is optional; if omitted, an ad-hoc session is auto-generated and returned — pass an optional client_name (e.g. "Windsurf") to fold your client into the ad-hoc id, e.g. sess-adhoc-windsurf (replaces the former start_session tool). summary_text is 1–3 sentences of completed work (not what's next). topic_key groups related work across sessions. next_step_text and query_hint are optional. Only call at meaningful milestones, not after every tool invocation. Example: {summary_text:'Refactored JWT validation into AuthService.', topic_key:'auth-refactor', next_step_text:'Wire AuthService into the login endpoint.'}.
save_context_digest Save a structured SaveContext digest as one Markdown file under MoContext\weeklyDigest. Params (schema v2): summary required; major_work? (feature, changes, files created/modified, status), decisions_v2? (decision + rationale), findings? (typed gotchas/patterns), pending_work?, plus legacy files?, tags?, decisions?, open_questions?, session_id?. Thin digests are rejected with a retry instruction. Use only when the user says SaveContext or explicitly asks to persist session context. -
write_memory_file Create or update a guarded .md/.txt file under the user-owned MoContext memory folder. Params: relative_path, content, overwrite? (required true to replace an existing file). Will not write to sys or arbitrary paths. -

The former save_pack / list_saved_packs / get_saved_pack and start_session MCP tools were removed in the 2026-07 redesign (saved packs duplicated record_activity's query_hint; sessions fold into record_activity.client_name). Their REST routes below remain for one release.

MCP uses ModelContextProtocol.AspNetCore 1.4.1. Transport: Streamable HTTP with stateful sessions (Mcp-Session-Id header). Protocol version: 2025-11-25. Tools are discovered via WithToolsFromAssembly() — all [McpServerTool] methods in the assembly are registered automatically.

7. Runtime File System Layout

%LOCALAPPDATA%\Meauxsoft\Mo-Search<ver>\
    MoContext.db      ← MoContext writes this (sessions, activity, saved packs, events)
    MoSl.db       ← MoSearch writes this; MoContext reads it (FTS index)
    MoContext_config.json ← user config (seeded from defaults on first run)
    Logs\
        MoContext.log    ← structured log from FileLoggerProvider
    MoContext\
        sys\         ← product-owned installed docs
        memory\      ← user/AI-owned durable notes
        weeklyDigest\  ← SaveContext Markdown digests

%PROGRAMFILES%\Meauxsoft\Mo-Search<ver>\MoContext\
    MoContext.Server.exe  ← single-file self-contained publish (net10-windows, WinExe)
    MoContext.Server.dll
    wwwroot\index.html   ← embedded static test UI

Section 11 (Startup Sequence) — moved to MoContext_Codebase.html.

Generated from MoContext source — MoContext\src\MoContext.Server\docs\MoContext_Overview.html