prism-mcp-server 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/.gitmodules +3 -0
  2. package/Dockerfile +30 -0
  3. package/LICENSE +21 -0
  4. package/README.md +970 -0
  5. package/benchmark.ts +172 -0
  6. package/call_chrome_mcp.py +96 -0
  7. package/docker-compose.yml +67 -0
  8. package/execute_via_chrome_mcp.py +133 -0
  9. package/gmail_auth_test.py +29 -0
  10. package/gmail_list_latest_5.py +27 -0
  11. package/index.ts +34 -0
  12. package/list_chrome_tools.py +70 -0
  13. package/package.json +64 -0
  14. package/patch_cgc_mcp.py +90 -0
  15. package/repomix-output.xml +9 -0
  16. package/run_server.sh +9 -0
  17. package/server.json +78 -0
  18. package/src/config.ts +85 -0
  19. package/src/server.ts +627 -0
  20. package/src/tools/compactionHandler.ts +313 -0
  21. package/src/tools/definitions.ts +367 -0
  22. package/src/tools/handlers.ts +261 -0
  23. package/src/tools/index.ts +38 -0
  24. package/src/tools/sessionMemoryDefinitions.ts +437 -0
  25. package/src/tools/sessionMemoryHandlers.ts +774 -0
  26. package/src/utils/braveApi.ts +375 -0
  27. package/src/utils/embeddingApi.ts +97 -0
  28. package/src/utils/executor.ts +105 -0
  29. package/src/utils/googleAi.ts +107 -0
  30. package/src/utils/keywordExtractor.ts +207 -0
  31. package/src/utils/supabaseApi.ts +194 -0
  32. package/supabase/migrations/015_session_memory.sql +145 -0
  33. package/supabase/migrations/016_knowledge_accumulation.sql +315 -0
  34. package/supabase/migrations/017_ledger_compaction.sql +74 -0
  35. package/supabase/migrations/018_semantic_search.sql +110 -0
  36. package/supabase/migrations/019_concurrency_control.sql +320 -0
  37. package/supabase/migrations/020_multi_tenant_rls.sql +459 -0
  38. package/test_cross_mcp.js +393 -0
  39. package/test_mcp_schema.js +83 -0
  40. package/tests/test_knowledge_system.js +319 -0
  41. package/tsconfig.json +16 -0
  42. package/vertex-ai/test_claude_vertex.py +78 -0
  43. package/vertex-ai/test_gemini_vertex.py +39 -0
  44. package/vertex-ai/test_hybrid_search_pipeline.ts +296 -0
  45. package/vertex-ai/test_pipeline_benchmark.ts +251 -0
  46. package/vertex-ai/test_realworld_comparison.ts +290 -0
  47. package/vertex-ai/verify_discovery_engine.ts +72 -0
package/README.md ADDED
@@ -0,0 +1,970 @@
1
+ # Prism MCP โ€” Enterprise-Grade AI Agent Memory & Multi-Engine Search
2
+
3
+ > Production-grade **Model Context Protocol (MCP)** server with **persistent session memory**, **multi-tenant RLS**, **semantic search (pgvector)**, **optimistic concurrency control**, **MCP Prompts & Resources**, **brain-inspired knowledge accumulation**, and **multi-engine search** (Brave + Vertex AI) with sandboxed code transforms and Gemini-powered analysis.
4
+
5
+ ---
6
+
7
+ ## What's New in v1.5.0
8
+
9
+ | Feature | Description |
10
+ |---|---|
11
+ | ๐Ÿง  **MCP Prompts** | `/resume_session` slash command โ€” inject context before the LLM thinks. Zero tool calls. |
12
+ | ๐Ÿ“Ž **MCP Resources** | Attach `memory://project/handoff` via paperclip โ€” auto-refresh on state changes. |
13
+ | ๐Ÿ”’ **Optimistic Concurrency** | Version-tracked handoffs prevent multi-client data loss. |
14
+ | ๐Ÿงน **Ledger Compaction** | Gemini-powered rollup of old entries โ€” keeps ledger lean with soft-delete archiving. |
15
+ | ๐Ÿ” **Semantic Search** | pgvector embeddings โ€” find sessions by meaning, not just keywords. |
16
+ | โ™ป๏ธ **Resource Subscriptions** | Attached memory auto-refreshes when handoff state changes mid-conversation. |
17
+ | ๐Ÿ›ก๏ธ **Multi-Tenant RLS** | `PRISM_USER_ID` env var โ€” Row Level Security isolates data per user on shared Supabase. |
18
+
19
+ ---
20
+
21
+ ## How Prism MCP Compares
22
+
23
+ | Capability | **Prism MCP** | **Mem0** | **Zep** | **Basic Memory** |
24
+ |---|---|---|---|---|
25
+ | **Architecture** | MCP-native (single npm package) | Standalone service + MCP adapter | Standalone service + API | MCP-native (local files) |
26
+ | **Storage** | Supabase (PostgreSQL) | Hybrid (vector + graph DBs) | PostgreSQL + Neo4j | Local markdown files |
27
+ | **Cold Start Fix** | โœ… MCP Prompts + Resources inject context before LLM thinks | โŒ Requires tool call | โŒ Requires tool call | โŒ Requires tool call |
28
+ | **Progressive Loading** | โœ… quick / standard / deep levels | โŒ All-or-nothing | โŒ Fixed context window | โŒ All-or-nothing |
29
+ | **Semantic Search** | โœ… pgvector + HNSW | โœ… Qdrant/Chroma | โœ… Built-in embeddings | โŒ No embeddings |
30
+ | **Concurrency Control** | โœ… OCC with version tracking | โŒ Last write wins | โŒ Last write wins | โŒ Single user only |
31
+ | **Auto-Compaction** | โœ… Gemini-powered rollup | โŒ Manual management | โœ… Auto-summarization | โŒ No compaction |
32
+ | **Resource Subscriptions** | โœ… Live refresh on state change | โŒ Not MCP-native | โŒ Not MCP-native | โŒ Not supported |
33
+ | **Knowledge Accumulation** | โœ… Auto-extracted keywords + categories | โœ… User/agent memories | โœ… Fact extraction | โŒ Manual tagging |
34
+ | **Infrastructure Cost** | Free tier (Supabase + Gemini) | Free tier available, paid for scale | Self-hosted or cloud ($$$) | Free (local only) |
35
+ | **Setup Complexity** | 2 env vars (Supabase URL + Key) | Docker + API keys + vector DB | Docker + PostgreSQL + Neo4j | No setup needed |
36
+ | **Multi-Project** | โœ… Built-in project isolation | โœ… User-scoped memories | โœ… Session-scoped | โŒ Single knowledge base |
37
+ | **Multi-Tenant RLS** | โœ… user_id + RLS policies | โŒ Not built-in | โŒ Not built-in | โŒ Single user only |
38
+
39
+ > **When to choose Prism MCP**: You want MCP-native memory with zero infrastructure overhead, progressive context loading, and enterprise features (OCC, compaction, semantic search) that work directly in Claude Desktop โ€” without running separate services.
40
+
41
+ ---
42
+
43
+ ## Overview
44
+
45
+ Prism MCP is a unified AI agent platform with two core pillars:
46
+
47
+ 1. **Session Memory & Knowledge System** โ€” Persistent session memory with progressive context loading, MCP Prompts for cold-start fix, MCP Resources for zero-tool-call context, semantic search via pgvector embeddings, optimistic concurrency control, auto-compaction, cross-project knowledge transfer, and selective memory pruning
48
+ 2. **Multi-Engine Search & Analysis** โ€” Brave Search + Vertex AI Discovery Engine hybrid pipeline with 94% context reduction, Gemini research analysis, and sandboxed code transforms
49
+
50
+ | Capability | Implementation |
51
+ |---|---|
52
+ | **Session Memory & Knowledge** | Progressive context loading (quick / standard / deep), MCP Prompts (/resume_session), MCP Resources (memory://), OCC (version tracking), ledger compaction, semantic search (pgvector), knowledge accumulation, and memory pruning via Supabase |
53
+ | **Multi-Engine Search** | Brave Search (real-time web) + Vertex AI Discovery Engine (curated enterprise index) with hybrid merge/dedup pipeline |
54
+ | **MCP Server Architecture** | Multi-tool server with `@modelcontextprotocol/sdk`, structured request handling, MCP Prompts, Resources with subscriptions, and extensible tool registration |
55
+ | **LLM Integration** | Claude Desktop, Google Gemini, and Claude-on-Vertex AI with secure prompt patterns |
56
+ | **API Orchestration** | Brave Search, Gemini, Gmail, Chrome DevTools Protocol, GCP Discovery Engine, and Supabase REST APIs |
57
+ | **Code-Mode Transforms** | Sandboxed JavaScript extraction over raw JSON/CSV payloads โ€” 85-95% token reduction |
58
+ | **Security & IP Protection** | GCP Application Default Credentials, OAuth 2.0, encrypted credential management, env-based secrets |
59
+ | **Testing & Validation** | Cross-MCP integration tests, Vertex AI verification scripts, schema validation, and benchmarks |
60
+
61
+ ## Quick Start
62
+
63
+ Get the MCP server running with Claude Desktop in under 2 minutes:
64
+
65
+ ### 1. Clone & Build
66
+
67
+ ```bash
68
+ git clone https://github.com/dcostenco/prism-mcp.git
69
+ cd prism-mcp
70
+ npm install
71
+ npm run build
72
+ ```
73
+
74
+ ### 2. Add to Claude Desktop
75
+
76
+ Copy this into your `claude_desktop_config.json` (replace the paths and API keys):
77
+
78
+ ```json
79
+ {
80
+ "mcpServers": {
81
+ "prism-mcp": {
82
+ "command": "node",
83
+ "args": ["/absolute/path/to/BCBA/build/server.js"],
84
+ "env": {
85
+ "BRAVE_API_KEY": "your-brave-api-key",
86
+ "GOOGLE_API_KEY": "your-google-gemini-key",
87
+ "SUPABASE_URL": "https://your-project.supabase.co",
88
+ "SUPABASE_KEY": "your-supabase-anon-key",
89
+ "PRISM_USER_ID": "your-unique-user-id"
90
+ }
91
+ }
92
+ }
93
+ }
94
+ ```
95
+
96
+ > **Note:** Only `BRAVE_API_KEY` is required. All other keys are optional and enable additional tools (Gemini analysis, session memory, etc.)
97
+
98
+ ### 3. Restart Claude Desktop
99
+
100
+ That's it โ€” all tools are now available in Claude.
101
+
102
+ ### Alternative: Local PostgreSQL (Docker)
103
+
104
+ If you prefer local PostgreSQL instead of Cloud Supabase:
105
+
106
+ ```bash
107
+ docker compose up -d # Start PostgreSQL + PostgREST
108
+ # Run all migrations:
109
+ cat supabase/migrations/*.sql | docker compose exec -T db psql -U prism -d prism_mcp
110
+ ```
111
+
112
+ Then set `SUPABASE_URL=http://localhost:3000` in your MCP config.
113
+
114
+ ---
115
+
116
+ ## Architecture
117
+
118
+ ```mermaid
119
+ graph TB
120
+ Client["AI Client<br/>(Claude Desktop / Cursor / Windsurf)"]
121
+ MCP["Prism MCP Server<br/>(TypeScript)"]
122
+
123
+ Client -- "MCP Protocol (stdio)" --> MCP
124
+
125
+ MCP --> Brave["Brave Search API<br/>Web + Local + AI Answers"]
126
+ MCP --> Gemini["Google Gemini API<br/>Research Paper Analysis"]
127
+ MCP --> Vertex["Vertex AI Discovery Engine<br/>Enterprise Search"]
128
+ MCP --> Sandbox["QuickJS Sandbox<br/>Code-Mode Transforms"]
129
+ MCP --> Supabase["Supabase<br/>Session Memory (Optional)"]
130
+
131
+ Supabase --> Ledger["session_ledger<br/>(append-only log)"]
132
+ Supabase --> Handoffs["session_handoffs<br/>(project state)"]
133
+ Supabase --> Context["get_session_context<br/>(progressive loading<br/>+ knowledge cache)"]
134
+ Supabase --> Knowledge["Knowledge System<br/>(search / forget / cache)"]
135
+
136
+ style Client fill:#4A90D9,color:#fff
137
+ style MCP fill:#2D3748,color:#fff
138
+ style Brave fill:#FB542B,color:#fff
139
+ style Gemini fill:#4285F4,color:#fff
140
+ style Vertex fill:#34A853,color:#fff
141
+ style Sandbox fill:#805AD5,color:#fff
142
+ style Supabase fill:#3ECF8E,color:#fff
143
+ style Knowledge fill:#F6AD55,color:#fff
144
+ ```
145
+
146
+ ### ASCII Architecture (for terminals)
147
+
148
+ ```
149
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” MCP Protocol (stdio) โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
150
+ โ”‚ AI Client โ”‚ โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ MCP Server โ”‚
151
+ โ”‚ (Claude Desktop) โ”‚ โ”‚ (TypeScript + Python) โ”‚
152
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
153
+ โ”‚
154
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
155
+ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚
156
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
157
+ โ”‚ Brave Search โ”‚ โ”‚ Gemini API โ”‚ โ”‚ Gmail OAuth โ”‚ โ”‚ Chrome DevTools โ”‚ โ”‚ Vertex AI Search โ”‚
158
+ โ”‚ (Web + Local) โ”‚ โ”‚ (Analysis) โ”‚ โ”‚ (Data Pipe) โ”‚ โ”‚ (MCP Introspect)โ”‚ โ”‚ (Discovery Engine) โ”‚
159
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
160
+
161
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
162
+ โ”‚ Google Cloud (Vertex AI) โ”‚
163
+ โ”‚ โ”‚
164
+ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
165
+ โ”‚ โ”‚ Discovery โ”‚ โ”‚ Gemini SDK โ”‚ โ”‚ Claude on โ”‚ โ”‚
166
+ โ”‚ โ”‚ Engine / โ”‚ โ”‚ (Vertex AI) โ”‚ โ”‚ Vertex AI โ”‚ โ”‚
167
+ โ”‚ โ”‚ AI Search โ”‚ โ”‚ โ”‚ โ”‚ (Anthropic)โ”‚ โ”‚
168
+ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
169
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
170
+
171
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
172
+ โ”‚ Supabase (Optional) โ”‚
173
+ โ”‚ โ”‚
174
+ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
175
+ โ”‚ โ”‚ session_ โ”‚ โ”‚ session_ โ”‚ โ”‚ get_sessionโ”‚ โ”‚
176
+ โ”‚ โ”‚ ledger โ”‚ โ”‚ handoffs โ”‚ โ”‚ _context() โ”‚ โ”‚
177
+ โ”‚ โ”‚ (append-only)โ”‚ โ”‚ (upsert) โ”‚ โ”‚ (RPC) โ”‚ โ”‚
178
+ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
179
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
180
+ ```
181
+
182
+ ## Core Components
183
+
184
+ ### 1. MCP Server (`src/`, `index.ts`)
185
+
186
+ The backbone of the platform โ€” a TypeScript MCP server that registers and exposes multiple tools via the Model Context Protocol standard.
187
+
188
+ - **Server entry point** with stdio transport binding
189
+ - **Modular tool definitions** with JSON Schema parameter validation
190
+ - **Request handlers** with structured error handling and response formatting
191
+ - **Config management** with environment-variable-driven API key injection
192
+
193
+ ### 2. Vertex AI Applications (`vertex-ai/`)
194
+
195
+ Integration layer connecting Google Cloud's Vertex AI services with the MCP search pipeline, enabling hybrid retrieval and multi-model analysis:
196
+
197
+ | Component | Description | GCP Service |
198
+ |-----------|-------------|-------------|
199
+ | `verify_discovery_engine.ts` | Queries and validates a Discovery Engine search index with structured result parsing | Vertex AI Search / Discovery Engine |
200
+ | `test_gemini_vertex.py` | Gemini model invocation via the Vertex AI Python SDK with ADC authentication | Vertex AI Generative Models |
201
+ | `test_claude_vertex.py` | Claude model deployment via Anthropic's Vertex AI integration with multi-region failover | Claude on Vertex AI (Model Garden) |
202
+
203
+ **Key capabilities:**
204
+ - **Discovery Engine Search** โ€” Document ingestion, index building, and structured query execution via `@google-cloud/discoveryengine` SDK
205
+ - **Multi-model orchestration** โ€” Seamless switching between Gemini and Claude models through the same GCP project
206
+ - **Application Default Credentials (ADC)** โ€” Secure, keyless authentication using `gcloud auth application-default login`
207
+ - **Multi-region failover** โ€” Automatic region rotation for Claude on Vertex AI (`us-east5`, `us-central1`, `europe-west1`)
208
+
209
+ ### Hybrid Search Pipeline: MCP + Vertex AI Discovery Engine
210
+
211
+ The platform's core architectural advantage is combining **real-time web search** (via MCP/Brave) with **enterprise-curated search** (via Vertex AI Discovery Engine) in a unified pipeline:
212
+
213
+ ```
214
+ Query โ”€โ”€โ–บ MCP Server
215
+ โ”œโ”€โ”€ brave_web_search โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Real-time web results
216
+ โ”œโ”€โ”€ Discovery Engine โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Curated enterprise index
217
+ โ””โ”€โ”€ code_mode_transform โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Merged, deduplicated, normalized output
218
+ โ”‚
219
+ gemini_research_paper_analysis
220
+ โ”‚
221
+ Structured analysis (LLM)
222
+ ```
223
+
224
+ **Why a hybrid pipeline?** Each source has distinct strengths โ€” the enhancement comes from combining them, not replacing one with the other:
225
+
226
+ | Dimension | ๐ŸŒ Brave Search (MCP) | ๐Ÿ” Discovery Engine (Vertex AI) | ๐Ÿ”€ Hybrid (Combined) |
227
+ |-----------|----------------------|----------------------------------|----------------------|
228
+ | **Coverage** | Public web โ€” broad, real-time | Curated document index โ€” deep, domain-specific | **Both:** breadth + depth |
229
+ | **Result quality** | Keyword-ranked web pages | ML-ranked with semantic understanding | **Deduplicated, best-of-both** |
230
+ | **Speed** | **~200ms** (live search) | ~900ms (pre-indexed retrieval) | ~2.4s sequential (both stages) |
231
+ | **Context efficiency** | 93% reduction via `code_mode_transform` | 95% reduction (pre-structured data) | 94% overall (71 KB โ†’ 4.1 KB) |
232
+ | **Token savings** | **~10,074 / query** | **~7,087 / query** | Combined: **~17K tokens saved** |
233
+ | **Freshness** | Real-time (seconds old) | Managed re-crawl schedules | Real-time + deep archive |
234
+ | **Model routing** | Single Gemini API key | Multi-model (Gemini + Claude) via GCP | Full model flexibility |
235
+
236
+ The `code_mode_transform` tool is the key performance enabler โ€” it runs sandboxed JavaScript over raw API payloads to extract only the relevant fields before passing data to the LLM, reducing context window usage by **85-95%** (measured via the built-in `benchmark.ts` suite). When combined with Discovery Engine's pre-structured results, the total pipeline achieves significantly lower token consumption compared to raw web scraping approaches.
237
+
238
+ ### Verified Test Results
239
+
240
+ Benchmark data from [`test_pipeline_benchmark.ts`](vertex-ai/test_pipeline_benchmark.ts) (5 queries ร— 3 iterations each):
241
+
242
+ | Metric | ๐ŸŒ Brave (MCP) | ๐Ÿ” Discovery Engine | Hybrid Total |
243
+ |--------|----------------|---------------------|--------------|
244
+ | **Avg latency** | 220ms | 1,193ms | ~1.4s (sequential) |
245
+ | **Avg raw payload** | 42.4 KB | 28.9 KB | 71.3 KB total input |
246
+ | **Avg reduced payload** | 3.0 KB | 1.2 KB | **4.2 KB total** (94% reduction) |
247
+ | **Token savings** | ~10,103 | ~7,097 | **~17,200 tokens saved / query** |
248
+
249
+ End-to-end pipeline results from [`test_hybrid_search_pipeline.ts`](vertex-ai/test_hybrid_search_pipeline.ts):
250
+
251
+ | Pipeline Stage | Results | Latency | Payload |
252
+ |----------------|---------|---------|--------|
253
+ | Stage 1: Brave Web Search | 5 results | 520ms | 24.1 KB raw |
254
+ | Stage 2: Discovery Engine | 5 results | 1,895ms | 23.1 KB raw |
255
+ | Stage 3: Merge & Dedup | **9 unique** (1 duplicate removed) | <1ms | 2.6 KB โ†’ 1.4 KB |
256
+ | Stage 4: Gemini Analysis | Structured summary | 4,919ms | โ€” |
257
+ | **Total Pipeline** | **9 merged results** | **7.3s end-to-end** | **~17K tokens saved** |
258
+
259
+ > *"The web search results provide practical understanding... the Discovery Engine results delve into specialized and cutting-edge topics from arXiv... Together, the sources provide a holistic perspective, bridging established techniques with advanced research."*
260
+ > โ€” Gemini 2.5 Flash analysis output
261
+
262
+ ### Real-World Comparison: Why the Hybrid Pipeline Matters
263
+
264
+ Results from [`test_realworld_comparison.ts`](vertex-ai/test_realworld_comparison.ts) โ€” 3 real AI/ML queries comparing Brave-only vs Hybrid:
265
+
266
+ | Real-World Query | Brave Only | Hybrid | DE Added |
267
+ |-----------------|------------|--------|----------|
268
+ | *RLHF implementation* (AI engineer) | 10 results (2 academic) | 20 results (12 academic) | **+10 unique papers** |
269
+ | *INT8 quantization* (ML deployment) | 10 results (4 academic) | 20 results (14 academic) | **+10 unique papers** |
270
+ | *RAG architecture* (enterprise dev) | 10 results (0 academic) | 20 results (10 academic) | **+10 unique papers** |
271
+
272
+ **Key finding:** For the RAG query, Brave returned **zero academic sources** โ€” only vendor docs (AWS, NVIDIA, IBM, Google Cloud). Discovery Engine filled this gap entirely with 10 peer-reviewed papers including the foundational RAG paper by Lewis et al.
273
+
274
+ | Aggregate Metric | Brave Only | Hybrid | Improvement |
275
+ |-----------------|------------|--------|-------------|
276
+ | **Avg results / query** | 10 | 20 | **+100%** |
277
+ | **Avg academic sources** | 2.0 | 12.0 | **+10 per query** |
278
+ | **Source overlap** | โ€” | 0% | Fully complementary |
279
+ | **Unique DE contributions** | โ€” | 30 total | 10 per query |
280
+
281
+ <details>
282
+ <summary><strong>Sample output: RAG Architecture query โ€” Brave-only vs Hybrid</strong></summary>
283
+
284
+ **Brave Search returned** (0 academic sources):
285
+ ```
286
+ [1] ๐ŸŒ Retrieval-augmented generation - Wikipedia (en.wikipedia.org)
287
+ [2] ๐ŸŒ Retrieval-Augmented Generation (RAG) | Pinecone (pinecone.io)
288
+ [3] ๐ŸŒ Introduction to RAG and Vector Databases (medium.com)
289
+ [4] ๐ŸŒ What is RAG? - AWS (aws.amazon.com)
290
+ [5] ๐ŸŒ RAG and vector databases - GitHub (github.com)
291
+ [6] ๐ŸŒ What is RAG? | Databricks (databricks.com)
292
+ [7] ๐ŸŒ What is RAG? | NVIDIA (nvidia.com)
293
+ [8] ๐ŸŒ What is RAG? | IBM (ibm.com)
294
+ [9] ๐ŸŒ What is RAG? | Confluent (confluent.io)
295
+ [10] ๐ŸŒ What is RAG? | Google Cloud (cloud.google.com)
296
+ ```
297
+
298
+ **Discovery Engine added** (10 academic sources, 0 overlap):
299
+ ```
300
+ [+1] ๐Ÿ“š Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (arxiv.org)
301
+ [+2] ๐Ÿ“š Benchmarking Vector, Graph and Hybrid RAG (arxiv.org)
302
+ [+3] ๐Ÿ“š HybridRAG: Integrating Knowledge Graphs and Vector Retrieval (arxiv.org)
303
+ [+4] ๐Ÿ“š Adversarial Threat Vectors and Risk Mitigation for RAG (arxiv.org)
304
+ [+5] ๐Ÿ“š RAGdb: A Zero-Dependency, Embeddable Architecture (arxiv.org)
305
+ [+6] ๐Ÿ“š Building Scalable AI-Powered Applications with Cloud Databases (arxiv.org)
306
+ [+7] ๐Ÿ“š Federated Retrieval-Augmented Generation (FRAG) (arxiv.org)
307
+ [+8] ๐Ÿ“š A Systematic Review of Key RAG Components (arxiv.org)
308
+ [+9] ๐Ÿ“š From Traditional RAG to Agentic and Graph RAG (arxiv.org)
309
+ [+10] ๐Ÿ“š Accelerating Retrieval-Augmented Generation (arxiv.org)
310
+ ```
311
+
312
+ </details>
313
+
314
+ ### 3. Search & Data Extraction Tools
315
+
316
+ Seven search/analysis tools plus five session memory & knowledge tools (12 total):
317
+
318
+ | Tool | Purpose | Input | Output |
319
+ |------|---------|-------|--------|
320
+ | `brave_web_search` | Real-time internet search | Query string | Structured search results |
321
+ | `brave_local_search` | Location-based POI discovery | Query + location | Business/POI data |
322
+ | `brave_web_search_code_mode` | JS extraction over web results | Query + JS transform | Filtered fields |
323
+ | `brave_local_search_code_mode` | JS extraction over local results | Query + JS transform | Filtered fields |
324
+ | `code_mode_transform` | Universal post-processing | Raw data + JS transform | Normalized output |
325
+ | `gemini_research_paper_analysis` | Academic paper analysis | Paper text + analysis type | Structured analysis |
326
+ | `brave_answers` | AI-grounded answers | Question | Concise answer |
327
+
328
+ **Optional: Session Memory & Knowledge Tools** *(enabled when Supabase is configured)*
329
+
330
+ | Tool | Purpose | Input | Output |
331
+ |------|---------|-------|--------|
332
+ | `session_save_ledger` | Append immutable session log | Project + summary + TODOs | Confirmation |
333
+ | `session_save_handoff` | Upsert latest project state | Project + context | Confirmation |
334
+ | `session_load_context` | Progressive context loading + knowledge cache | Project + level | Session context + hot keywords |
335
+ | `knowledge_search` | Search accumulated knowledge | Keywords, category, or free text | Ranked results |
336
+ | `knowledge_forget` | Prune bad/old session memories | Project + filters + dry_run | Deletion report |
337
+
338
+ ### 4. Data Pipeline Integrations (Python)
339
+
340
+ Python-based automation for API consumption and data manipulation:
341
+
342
+ - **Gmail API** โ€” OAuth 2.0 authenticated email data retrieval and parsing
343
+ - **Chrome DevTools Protocol** โ€” Programmatic MCP tool introspection and browser automation
344
+ - **Cross-MCP Testing** โ€” Integration test suite validating tool interoperability across MCP servers
345
+
346
+ ### 5. Universal Code Mode Transform
347
+
348
+ A powerful **post-processing layer** designed to normalize and extract specific fields from large MCP outputs. Supports ready-to-use templates for:
349
+
350
+ - GitHub Issues / Pull Requests โ†’ compact summaries
351
+ - Firecrawl scrape results โ†’ title + URL extraction
352
+ - Chrome DevTools network logs โ†’ method + URL + status
353
+ - Video transcripts โ†’ keyword-filtered timestamp extraction
354
+
355
+ ## Technical Stack
356
+
357
+ | Layer | Technologies |
358
+ |-------|-------------|
359
+ | **Runtime** | Node.js 18+, TypeScript, `@modelcontextprotocol/sdk` |
360
+ | **Cloud AI** | Google Cloud Vertex AI, Discovery Engine, Gemini SDK, Anthropic Vertex SDK |
361
+ | **Data Processing** | Python 3.10+, JSON/CSV parsing, JavaScript extraction |
362
+ | **APIs** | Brave Search (Pro + Answers), Google Gemini, Gmail, Chrome DevTools, GCP Discovery Engine |
363
+ | **Auth & Security** | GCP ADC, OAuth 2.0, AES-encrypted credentials, env-based secrets injection |
364
+ | **Testing** | MCP schema validation, cross-server integration tests, Vertex AI verification, hybrid pipeline benchmarks |
365
+ | **Tooling** | Git, npm, gcloud CLI, Linux/macOS |
366
+
367
+ ## Project Structure
368
+
369
+ ```
370
+ โ”œโ”€โ”€ src/
371
+ โ”‚ โ”œโ”€โ”€ server.ts # MCP server core (conditional tool registration)
372
+ โ”‚ โ”œโ”€โ”€ config.ts # Configuration & environment management
373
+ โ”‚ โ”œโ”€โ”€ tools/
374
+ โ”‚ โ”‚ โ”œโ”€โ”€ definitions.ts # Search & analysis tool schemas
375
+ โ”‚ โ”‚ โ”œโ”€โ”€ handlers.ts # Search & analysis handlers
376
+ โ”‚ โ”‚ โ”œโ”€โ”€ sessionMemoryDefinitions.ts # Session memory + knowledge tool schemas
377
+ โ”‚ โ”‚ โ”œโ”€โ”€ sessionMemoryHandlers.ts # Session memory + knowledge handlers
378
+ โ”‚ โ”‚ โ””โ”€โ”€ index.ts # Tool registration & re-exports
379
+ โ”‚ โ””โ”€โ”€ utils/
380
+ โ”‚ โ”œโ”€โ”€ braveApi.ts # Brave Search REST client
381
+ โ”‚ โ”œโ”€โ”€ googleAi.ts # Google Gemini SDK wrapper
382
+ โ”‚ โ”œโ”€โ”€ executor.ts # QuickJS sandbox executor
383
+ โ”‚ โ”œโ”€โ”€ supabaseApi.ts # Supabase REST client (optional)
384
+ โ”‚ โ””โ”€โ”€ keywordExtractor.ts # Zero-dependency keyword extraction
385
+ โ”œโ”€โ”€ supabase/
386
+ โ”‚ โ””โ”€โ”€ migrations/
387
+ โ”‚ โ”œโ”€โ”€ 015_session_memory.sql # Session memory schema (tables + RPC)
388
+ โ”‚ โ””โ”€โ”€ 016_knowledge_accumulation.sql # Knowledge indexes, search RPC, cache preload
389
+ โ”œโ”€โ”€ vertex-ai/
390
+ โ”‚ โ”œโ”€โ”€ verify_discovery_engine.ts # Vertex AI Search index verification
391
+ โ”‚ โ”œโ”€โ”€ test_hybrid_search_pipeline.ts # End-to-end hybrid pipeline test
392
+ โ”‚ โ”œโ”€โ”€ test_pipeline_benchmark.ts # Performance benchmark: Brave vs DE
393
+ โ”‚ โ”œโ”€โ”€ test_realworld_comparison.ts # Real-world side-by-side comparison
394
+ โ”‚ โ”œโ”€โ”€ test_gemini_vertex.py # Gemini model via Vertex AI SDK
395
+ โ”‚ โ””โ”€โ”€ test_claude_vertex.py # Claude model via Vertex AI
396
+ โ”œโ”€โ”€ index.ts # Server entry point
397
+ โ”œโ”€โ”€ benchmark.ts # Performance benchmarking suite
398
+ โ”œโ”€โ”€ test_mcp_schema.js # MCP schema validation tests
399
+ โ”œโ”€โ”€ test_cross_mcp.js # Cross-MCP integration test suite
400
+ โ”œโ”€โ”€ package.json # Dependencies & build config
401
+ โ””โ”€โ”€ tsconfig.json # TypeScript configuration
402
+ ```
403
+
404
+ ## Getting Started
405
+
406
+ ### Prerequisites
407
+ - Node.js 18+
408
+ - Python 3.10+
409
+ - npm
410
+ - Google Cloud SDK (`gcloud`) with Vertex AI enabled
411
+
412
+ ### Installation
413
+ ```bash
414
+ git clone https://github.com/dcostenco/prism-mcp.git
415
+ cd prism-mcp
416
+ npm install
417
+ npm run build
418
+ ```
419
+
420
+ ### GCP / Vertex AI Setup
421
+ ```bash
422
+ # Authenticate for Vertex AI (no API keys needed โ€” uses ADC)
423
+ gcloud auth application-default login
424
+
425
+ # Optional: set Discovery Engine env vars for hybrid search
426
+ export DISCOVERY_ENGINE_PROJECT_ID=<your-gcp-project>
427
+ export DISCOVERY_ENGINE_ENGINE_ID=<your-engine-id>
428
+ export DISCOVERY_ENGINE_LOCATION=global
429
+ export DISCOVERY_ENGINE_COLLECTION=default_collection
430
+ export DISCOVERY_ENGINE_SERVING_CONFIG=default_serving_config
431
+ ```
432
+
433
+ ### Configuration
434
+
435
+ All credentials are injected via environment variables or GCP Application Default Credentials โ€” **no API keys are stored in this repository**.
436
+
437
+ Required environment variables (set via your shell profile or a `.env` file, which is `.gitignore`โ€™d):
438
+
439
+ - `BRAVE_API_KEY` โ€” Brave Search Pro subscription
440
+ - `GEMINI_API_KEY` โ€” Google AI Studio API key
441
+ - `DISCOVERY_ENGINE_PROJECT_ID` โ€” GCP project with Discovery Engine enabled
442
+ - `DISCOVERY_ENGINE_ENGINE_ID` โ€” Your Discovery Engine app/engine ID
443
+
444
+ ### Running
445
+ ```bash
446
+ # MCP Server
447
+ npm start
448
+
449
+ # Vertex AI Discovery Engine verification
450
+ npx ts-node vertex-ai/verify_discovery_engine.ts
451
+
452
+ # Vertex AI model tests
453
+ python3 vertex-ai/test_gemini_vertex.py
454
+ python3 vertex-ai/test_claude_vertex.py
455
+
456
+ # Hybrid pipeline test (MCP + Discovery Engine end-to-end)
457
+ npx ts-node vertex-ai/test_hybrid_search_pipeline.ts
458
+
459
+ # Performance benchmark (Brave Search vs Discovery Engine)
460
+ npx ts-node vertex-ai/test_pipeline_benchmark.ts
461
+ ```
462
+
463
+ ### Claude Desktop Integration
464
+
465
+ Add the server to your Claude Desktop MCP config (credentials are passed via environment variables):
466
+
467
+ ```json
468
+ {
469
+ "mcpServers": {
470
+ "prism-mcp": {
471
+ "command": "node",
472
+ "args": ["<path>/build/index.js"],
473
+ "env": {
474
+ "BRAVE_API_KEY": "${BRAVE_API_KEY}",
475
+ "GEMINI_API_KEY": "${GEMINI_API_KEY}",
476
+ "DISCOVERY_ENGINE_PROJECT_ID": "${DISCOVERY_ENGINE_PROJECT_ID}",
477
+ "DISCOVERY_ENGINE_ENGINE_ID": "${DISCOVERY_ENGINE_ENGINE_ID}",
478
+ "SUPABASE_URL": "${SUPABASE_URL}",
479
+ "SUPABASE_KEY": "${SUPABASE_KEY}"
480
+ }
481
+ }
482
+ }
483
+ }
484
+ ```
485
+
486
+ > **Note:** All 12 tools are available when both Brave and Supabase keys are configured. `SUPABASE_URL` and `SUPABASE_KEY` enable the 5 session memory + knowledge tools. Without them, the server runs with 7 search & analysis tools.
487
+
488
+ ## Key Design Decisions
489
+
490
+ - **Protocol-first architecture** โ€” All tools are exposed through the standardized MCP interface, ensuring compatibility with any MCP-compliant AI client
491
+ - **Cloud-native AI** โ€” Vertex AI integration provides enterprise-grade model access with GCP's security, quota management, and multi-region support
492
+ - **Multi-model strategy** โ€” Supports Gemini and Claude through the same GCP infrastructure, enabling model selection based on task requirements
493
+ - **Separation of concerns** โ€” Tool definitions, handlers, and configuration are cleanly separated for maintainability
494
+ - **Security by design** โ€” No hardcoded credentials; all secrets flow through environment variables, ADC, or encrypted stores
495
+ - **Extensibility** โ€” New tools can be registered by adding a definition + handler without modifying the server core
496
+ - **Optional modules** โ€” Session memory tools only register when Supabase is configured โ€” zero impact on users who don't need them
497
+ - **Cross-system interoperability** โ€” Universal transform layer enables output normalization across heterogeneous MCP servers
498
+
499
+ ---
500
+
501
+ ## Session Memory & Knowledge System
502
+
503
+ Prism's core differentiator: persistent session memory and brain-inspired knowledge accumulation for AI agents โ€” save work logs, hand off state between sessions, progressively load context on boot, search accumulated knowledge, and prune bad memories. This is what makes Prism more than just another search server.
504
+
505
+ ### Knowledge Accumulation System *(v0.3.0)*
506
+
507
+ The brain-inspired knowledge layer that turns session data into searchable, manageable institutional memory.
508
+
509
+ ```
510
+ Session saves โ†’ Keywords auto-extracted โ†’ GIN-indexed โ†’ Searchable at boot
511
+ โ”‚
512
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
513
+ โ–ผ โ–ผ
514
+ knowledge_search knowledge_cache
515
+ (on-demand) (auto at boot)
516
+ ```
517
+
518
+ #### How Knowledge Accumulates (Zero Effort)
519
+
520
+ Every `session_save_ledger` and `session_save_handoff` call automatically extracts keywords from the text using lightweight, in-process NLP (~0.020ms/call). No LLM calls, no external dependencies.
521
+
522
+ **Example:** Saving a ledger entry with summary *"Fixed Stripe webhook race condition using database-backed idempotency keys"* automatically extracts:
523
+ - **Keywords:** `stripe`, `webhook`, `race`, `condition`, `database`, `idempotency`, `keys`
524
+ - **Categories:** `cat:debugging`, `cat:api-integration`
525
+
526
+ #### `knowledge_search` โ€” Query Accumulated Knowledge
527
+
528
+ Search across all sessions by keyword, category, or free text:
529
+
530
+ ```json
531
+ {
532
+ "name": "knowledge_search",
533
+ "arguments": {
534
+ "project": "ecommerce-api",
535
+ "category": "debugging",
536
+ "query": "Stripe webhook"
537
+ }
538
+ }
539
+ ```
540
+
541
+ **Available categories:** `debugging`, `architecture`, `deployment`, `testing`, `configuration`, `api-integration`, `data-migration`, `security`, `performance`, `documentation`, `ai-ml`, `ui-frontend`, `resume`
542
+
543
+ #### `knowledge_forget` โ€” Prune Bad Memories
544
+
545
+ Selectively delete outdated or incorrect knowledge, like a brain pruning bad connections:
546
+
547
+ | Mode | Example | Effect |
548
+ |------|---------|--------|
549
+ | **By project** | `project: "old-app"` | Clear all knowledge for that project |
550
+ | **By category** | `project: "my-app", category: "debugging"` | Only forget debugging entries |
551
+ | **By age** | `project: "my-app", older_than_days: 30` | Forget entries older than 30 days |
552
+ | **Full reset** | `project: "my-app", confirm_all: true, clear_handoff: true` | Wipe everything + handoff state |
553
+ | **Dry run** | `dry_run: true` | Preview what would be deleted |
554
+
555
+ ```json
556
+ {
557
+ "name": "knowledge_forget",
558
+ "arguments": {
559
+ "project": "my-app",
560
+ "older_than_days": 30,
561
+ "dry_run": true
562
+ }
563
+ }
564
+ ```
565
+ **Response:** `๐Ÿ” 12 ledger entries would be forgotten for project "my-app" older than 30 days. This was a dry run.`
566
+
567
+ #### Knowledge Cache Preload (Automatic at Boot)
568
+
569
+ When `session_load_context` runs at `standard` or `deep` level, it now automatically includes a `knowledge_cache` section with the brain's hottest pathways โ€” no separate search call needed:
570
+
571
+ ```json
572
+ {
573
+ "level": "standard",
574
+ "project": "ecommerce-api",
575
+ "knowledge_cache": {
576
+ "hot_keywords": ["stripe", "webhook", "idempotency", "subscription", "api"],
577
+ "top_categories": ["api-integration", "debugging"],
578
+ "total_sessions": 14
579
+ }
580
+ }
581
+ ```
582
+
583
+ At `deep` level, you also get **cross-project knowledge** โ€” related sessions from OTHER projects that share keywords with the current one, enabling knowledge transfer across codebases.
584
+
585
+ #### Why Prism's Approach Is Different
586
+
587
+ Most MCP memory servers require **embedding models**, **graph databases**, or **LLM calls at save time**. Prism takes a fundamentally different approach:
588
+
589
+ > **๐Ÿง  Zero-cost intelligence.** Knowledge accumulates automatically from data you're already saving โ€” no new infrastructure, no extra API calls, no perceptible latency.
590
+
591
+ **5 key benefits no other MCP memory server offers:**
592
+
593
+ | # | Benefit | Details |
594
+ |---|---|---|
595
+ | โšก | **40,000ร— faster writes** | 0.005ms per save vs. 200โ€“500ms for graph/embedding servers. Your agent never waits. |
596
+ | ๐Ÿ—๏ธ | **Zero new infrastructure** | No Neo4j, no FalkorDB, no pgvector, no embedding API. Uses existing Supabase `TEXT[]` columns + PostgreSQL GIN indexes. |
597
+ | ๐Ÿงน | **Built-in memory pruning** | The only MCP memory with a first-class `knowledge_forget` tool โ€” 4 delete modes + dry_run safety. Others require manual DB operations. |
598
+ | ๐Ÿ”ฅ | **Knowledge cache at boot** | `session_load_context` auto-includes hot keywords and top categories. No separate search call. No other server preloads knowledge. |
599
+ | ๐Ÿ”— | **Cross-project knowledge transfer** | At `deep` level, surfaces relevant sessions from *other* projects via keyword overlap. Graph servers enforce strict isolation โ€” Prism treats cross-pollination as a feature. |
600
+
601
+ **Comparison with leading alternatives:**
602
+
603
+ ```
604
+ Prism Knowledge Graph Graphiti/FalkorDB Hindsight
605
+ Write overhead 0.005ms ~200ms ~500ms+ ~300ms
606
+ External deps None Neo4j/JSON FalkorDB (Docker) pgvector + embeddings
607
+ LLM at save time No No Yes Yes
608
+ Auto-categorize 13 cats Schema-dependent Schema-dependent Via LLM
609
+ Forget/prune tool โœ… 4 modes โŒ Manual โš ๏ธ TTL only โŒ None
610
+ Cache preload โœ… โŒ โŒ โŒ
611
+ Cross-project โœ… โŒ โŒ Isolated โŒ
612
+ ```
613
+
614
+ > **Philosophy:** Make the simplest thing that actually works, then make it invisible.
615
+
616
+ ### Why Session Memory?
617
+
618
+ AI agents forget everything between sessions. Session memory solves this:
619
+
620
+ ```
621
+ Session 1: Agent works on feature โ†’ saves ledger + handoff
622
+ โ”‚
623
+ Session 2: Agent boots โ†’ loads context โ† โ”€โ”˜ โ†’ continues seamlessly
624
+ ```
625
+
626
+ ### How It Works
627
+
628
+ Three complementary tools:
629
+
630
+ | Tool | When to Use | What It Does |
631
+ |------|-------------|---------------|
632
+ | `session_save_ledger` | End of every session | Appends an **immutable** log entry (summary, TODOs, files changed, decisions) |
633
+ | `session_save_handoff` | End of every session | **Upserts** the latest project state for next session boot |
634
+ | `session_load_context` | Start of every session | **Loads** context at the requested depth level |
635
+
636
+ ### Progressive Context Loading
637
+
638
+ Load only what you need โ€” saves tokens and speeds up boot:
639
+
640
+ | Level | What You Get | Approximate Size | When to Use |
641
+ |-------|-------------|-------------------|-------------|
642
+ | **quick** | Open TODOs and keywords from the last session | ~50 tokens (very small) | Fast check-ins โ€” "what was I working on?" |
643
+ | **standard** | Everything in *quick*, plus a summary of recent work and key decisions | ~200 tokens (small) | **Recommended for most sessions** โ€” gives the agent enough context to continue working |
644
+ | **deep** | Everything in *standard*, plus full logs from the last 5 sessions including all files changed | ~1000+ tokens (larger) | After a long break or when you need the complete history |
645
+
646
+ ### Real-Life Usage Examples
647
+
648
+ #### Example 1: Saving a Session (End of Work)
649
+
650
+ After completing a feature implementation session, the agent saves both a ledger entry and a handoff:
651
+
652
+ **Save Ledger** โ€” permanent record of what happened:
653
+ ```json
654
+ {
655
+ "name": "session_save_ledger",
656
+ "arguments": {
657
+ "project": "ecommerce-api",
658
+ "conversation_id": "conv-2026-03-18-a1b2c3",
659
+ "summary": "Implemented Stripe webhook handler for subscription lifecycle events. Added idempotency keys to prevent duplicate processing. Fixed race condition in concurrent webhook delivery.",
660
+ "todos": [
661
+ "Add retry logic for failed Stripe API calls (currently fails silently)",
662
+ "Write integration tests for subscription upgrade/downgrade flows",
663
+ "Update API docs with new webhook endpoint schema"
664
+ ],
665
+ "files_changed": [
666
+ "src/webhooks/stripe.ts",
667
+ "src/services/subscription.ts",
668
+ "src/middleware/idempotency.ts",
669
+ "tests/webhooks/stripe.test.ts"
670
+ ],
671
+ "decisions": [
672
+ "Used database-backed idempotency keys instead of Redis (simpler ops, acceptable latency for webhook volume)",
673
+ "Chose to process webhooks synchronously rather than queue โ€” volume is under 100/min",
674
+ "Deferred retry logic to next session โ€” needs design review for exponential backoff strategy"
675
+ ]
676
+ }
677
+ }
678
+ ```
679
+
680
+ **Save Handoff** โ€” live state for next session:
681
+ ```json
682
+ {
683
+ "name": "session_save_handoff",
684
+ "arguments": {
685
+ "project": "ecommerce-api",
686
+ "open_todos": [
687
+ "Add retry logic for failed Stripe API calls",
688
+ "Write integration tests for subscription flows",
689
+ "Update API docs with webhook endpoint schema"
690
+ ],
691
+ "active_branch": "feature/stripe-webhooks",
692
+ "last_summary": "Stripe webhook handler implemented with idempotency. Race condition fixed. Tests passing. Retry logic deferred.",
693
+ "key_context": "Webhook endpoint is POST /api/webhooks/stripe. Using stripe.webhooks.constructEvent() for signature verification. Idempotency table is 'webhook_events' with unique constraint on stripe_event_id."
694
+ }
695
+ }
696
+ ```
697
+
698
+ #### Example 2: Booting a New Session (Start of Work)
699
+
700
+ The next session (possibly hours or days later) loads context to resume:
701
+
702
+ **Load Context (L2 โ€” recommended default):**
703
+ ```json
704
+ {
705
+ "name": "session_load_context",
706
+ "arguments": {
707
+ "project": "ecommerce-api",
708
+ "level": "standard"
709
+ }
710
+ }
711
+ ```
712
+
713
+ **What the agent gets back:**
714
+ ```json
715
+ {
716
+ "handoff": {
717
+ "project": "ecommerce-api",
718
+ "open_todos": [
719
+ "Add retry logic for failed Stripe API calls",
720
+ "Write integration tests for subscription flows",
721
+ "Update API docs with webhook endpoint schema"
722
+ ],
723
+ "active_branch": "feature/stripe-webhooks",
724
+ "last_summary": "Stripe webhook handler implemented with idempotency. Race condition fixed. Tests passing. Retry logic deferred.",
725
+ "key_context": "Webhook endpoint is POST /api/webhooks/stripe. Using stripe.webhooks.constructEvent() for signature verification. Idempotency table is 'webhook_events' with unique constraint on stripe_event_id."
726
+ },
727
+ "recent_sessions": [
728
+ {
729
+ "summary": "Stripe webhook handler implemented with idempotency. Race condition fixed.",
730
+ "created_at": "2026-03-18T16:30:00Z"
731
+ },
732
+ {
733
+ "summary": "Set up Stripe SDK integration and customer portal. Created subscription model.",
734
+ "created_at": "2026-03-17T14:00:00Z"
735
+ },
736
+ {
737
+ "summary": "Designed payment architecture. Chose Stripe over Paddle for webhook flexibility.",
738
+ "created_at": "2026-03-16T10:00:00Z"
739
+ }
740
+ ]
741
+ }
742
+ ```
743
+
744
+ The agent now knows exactly where to pick up โ€” it can immediately start on the retry logic without asking the user to re-explain the project.
745
+
746
+ #### Example 3: Multi-Day Workflow (Full Lifecycle)
747
+
748
+ A realistic multi-day development workflow showing how session memory accumulates:
749
+
750
+ ```
751
+ Day 1 (Monday) โ€” Architecture & Setup
752
+ โ”œโ”€โ”€ Agent designs auth system architecture
753
+ โ”œโ”€โ”€ session_save_ledger: "Designed JWT auth with refresh tokens. Chose bcrypt over argon2."
754
+ โ””โ”€โ”€ session_save_handoff: branch=feature/auth, todos=["implement signup endpoint"]
755
+
756
+ Day 2 (Tuesday) โ€” Implementation
757
+ โ”œโ”€โ”€ session_load_context("standard"): Gets Day 1 handoff + summary
758
+ โ”œโ”€โ”€ Agent implements signup/login endpoints
759
+ โ”œโ”€โ”€ session_save_ledger: "Built signup + login. Added rate limiting. 12 tests passing."
760
+ โ””โ”€โ”€ session_save_handoff: branch=feature/auth, todos=["add password reset flow"]
761
+
762
+ Day 3 (Wednesday) โ€” Bug Fix (Different Agent Session)
763
+ โ”œโ”€โ”€ session_load_context("standard"): Gets Day 2 handoff + Day 1-2 summaries
764
+ โ”œโ”€โ”€ Agent fixes token refresh race condition
765
+ โ”œโ”€โ”€ session_save_ledger: "Fixed refresh token rotation bug (was invalidating too early)."
766
+ โ””โ”€โ”€ session_save_handoff: todos=["add password reset", "deploy to staging"]
767
+
768
+ Day 5 (Friday) โ€” Deep Recovery After Break
769
+ โ”œโ”€โ”€ session_load_context("deep"): Gets FULL history โ€” all summaries, all TODOs, all decisions
770
+ โ”œโ”€โ”€ Agent sees complete project context despite 2-day gap
771
+ โ””โ”€โ”€ Continues with password reset implementation
772
+ ```
773
+
774
+ **A "deep" recovery response** includes aggregated data across all sessions:
775
+ ```json
776
+ {
777
+ "handoff": { "...": "latest state" },
778
+ "recent_sessions": [ "...3 most recent..." ],
779
+ "all_todos_aggregated": [
780
+ "add password reset flow",
781
+ "deploy to staging",
782
+ "add password complexity validation"
783
+ ],
784
+ "all_decisions": [
785
+ "JWT auth with refresh tokens (Day 1)",
786
+ "bcrypt over argon2 for password hashing (Day 1)",
787
+ "Rate limiting: 5 attempts per 15 min window (Day 2)",
788
+ "Refresh token rotation: invalidate after use, not on issue (Day 3)"
789
+ ],
790
+ "session_count": 4,
791
+ "first_session": "2026-03-16T10:00:00Z",
792
+ "last_session": "2026-03-19T09:00:00Z"
793
+ }
794
+ ```
795
+
796
+ ### Supabase Setup (Step-by-Step)
797
+
798
+ #### 1. Create a Supabase Project
799
+
800
+ 1. Go to [supabase.com](https://supabase.com) and sign in (free tier works)
801
+ 2. Click **New Project** โ†’ choose a name and password โ†’ select a region close to you
802
+ 3. Wait for the project to be provisioned (~30 seconds)
803
+
804
+ #### 2. Apply the Migration
805
+
806
+ 1. In your Supabase dashboard, go to **SQL Editor** (left sidebar)
807
+ 2. Click **New query**
808
+ 3. Copy the contents of [`supabase/migrations/015_session_memory.sql`](supabase/migrations/015_session_memory.sql) and paste into the editor
809
+ 4. Click **Run** (or press `Cmd+Enter`)
810
+ 5. You should see: `Success. No rows returned`
811
+
812
+ This creates:
813
+ - `session_ledger` table โ€” append-only session logs
814
+ - `session_handoffs` table โ€” latest project state (one per project)
815
+ - `get_session_context()` RPC function โ€” progressive context loading
816
+
817
+ #### 3. Get Your Credentials
818
+
819
+ 1. Go to **Settings โ†’ API** in your Supabase dashboard
820
+ 2. Copy the **Project URL** (e.g. `https://abcdefg.supabase.co`)
821
+ 3. Copy the **anon public** key (starts with `eyJ...`)
822
+
823
+ #### 4. Set Environment Variables
824
+
825
+ ```bash
826
+ # Add to your shell profile (.zshrc, .bashrc) or .env file
827
+ export SUPABASE_URL="https://your-project.supabase.co"
828
+ export SUPABASE_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
829
+ ```
830
+
831
+ #### 5. Rebuild and Restart
832
+
833
+ ```bash
834
+ npm run build
835
+ # Restart your MCP client (Claude Desktop, etc.)
836
+ ```
837
+
838
+ On startup you'll see:
839
+ ```
840
+ Session memory enabled (Supabase configured)
841
+ Registering 12 tools (7 base + 5 session memory & knowledge)
842
+ ```
843
+
844
+ #### 6. Apply Knowledge Accumulation Migration
845
+
846
+ 1. In your Supabase dashboard, go to **SQL Editor**
847
+ 2. Click **New query**
848
+ 3. Copy the contents of [`supabase/migrations/016_knowledge_accumulation.sql`](supabase/migrations/016_knowledge_accumulation.sql)
849
+ 4. Click **Run**
850
+ 5. You should see: `Success. No rows returned`
851
+
852
+ This adds:
853
+ - GIN indexes on keywords columns for fast search
854
+ - `search_knowledge()` RPC for querying accumulated knowledge
855
+ - Enhanced `get_session_context()` with knowledge cache preload
856
+
857
+ ### Verifying the Setup
858
+
859
+ After configuring, verify the tables exist by running this in the Supabase SQL Editor:
860
+
861
+ ```sql
862
+ -- Should return 3 rows: session_ledger, session_handoffs, get_session_context
863
+ SELECT
864
+ CASE
865
+ WHEN routine_type IS NOT NULL THEN 'function'
866
+ ELSE 'table'
867
+ END AS type,
868
+ COALESCE(table_name, routine_name) AS name
869
+ FROM information_schema.tables
870
+ WHERE table_schema = 'public'
871
+ AND table_name IN ('session_ledger', 'session_handoffs')
872
+ UNION ALL
873
+ SELECT 'function', routine_name
874
+ FROM information_schema.routines
875
+ WHERE routine_schema = 'public'
876
+ AND routine_name = 'get_session_context';
877
+ ```
878
+
879
+ ### Maintenance Guide
880
+
881
+ #### Cleaning Up Old Ledger Entries
882
+
883
+ The ledger grows over time. To prune entries older than 30 days:
884
+
885
+ ```sql
886
+ DELETE FROM session_ledger
887
+ WHERE created_at < NOW() - INTERVAL '30 days';
888
+ ```
889
+
890
+ #### Backing Up Session Data
891
+
892
+ ```sql
893
+ -- Export all session data as JSON
894
+ SELECT json_agg(t) FROM (
895
+ SELECT * FROM session_ledger ORDER BY created_at
896
+ ) t;
897
+
898
+ SELECT json_agg(t) FROM (
899
+ SELECT * FROM session_handoffs ORDER BY updated_at
900
+ ) t;
901
+ ```
902
+
903
+ #### Restoring from Backup
904
+
905
+ Paste the JSON arrays into INSERT statements:
906
+
907
+ ```sql
908
+ INSERT INTO session_ledger (project, conversation_id, summary, todos, files_changed, decisions)
909
+ SELECT project, conversation_id, summary, todos, files_changed, decisions
910
+ FROM json_populate_recordset(NULL::session_ledger, '<paste JSON array>');
911
+ ```
912
+
913
+ #### Monitoring Table Size
914
+
915
+ ```sql
916
+ SELECT
917
+ relname AS table_name,
918
+ pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
919
+ n_live_tup AS row_count
920
+ FROM pg_stat_user_tables
921
+ WHERE schemaname = 'public'
922
+ AND relname IN ('session_ledger', 'session_handoffs')
923
+ ORDER BY pg_total_relation_size(relid) DESC;
924
+ ```
925
+
926
+ ### Troubleshooting
927
+
928
+ | Symptom | Cause | Fix |
929
+ |---------|-------|-----|
930
+ | `Session memory disabled` on startup | `SUPABASE_URL` or `SUPABASE_KEY` not set | Set both env vars and restart |
931
+ | `Supabase POST failed: 404` | Migration not applied | Run `015_session_memory.sql` in SQL Editor |
932
+ | `Supabase POST failed: 401` | Wrong API key | Use the **anon public** key from Settings โ†’ API |
933
+ | `Supabase POST failed: 42501` | RLS blocking inserts | Ensure RLS policies allow inserts (see Security below) |
934
+ | `No session context found` | No prior sessions saved | Expected for new projects โ€” save a ledger entry first |
935
+ | `session_save_handoff` returns empty | First-time upsert | Normal โ€” the handoff is created, subsequent loads will work |
936
+
937
+ ### Security Recommendations
938
+
939
+ 1. **Use the anon key** for MCP server config โ€” it's safe for client-side use
940
+ 2. **Enable Row Level Security (RLS)** on both tables:
941
+
942
+ ```sql
943
+ -- Enable RLS
944
+ ALTER TABLE session_ledger ENABLE ROW LEVEL SECURITY;
945
+ ALTER TABLE session_handoffs ENABLE ROW LEVEL SECURITY;
946
+
947
+ -- Allow inserts and reads for authenticated and anon users
948
+ CREATE POLICY "Allow all for session_ledger" ON session_ledger
949
+ FOR ALL USING (true) WITH CHECK (true);
950
+
951
+ CREATE POLICY "Allow all for session_handoffs" ON session_handoffs
952
+ FOR ALL USING (true) WITH CHECK (true);
953
+ ```
954
+
955
+ 3. **For multi-user setups**, restrict policies to specific projects:
956
+
957
+ ```sql
958
+ -- Example: only allow access to your own projects
959
+ CREATE POLICY "User-scoped access" ON session_ledger
960
+ FOR ALL USING (project = current_setting('request.jwt.claims')::json->>'project')
961
+ WITH CHECK (project = current_setting('request.jwt.claims')::json->>'project');
962
+ ```
963
+
964
+ 4. **Never commit** your `SUPABASE_KEY` to version control โ€” use environment variables
965
+
966
+ ---
967
+
968
+ ## License
969
+
970
+ MIT