membannk 0.1.0__tar.gz
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.
- membannk-0.1.0/.gitignore +10 -0
- membannk-0.1.0/LICENSE +21 -0
- membannk-0.1.0/PKG-INFO +125 -0
- membannk-0.1.0/README.md +104 -0
- membannk-0.1.0/hooks/membannk-session-start.sh +30 -0
- membannk-0.1.0/pyproject.toml +39 -0
- membannk-0.1.0/src/membannk/__init__.py +3 -0
- membannk-0.1.0/src/membannk/__main__.py +3 -0
- membannk-0.1.0/src/membannk/app.py +843 -0
- membannk-0.1.0/src/membannk/cli.py +102 -0
membannk-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BharanitharanR
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
membannk-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: membannk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: One local memory shared by all your AI assistants (Claude, ChatGPT, Gemini, Grok) over MCP.
|
|
5
|
+
Project-URL: Homepage, https://github.com/BharanitharanR/membannk
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: chatgpt,claude,gemini,knowledge-base,llm,mcp,memory,txtai
|
|
9
|
+
Classifier: Operating System :: MacOS
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Requires-Dist: docling>=2.0
|
|
14
|
+
Requires-Dist: fastapi>=0.115
|
|
15
|
+
Requires-Dist: mcp>=2.3
|
|
16
|
+
Requires-Dist: ngrok>=1.4
|
|
17
|
+
Requires-Dist: pyside6>=6.7
|
|
18
|
+
Requires-Dist: txtai[pipeline-audio,pipeline-data,workflow]>=9.0
|
|
19
|
+
Requires-Dist: uvicorn>=0.30
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# MemBannk
|
|
23
|
+
|
|
24
|
+
**One memory shared by all your AI assistants.** Start a thread in Claude, pick it up in ChatGPT, then finish it in Gemini, without pasting the history across.
|
|
25
|
+
|
|
26
|
+
MemBannk is a small desktop app that runs on your Mac. It keeps:
|
|
27
|
+
|
|
28
|
+
- **Conversation checkpoints.** An assistant saves a structured snapshot (topic, summary, decisions, open questions, next steps). Any other assistant can `resume` it later, by exact topic name or just by describing it ("where was I with the launch plan?").
|
|
29
|
+
- **A personal knowledge base.** Drop in Markdown, text, PDFs, folders, `.zip` archives, or even video and audio (transcribed locally with Whisper). Everything is searchable by meaning.
|
|
30
|
+
|
|
31
|
+
Assistants reach it over the [Model Context Protocol (MCP)](https://modelcontextprotocol.io). Data stays on your machine in SQLite and a txtai vector index. The optional ngrok tunnel only lets web assistants talk to your machine; nothing is stored in the cloud.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install git+https://github.com/BharanitharanR/membannk
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Python 3.10+ is required, and a virtual environment is recommended. The first launch downloads about 500 MB of models (MiniLM embeddings, Docling, Whisper base).
|
|
40
|
+
|
|
41
|
+
## Run
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
membannk
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
A window opens and the MCP server starts at `http://127.0.0.1:8000/mcp`. Leave the window open while you work.
|
|
48
|
+
|
|
49
|
+
### Make it reachable from ChatGPT, Gemini and claude.ai (ngrok)
|
|
50
|
+
|
|
51
|
+
Web assistants can't see `127.0.0.1`, so they need a public HTTPS URL. The ngrok tunnel is built in, with no separate binary to install:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
membannk --set-ngrok-token <your-ngrok-authtoken> # once; free at dashboard.ngrok.com
|
|
55
|
+
membannk --tunnel --domain <your-static-domain>.ngrok-free.app
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The window shows a **public MCP URL** like `https://<domain>/<secret>/mcp`. The secret path is generated once and saved in `~/.membannk/path_token`. Every other path returns 404, so **treat the whole URL like a password**. To rotate it, run `membannk --new-secret`. `membannk --show-url` prints the URL again.
|
|
59
|
+
|
|
60
|
+
## Connect your assistants
|
|
61
|
+
|
|
62
|
+
| Assistant | How |
|
|
63
|
+
|---|---|
|
|
64
|
+
| Claude Code | `claude mcp add --transport http membannk http://127.0.0.1:8000/mcp` |
|
|
65
|
+
| Cursor / VS Code | Add an MCP server with URL `http://127.0.0.1:8000/mcp` |
|
|
66
|
+
| Claude (desktop / claude.ai) | Settings → Connectors → Add custom connector → paste the public URL |
|
|
67
|
+
| ChatGPT | Settings → Apps & Connectors → Advanced → Developer mode → Create connector → paste the public URL |
|
|
68
|
+
| Gemini | Settings → Connectors / MCP servers → Connect to an MCP server → paste the public URL |
|
|
69
|
+
|
|
70
|
+
Menu names move around as these apps update. Look for "custom connector" or "MCP server".
|
|
71
|
+
|
|
72
|
+
## Use it
|
|
73
|
+
|
|
74
|
+
Just talk normally:
|
|
75
|
+
|
|
76
|
+
- *"Save this as **MemBannk launch plan**."* The assistant calls `save_context`.
|
|
77
|
+
- In another assistant: *"Resume the MemBannk launch plan"* or *"where was I with the launch?"* The assistant calls `resume` and continues from the latest checkpoint, with earlier checkpoints and related KB material attached.
|
|
78
|
+
- *"What did my notes say about pricing?"* The assistant calls `search_kb`.
|
|
79
|
+
|
|
80
|
+
### Tools
|
|
81
|
+
|
|
82
|
+
| Tool | What it does |
|
|
83
|
+
|---|---|
|
|
84
|
+
| `save_context(topic, summary, decisions, open_questions, next_steps, source)` | Save a checkpoint |
|
|
85
|
+
| `resume(query, history=3, include_kb=True)` | Load the latest checkpoint(s) for a topic, matched by name, meaning or keyword |
|
|
86
|
+
| `list_topics()` | List saved threads |
|
|
87
|
+
| `search_kb(query, limit=3)` | Semantic search over ingested files |
|
|
88
|
+
| `ingest_paths(paths)` | Ingest files, folders or `.zip` archives from disk |
|
|
89
|
+
| `kb_stats()` | Count indexed chunks |
|
|
90
|
+
|
|
91
|
+
REST endpoints are also available: `POST /ingest`, `GET /search?query=`, `GET /health`.
|
|
92
|
+
|
|
93
|
+
### Claude Code: pull memory at session start (optional)
|
|
94
|
+
|
|
95
|
+
`hooks/membannk-session-start.sh` is a SessionStart hook that tells Claude to check MemBannk for the current project before it starts work. Add it to `~/.claude/settings.json`:
|
|
96
|
+
|
|
97
|
+
```json
|
|
98
|
+
{
|
|
99
|
+
"hooks": {
|
|
100
|
+
"SessionStart": [
|
|
101
|
+
{ "hooks": [{ "type": "command", "command": "/path/to/membannk/hooks/membannk-session-start.sh" }] }
|
|
102
|
+
]
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Configuration
|
|
108
|
+
|
|
109
|
+
| Env var | Default | Meaning |
|
|
110
|
+
|---|---|---|
|
|
111
|
+
| `MEMBANNK_PORT` | `8000` | Port (`--port` overrides it) |
|
|
112
|
+
| `MEMBANNK_HOST` | `127.0.0.1` | Listen address |
|
|
113
|
+
| `MEMBANNK_DATA_DIR` | `~/Library/Application Support/LocalKB` | Where the index and `contexts.db` live |
|
|
114
|
+
| `MEMBANNK_PATH_TOKEN` | *(auto with `--tunnel`)* | Secret path prefix |
|
|
115
|
+
| `NGROK_AUTHTOKEN` | `~/.membannk/ngrok_auth` | ngrok authtoken |
|
|
116
|
+
| `MEMBANNK_NGROK_DOMAIN` | `~/.membannk/ngrok_domain` | Static ngrok domain |
|
|
117
|
+
|
|
118
|
+
## Security notes
|
|
119
|
+
|
|
120
|
+
- Without `--tunnel`, the server only listens on `127.0.0.1`.
|
|
121
|
+
- With `--tunnel`, anyone who has the full URL can read your checkpoints and KB. They can also call `ingest_paths` to index files from your disk. Keep the URL private, rotate it with `--new-secret` if it leaks, and stop the app when you don't need remote access.
|
|
122
|
+
|
|
123
|
+
## License
|
|
124
|
+
|
|
125
|
+
MIT
|
membannk-0.1.0/README.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# MemBannk
|
|
2
|
+
|
|
3
|
+
**One memory shared by all your AI assistants.** Start a thread in Claude, pick it up in ChatGPT, then finish it in Gemini, without pasting the history across.
|
|
4
|
+
|
|
5
|
+
MemBannk is a small desktop app that runs on your Mac. It keeps:
|
|
6
|
+
|
|
7
|
+
- **Conversation checkpoints.** An assistant saves a structured snapshot (topic, summary, decisions, open questions, next steps). Any other assistant can `resume` it later, by exact topic name or just by describing it ("where was I with the launch plan?").
|
|
8
|
+
- **A personal knowledge base.** Drop in Markdown, text, PDFs, folders, `.zip` archives, or even video and audio (transcribed locally with Whisper). Everything is searchable by meaning.
|
|
9
|
+
|
|
10
|
+
Assistants reach it over the [Model Context Protocol (MCP)](https://modelcontextprotocol.io). Data stays on your machine in SQLite and a txtai vector index. The optional ngrok tunnel only lets web assistants talk to your machine; nothing is stored in the cloud.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install git+https://github.com/BharanitharanR/membannk
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Python 3.10+ is required, and a virtual environment is recommended. The first launch downloads about 500 MB of models (MiniLM embeddings, Docling, Whisper base).
|
|
19
|
+
|
|
20
|
+
## Run
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
membannk
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
A window opens and the MCP server starts at `http://127.0.0.1:8000/mcp`. Leave the window open while you work.
|
|
27
|
+
|
|
28
|
+
### Make it reachable from ChatGPT, Gemini and claude.ai (ngrok)
|
|
29
|
+
|
|
30
|
+
Web assistants can't see `127.0.0.1`, so they need a public HTTPS URL. The ngrok tunnel is built in, with no separate binary to install:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
membannk --set-ngrok-token <your-ngrok-authtoken> # once; free at dashboard.ngrok.com
|
|
34
|
+
membannk --tunnel --domain <your-static-domain>.ngrok-free.app
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The window shows a **public MCP URL** like `https://<domain>/<secret>/mcp`. The secret path is generated once and saved in `~/.membannk/path_token`. Every other path returns 404, so **treat the whole URL like a password**. To rotate it, run `membannk --new-secret`. `membannk --show-url` prints the URL again.
|
|
38
|
+
|
|
39
|
+
## Connect your assistants
|
|
40
|
+
|
|
41
|
+
| Assistant | How |
|
|
42
|
+
|---|---|
|
|
43
|
+
| Claude Code | `claude mcp add --transport http membannk http://127.0.0.1:8000/mcp` |
|
|
44
|
+
| Cursor / VS Code | Add an MCP server with URL `http://127.0.0.1:8000/mcp` |
|
|
45
|
+
| Claude (desktop / claude.ai) | Settings → Connectors → Add custom connector → paste the public URL |
|
|
46
|
+
| ChatGPT | Settings → Apps & Connectors → Advanced → Developer mode → Create connector → paste the public URL |
|
|
47
|
+
| Gemini | Settings → Connectors / MCP servers → Connect to an MCP server → paste the public URL |
|
|
48
|
+
|
|
49
|
+
Menu names move around as these apps update. Look for "custom connector" or "MCP server".
|
|
50
|
+
|
|
51
|
+
## Use it
|
|
52
|
+
|
|
53
|
+
Just talk normally:
|
|
54
|
+
|
|
55
|
+
- *"Save this as **MemBannk launch plan**."* The assistant calls `save_context`.
|
|
56
|
+
- In another assistant: *"Resume the MemBannk launch plan"* or *"where was I with the launch?"* The assistant calls `resume` and continues from the latest checkpoint, with earlier checkpoints and related KB material attached.
|
|
57
|
+
- *"What did my notes say about pricing?"* The assistant calls `search_kb`.
|
|
58
|
+
|
|
59
|
+
### Tools
|
|
60
|
+
|
|
61
|
+
| Tool | What it does |
|
|
62
|
+
|---|---|
|
|
63
|
+
| `save_context(topic, summary, decisions, open_questions, next_steps, source)` | Save a checkpoint |
|
|
64
|
+
| `resume(query, history=3, include_kb=True)` | Load the latest checkpoint(s) for a topic, matched by name, meaning or keyword |
|
|
65
|
+
| `list_topics()` | List saved threads |
|
|
66
|
+
| `search_kb(query, limit=3)` | Semantic search over ingested files |
|
|
67
|
+
| `ingest_paths(paths)` | Ingest files, folders or `.zip` archives from disk |
|
|
68
|
+
| `kb_stats()` | Count indexed chunks |
|
|
69
|
+
|
|
70
|
+
REST endpoints are also available: `POST /ingest`, `GET /search?query=`, `GET /health`.
|
|
71
|
+
|
|
72
|
+
### Claude Code: pull memory at session start (optional)
|
|
73
|
+
|
|
74
|
+
`hooks/membannk-session-start.sh` is a SessionStart hook that tells Claude to check MemBannk for the current project before it starts work. Add it to `~/.claude/settings.json`:
|
|
75
|
+
|
|
76
|
+
```json
|
|
77
|
+
{
|
|
78
|
+
"hooks": {
|
|
79
|
+
"SessionStart": [
|
|
80
|
+
{ "hooks": [{ "type": "command", "command": "/path/to/membannk/hooks/membannk-session-start.sh" }] }
|
|
81
|
+
]
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Configuration
|
|
87
|
+
|
|
88
|
+
| Env var | Default | Meaning |
|
|
89
|
+
|---|---|---|
|
|
90
|
+
| `MEMBANNK_PORT` | `8000` | Port (`--port` overrides it) |
|
|
91
|
+
| `MEMBANNK_HOST` | `127.0.0.1` | Listen address |
|
|
92
|
+
| `MEMBANNK_DATA_DIR` | `~/Library/Application Support/LocalKB` | Where the index and `contexts.db` live |
|
|
93
|
+
| `MEMBANNK_PATH_TOKEN` | *(auto with `--tunnel`)* | Secret path prefix |
|
|
94
|
+
| `NGROK_AUTHTOKEN` | `~/.membannk/ngrok_auth` | ngrok authtoken |
|
|
95
|
+
| `MEMBANNK_NGROK_DOMAIN` | `~/.membannk/ngrok_domain` | Static ngrok domain |
|
|
96
|
+
|
|
97
|
+
## Security notes
|
|
98
|
+
|
|
99
|
+
- Without `--tunnel`, the server only listens on `127.0.0.1`.
|
|
100
|
+
- With `--tunnel`, anyone who has the full URL can read your checkpoints and KB. They can also call `ingest_paths` to index files from your disk. Keep the URL private, rotate it with `--new-secret` if it leaks, and stop the app when you don't need remote access.
|
|
101
|
+
|
|
102
|
+
## License
|
|
103
|
+
|
|
104
|
+
MIT
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# MemBannk SessionStart hook: tells Claude to pull prior cross-agent context.
|
|
3
|
+
# Output on stdout is added to Claude's context at session start.
|
|
4
|
+
|
|
5
|
+
set -u
|
|
6
|
+
|
|
7
|
+
PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$PWD}"
|
|
8
|
+
PROJECT_NAME="$(basename "$PROJECT_DIR")"
|
|
9
|
+
|
|
10
|
+
if git -C "$PROJECT_DIR" rev-parse --show-toplevel >/dev/null 2>&1; then
|
|
11
|
+
REPO_ROOT="$(git -C "$PROJECT_DIR" rev-parse --show-toplevel)"
|
|
12
|
+
BRANCH="$(git -C "$PROJECT_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)"
|
|
13
|
+
else
|
|
14
|
+
REPO_ROOT="$PROJECT_DIR"
|
|
15
|
+
BRANCH="none"
|
|
16
|
+
fi
|
|
17
|
+
|
|
18
|
+
cat <<EOF
|
|
19
|
+
[MemBannk session context]
|
|
20
|
+
Project: ${PROJECT_NAME}
|
|
21
|
+
Repository root: ${REPO_ROOT}
|
|
22
|
+
Git branch: ${BRANCH}
|
|
23
|
+
|
|
24
|
+
Before starting work, search MemBannk (search_kb) for this project and task.
|
|
25
|
+
Look for: discussions from other agents (ChatGPT, Claude, Gemini, Grok), architecture,
|
|
26
|
+
decisions, rejected alternatives, open questions, unfinished work, and prior implementation details.
|
|
27
|
+
Reconcile anything you find with the current codebase. Do not trust stale memory blindly.
|
|
28
|
+
EOF
|
|
29
|
+
|
|
30
|
+
exit 0
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "membannk"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "One local memory shared by all your AI assistants (Claude, ChatGPT, Gemini, Grok) over MCP."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
keywords = ["mcp", "memory", "llm", "claude", "chatgpt", "gemini", "txtai", "knowledge-base"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: MacOS",
|
|
17
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
18
|
+
]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"txtai[pipeline-audio,pipeline-data,workflow]>=9.0",
|
|
21
|
+
"docling>=2.0",
|
|
22
|
+
"PySide6>=6.7",
|
|
23
|
+
"fastapi>=0.115",
|
|
24
|
+
"uvicorn>=0.30",
|
|
25
|
+
"mcp>=2.3",
|
|
26
|
+
"ngrok>=1.4",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
membannk = "membannk.cli:main"
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/BharanitharanR/membannk"
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.wheel]
|
|
36
|
+
packages = ["src/membannk"]
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.sdist]
|
|
39
|
+
include = ["src/membannk", "hooks", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
"""
|
|
2
|
+
================================================================================
|
|
3
|
+
MemBannk: a local memory shared by all your AI assistants (desktop app + MCP server)
|
|
4
|
+
================================================================================
|
|
5
|
+
What this script does:
|
|
6
|
+
1. Opens a native macOS desktop window (using PySide6 / Qt) with a chat interface.
|
|
7
|
+
2. Lets you drag-and-drop (or browse for) Markdown (.md), Text (.txt), PDF (.pdf),
|
|
8
|
+
Video/Audio (.mp4, .mov, .mkv, .mp3, .wav), folders, or .zip archives.
|
|
9
|
+
3. Uses txtai's native FileTask workflows to automatically unzip archives, walk
|
|
10
|
+
nested folders, parse documents with Docling, and transcribe videos with Whisper.
|
|
11
|
+
4. Stores everything locally on your Mac in a semantic vector + SQLite database.
|
|
12
|
+
5. Runs an embedded FastAPI + MCP (Model Context Protocol) server in the background
|
|
13
|
+
so AI coding assistants (Cursor, Claude Code, VS Code) can also query or add
|
|
14
|
+
to your Knowledge Base at http://127.0.0.1:8000/mcp.
|
|
15
|
+
================================================================================
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
# ------------------------------------------------------------------------------
|
|
19
|
+
# SECTION 1: IMPORTS (Bringing in the libraries we need)
|
|
20
|
+
# ------------------------------------------------------------------------------
|
|
21
|
+
import contextlib # Helps manage startup/shutdown lifecycle for the FastAPI server
|
|
22
|
+
import datetime # Timestamps for saved conversation checkpoints
|
|
23
|
+
import json # Stores list fields (decisions, questions) inside SQLite
|
|
24
|
+
import os # Helps work with macOS file paths, folders, and environment
|
|
25
|
+
import re # Normalises topic names into stable keys
|
|
26
|
+
import sqlite3 # Small structured store for cross-assistant conversation checkpoints
|
|
27
|
+
import sys # Provides system-level arguments and exit controls for the app
|
|
28
|
+
import threading # Allows running the web server & heavy tasks without freezing the UI
|
|
29
|
+
|
|
30
|
+
import uvicorn # The web server engine that runs FastAPI
|
|
31
|
+
from fastapi import FastAPI, HTTPException # Framework to build REST API endpoints
|
|
32
|
+
from mcp.server.mcpserver import MCPServer # MCP v2 SDK class to expose AI agent tools
|
|
33
|
+
from pydantic import BaseModel # Validates incoming JSON data for API requests
|
|
34
|
+
|
|
35
|
+
# PySide6 provides the native macOS desktop window, buttons, text boxes, and threads
|
|
36
|
+
from PySide6.QtCore import QThread, Signal
|
|
37
|
+
from PySide6.QtWidgets import (
|
|
38
|
+
QApplication, # The core desktop application manager
|
|
39
|
+
QMainWindow, # The main window frame
|
|
40
|
+
QWidget, # Generic container for UI elements
|
|
41
|
+
QVBoxLayout, # Stacks UI elements vertically (top to bottom)
|
|
42
|
+
QHBoxLayout, # Arranges UI elements horizontally (left to right)
|
|
43
|
+
QTextBrowser, # Read-only rich text area used to display chat history
|
|
44
|
+
QLineEdit, # Single-line text input box where you type questions
|
|
45
|
+
QPushButton, # Clickable buttons ("+ Add Files", "Ask")
|
|
46
|
+
QFileDialog, # Native macOS Finder file-picker popup
|
|
47
|
+
QLabel, # Simple text label for showing status messages at the top
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# ------------------------------------------------------------------------------
|
|
52
|
+
# SECTION 2: STORAGE CONFIGURATION & THREAD-SAFE SHARED STATE
|
|
53
|
+
# ------------------------------------------------------------------------------
|
|
54
|
+
# We store the database inside macOS's standard 'Application Support' folder so
|
|
55
|
+
# your data persists safely even if you package this script into a .app icon.
|
|
56
|
+
_DEFAULT_DATA_DIR = ("~/Library/Application Support/LocalKB" if sys.platform == "darwin"
|
|
57
|
+
else "~/.local/share/membannk")
|
|
58
|
+
APP_DATA_DIR = os.path.expanduser(os.environ.get("MEMBANNK_DATA_DIR", _DEFAULT_DATA_DIR))
|
|
59
|
+
os.makedirs(APP_DATA_DIR, exist_ok=True) # Create the folder if it doesn't exist yet
|
|
60
|
+
INDEX_DIR = os.path.join(APP_DATA_DIR, "kb_index") # Subfolder for the txtai database
|
|
61
|
+
|
|
62
|
+
# Network settings (all optional, set as environment variables before launching):
|
|
63
|
+
# MEMBANNK_HOST interface to listen on (default 127.0.0.1, local only)
|
|
64
|
+
# MEMBANNK_PORT port to listen on (default 8000)
|
|
65
|
+
# MEMBANNK_PATH_TOKEN long random secret. When set, every endpoint lives under
|
|
66
|
+
# /<token>/ (MCP at /<token>/mcp) and every other path returns 404.
|
|
67
|
+
# `membannk --tunnel` creates and saves one for you automatically.
|
|
68
|
+
# MEMBANNK_TUNNEL=1 open an ngrok tunnel at startup (set by `membannk --tunnel`)
|
|
69
|
+
# NGROK_AUTHTOKEN your ngrok authtoken (or put it in ~/.membannk/ngrok_auth)
|
|
70
|
+
# MEMBANNK_NGROK_DOMAIN optional reserved/static ngrok domain, e.g. my-name.ngrok-free.app
|
|
71
|
+
HOST = os.environ.get("MEMBANNK_HOST", "127.0.0.1")
|
|
72
|
+
PORT = int(os.environ.get("MEMBANNK_PORT", "8000"))
|
|
73
|
+
PATH_TOKEN = os.environ.get("MEMBANNK_PATH_TOKEN", "").strip().strip("/")
|
|
74
|
+
BASE_PATH = f"/{PATH_TOKEN}" if PATH_TOKEN else ""
|
|
75
|
+
MCP_URL = f"http://{HOST}:{PORT}{BASE_PATH}/mcp"
|
|
76
|
+
|
|
77
|
+
# Because both the Desktop UI and the FastAPI/MCP web server access the same txtai
|
|
78
|
+
# database at the same time, we use a 'Lock' so two operations never collide.
|
|
79
|
+
kb_lock = threading.Lock()
|
|
80
|
+
|
|
81
|
+
# A dictionary holding our loaded AI models and workflows so every part of the
|
|
82
|
+
# program (UI threads, FastAPI routes, MCP tools) can share them in memory.
|
|
83
|
+
shared_state = {
|
|
84
|
+
"embeddings": None, # The txtai semantic search database
|
|
85
|
+
"doc_workflow": None, # The txtai workflow for Markdown, TXT, PDF, and Zip files
|
|
86
|
+
"media_workflow": None, # The txtai workflow for Video and Audio files
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# ------------------------------------------------------------------------------
|
|
91
|
+
# SECTION 3: CORE INGESTION LOGIC (Shared by Desktop UI, FastAPI, and MCP)
|
|
92
|
+
# ------------------------------------------------------------------------------
|
|
93
|
+
def run_ingestion_workflows(file_paths: list[str]) -> str:
|
|
94
|
+
"""
|
|
95
|
+
Takes a list of file, folder, or .zip paths, extracts their text or spoken
|
|
96
|
+
audio transcripts using txtai's native FileTask workflows, and saves them
|
|
97
|
+
into the local semantic search database.
|
|
98
|
+
"""
|
|
99
|
+
doc_workflow = shared_state["doc_workflow"]
|
|
100
|
+
media_workflow = shared_state["media_workflow"]
|
|
101
|
+
|
|
102
|
+
# Safety check: make sure models have finished loading before ingesting
|
|
103
|
+
if not doc_workflow or not media_workflow:
|
|
104
|
+
return "Models are still loading. Please wait a moment and try again."
|
|
105
|
+
|
|
106
|
+
# This list will hold all the text chunks we prepare to insert into txtai
|
|
107
|
+
new_docs = []
|
|
108
|
+
|
|
109
|
+
# --- Step 3A: Process Documents (Markdown, TXT, PDF) & Zip Archives ---
|
|
110
|
+
# doc_workflow automatically unzips any .zip files, walks nested folders,
|
|
111
|
+
# and runs Docling's Textractor on matching files.
|
|
112
|
+
for idx, sections in enumerate(doc_workflow(file_paths)):
|
|
113
|
+
# If Textractor returns a single string instead of a list, wrap it in a list
|
|
114
|
+
if isinstance(sections, str):
|
|
115
|
+
sections = [sections]
|
|
116
|
+
|
|
117
|
+
# Loop through each extracted section/paragraph and format it for txtai
|
|
118
|
+
for sec_idx, section in enumerate(sections or []):
|
|
119
|
+
new_docs.append({
|
|
120
|
+
"id": f"doc#{os.urandom(4).hex()}#{sec_idx}", # Unique random ID
|
|
121
|
+
"source": f"document_{idx}", # Source label
|
|
122
|
+
"text": section, # The actual text content
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
# --- Step 3B: Process Media (Videos & Audio) & Zip Archives ---
|
|
126
|
+
# media_workflow unzips archives, finds video/audio files, and transcribes
|
|
127
|
+
# spoken speech into text using OpenAI's Whisper model.
|
|
128
|
+
for idx, transcript in enumerate(media_workflow(file_paths)):
|
|
129
|
+
if transcript:
|
|
130
|
+
# Break long video transcripts into 500-character chunks for better search
|
|
131
|
+
chunks = [transcript[i : i + 500] for i in range(0, len(transcript), 500)]
|
|
132
|
+
for chunk_idx, chunk in enumerate(chunks):
|
|
133
|
+
new_docs.append({
|
|
134
|
+
"id": f"media#{os.urandom(4).hex()}#{chunk_idx}",
|
|
135
|
+
"source": f"media_{idx}",
|
|
136
|
+
"text": chunk,
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
# --- Step 3C: Save Extracted Chunks into the txtai Database ---
|
|
140
|
+
if new_docs:
|
|
141
|
+
# Acquire the thread lock before writing to the database
|
|
142
|
+
with kb_lock:
|
|
143
|
+
emb = shared_state["embeddings"]
|
|
144
|
+
emb.upsert(new_docs) # Insert new chunks (or update if IDs match)
|
|
145
|
+
emb.save(INDEX_DIR) # Persist the updated index to your Mac's hard drive
|
|
146
|
+
return f"Ingested {len(new_docs)} chunks using txtai FileTask workflow."
|
|
147
|
+
|
|
148
|
+
return "No supported files found in the selected path or archive."
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# ------------------------------------------------------------------------------
|
|
152
|
+
# SECTION 3B: CONVERSATION CHECKPOINTS (Cross-assistant handoff: Claude -> ChatGPT ...)
|
|
153
|
+
# ------------------------------------------------------------------------------
|
|
154
|
+
# Each checkpoint is one structured snapshot of a conversation about a topic.
|
|
155
|
+
# SQLite keeps the exact, ordered history per topic; the txtai index gets a copy
|
|
156
|
+
# (id "ctx#<row id>") so `resume` can find a topic by meaning, not just by name.
|
|
157
|
+
CONTEXT_DB = os.path.join(APP_DATA_DIR, "contexts.db")
|
|
158
|
+
CTX_PREFIX = "ctx#"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _ctx_conn() -> sqlite3.Connection:
|
|
162
|
+
conn = sqlite3.connect(CONTEXT_DB)
|
|
163
|
+
conn.row_factory = sqlite3.Row
|
|
164
|
+
conn.execute(
|
|
165
|
+
"""CREATE TABLE IF NOT EXISTS contexts (
|
|
166
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
167
|
+
topic TEXT NOT NULL,
|
|
168
|
+
topic_key TEXT NOT NULL,
|
|
169
|
+
source TEXT NOT NULL,
|
|
170
|
+
summary TEXT NOT NULL,
|
|
171
|
+
decisions TEXT NOT NULL DEFAULT '[]',
|
|
172
|
+
open_questions TEXT NOT NULL DEFAULT '[]',
|
|
173
|
+
next_steps TEXT NOT NULL DEFAULT '[]',
|
|
174
|
+
created_at TEXT NOT NULL
|
|
175
|
+
)"""
|
|
176
|
+
)
|
|
177
|
+
conn.execute("CREATE INDEX IF NOT EXISTS idx_ctx_topic ON contexts(topic_key, id)")
|
|
178
|
+
return conn
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _topic_key(topic: str) -> str:
|
|
182
|
+
return re.sub(r"[^a-z0-9]+", "-", topic.lower()).strip("-")
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _clean_list(items) -> list[str]:
|
|
186
|
+
if not items:
|
|
187
|
+
return []
|
|
188
|
+
if isinstance(items, str):
|
|
189
|
+
items = [items]
|
|
190
|
+
return [str(i).strip() for i in items if str(i).strip()]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _render_checkpoint(row: sqlite3.Row, full: bool = True) -> str:
|
|
194
|
+
"""Formats one checkpoint as readable text for the AI (and for indexing)."""
|
|
195
|
+
lines = [f"Topic: {row['topic']} | saved {row['created_at']} from {row['source']}",
|
|
196
|
+
f"Summary: {row['summary']}"]
|
|
197
|
+
if full:
|
|
198
|
+
for label, col in (("Decisions", "decisions"),
|
|
199
|
+
("Open questions", "open_questions"),
|
|
200
|
+
("Next steps", "next_steps")):
|
|
201
|
+
items = json.loads(row[col] or "[]")
|
|
202
|
+
if items:
|
|
203
|
+
lines.append(f"{label}:\n" + "\n".join(f" - {i}" for i in items))
|
|
204
|
+
return "\n".join(lines)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# Semantic topic matching thresholds (MiniLM cosine scores). Measured on real
|
|
208
|
+
# checkpoints: related phrasings score ~0.30+, unrelated ones up to ~0.20.
|
|
209
|
+
RESUME_MATCH_SCORE = 0.28 # at/above: resume this topic directly
|
|
210
|
+
RESUME_SUGGEST_SCORE = 0.15 # between: offer as "possible matches" instead of guessing
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _index_doc(row: sqlite3.Row) -> dict:
|
|
214
|
+
# Index only topic + summary: lists of decisions/steps dilute the embedding and
|
|
215
|
+
# measurably lower match scores for natural "where was I with X" queries.
|
|
216
|
+
return {"id": f"{CTX_PREFIX}{row['id']}", "source": f"context:{row['topic_key']}",
|
|
217
|
+
"text": f"{row['topic']}. {row['summary']}"}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _index_checkpoint(row: sqlite3.Row) -> None:
|
|
221
|
+
"""Copies a checkpoint into the txtai index so it is searchable by meaning."""
|
|
222
|
+
with kb_lock:
|
|
223
|
+
emb = shared_state["embeddings"]
|
|
224
|
+
if emb is None:
|
|
225
|
+
return # Models still loading; backfill_checkpoint_index covers it at load
|
|
226
|
+
emb.upsert([_index_doc(row)])
|
|
227
|
+
emb.save(INDEX_DIR)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def backfill_checkpoint_index(emb) -> int:
|
|
231
|
+
"""(Re)indexes every checkpoint at startup so the index matches SQLite. Returns count."""
|
|
232
|
+
with contextlib.closing(_ctx_conn()) as conn:
|
|
233
|
+
rows = conn.execute("SELECT * FROM contexts").fetchall()
|
|
234
|
+
if rows:
|
|
235
|
+
emb.upsert([_index_doc(r) for r in rows])
|
|
236
|
+
emb.save(INDEX_DIR)
|
|
237
|
+
return len(rows)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def save_checkpoint(topic: str, summary: str, decisions=None, open_questions=None,
|
|
241
|
+
next_steps=None, source: str = "unknown") -> dict:
|
|
242
|
+
topic, summary = (topic or "").strip(), (summary or "").strip()
|
|
243
|
+
if not topic or not summary:
|
|
244
|
+
raise ValueError("Both 'topic' and 'summary' are required.")
|
|
245
|
+
now = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
|
|
246
|
+
with contextlib.closing(_ctx_conn()) as conn, conn:
|
|
247
|
+
cur = conn.execute(
|
|
248
|
+
"""INSERT INTO contexts (topic, topic_key, source, summary, decisions,
|
|
249
|
+
open_questions, next_steps, created_at)
|
|
250
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
|
|
251
|
+
(topic, _topic_key(topic), (source or "unknown").strip().lower(), summary,
|
|
252
|
+
json.dumps(_clean_list(decisions)), json.dumps(_clean_list(open_questions)),
|
|
253
|
+
json.dumps(_clean_list(next_steps)), now),
|
|
254
|
+
)
|
|
255
|
+
row = conn.execute("SELECT * FROM contexts WHERE id = ?", (cur.lastrowid,)).fetchone()
|
|
256
|
+
_index_checkpoint(row)
|
|
257
|
+
with contextlib.closing(_ctx_conn()) as conn:
|
|
258
|
+
count = conn.execute("SELECT COUNT(*) FROM contexts WHERE topic_key = ?",
|
|
259
|
+
(row["topic_key"],)).fetchone()[0]
|
|
260
|
+
return {"id": row["id"], "topic": row["topic"], "topic_key": row["topic_key"],
|
|
261
|
+
"checkpoints_for_topic": count, "saved_at": now}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
_STOPWORDS = {"the", "and", "was", "were", "where", "what", "with", "from", "that", "this",
|
|
265
|
+
"about", "left", "off", "pick", "resume", "continue", "my", "our", "your",
|
|
266
|
+
"project", "thing", "work", "chat", "conversation", "were", "have", "had"}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _find_topic_key(query: str) -> tuple[str | None, list[str]]:
|
|
270
|
+
"""Returns (topic_key, suggestions). Exact topic name first, then a confident semantic
|
|
271
|
+
match, then a keyword match. If only weak semantic matches exist, returns them as
|
|
272
|
+
suggestions (topic names) rather than guessing."""
|
|
273
|
+
key = _topic_key(query)
|
|
274
|
+
with contextlib.closing(_ctx_conn()) as conn:
|
|
275
|
+
if key and conn.execute("SELECT 1 FROM contexts WHERE topic_key = ? LIMIT 1",
|
|
276
|
+
(key,)).fetchone():
|
|
277
|
+
return key, []
|
|
278
|
+
|
|
279
|
+
with kb_lock:
|
|
280
|
+
emb = shared_state["embeddings"]
|
|
281
|
+
hits = []
|
|
282
|
+
if emb is not None and emb.count():
|
|
283
|
+
hits = emb.search(
|
|
284
|
+
"select id, score from txtai where similar(:q) and id like 'ctx#%'",
|
|
285
|
+
10, parameters={"q": query},
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
scored: dict[str, tuple[float, str]] = {} # topic_key -> (best score, topic name)
|
|
289
|
+
with contextlib.closing(_ctx_conn()) as conn:
|
|
290
|
+
for hit in hits:
|
|
291
|
+
row = conn.execute("SELECT topic, topic_key FROM contexts WHERE id = ?",
|
|
292
|
+
(int(str(hit["id"])[len(CTX_PREFIX):]),)).fetchone()
|
|
293
|
+
if row and hit["score"] > scored.get(row["topic_key"], (-1, ""))[0]:
|
|
294
|
+
scored[row["topic_key"]] = (hit["score"], row["topic"])
|
|
295
|
+
ranked = sorted(scored.items(), key=lambda kv: kv[1][0], reverse=True)
|
|
296
|
+
if ranked and ranked[0][1][0] >= RESUME_MATCH_SCORE:
|
|
297
|
+
return ranked[0][0], []
|
|
298
|
+
|
|
299
|
+
words = [w for w in re.findall(r"[a-z0-9]+", query.lower())
|
|
300
|
+
if len(w) > 2 and w not in _STOPWORDS]
|
|
301
|
+
if words:
|
|
302
|
+
clause = " OR ".join(["lower(topic || ' ' || summary) LIKE ?"] * len(words))
|
|
303
|
+
with contextlib.closing(_ctx_conn()) as conn:
|
|
304
|
+
row = conn.execute(f"SELECT topic_key FROM contexts WHERE {clause} "
|
|
305
|
+
"ORDER BY id DESC LIMIT 1",
|
|
306
|
+
[f"%{w}%" for w in words]).fetchone()
|
|
307
|
+
if row:
|
|
308
|
+
return row["topic_key"], []
|
|
309
|
+
|
|
310
|
+
return None, [name for _, (score, name) in ranked if score >= RESUME_SUGGEST_SCORE][:3]
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def list_checkpoint_topics(limit: int = 20) -> list[dict]:
|
|
314
|
+
with contextlib.closing(_ctx_conn()) as conn:
|
|
315
|
+
rows = conn.execute(
|
|
316
|
+
"""SELECT c.topic, c.topic_key, c.source, c.created_at, t.n
|
|
317
|
+
FROM contexts c
|
|
318
|
+
JOIN (SELECT topic_key, MAX(id) AS last_id, COUNT(*) AS n
|
|
319
|
+
FROM contexts GROUP BY topic_key) t ON c.id = t.last_id
|
|
320
|
+
ORDER BY c.id DESC LIMIT ?""", (limit,)).fetchall()
|
|
321
|
+
return [dict(r) for r in rows]
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def resume_context(query: str, history: int = 3, include_kb: bool = True) -> str:
|
|
325
|
+
key, suggestions = _find_topic_key(query or "")
|
|
326
|
+
if key is None:
|
|
327
|
+
if suggestions:
|
|
328
|
+
names = "\n".join(f"- {s}" for s in suggestions)
|
|
329
|
+
return (f"No confident match for '{query}'. Possible matches:\n{names}\n"
|
|
330
|
+
"If one of these is what the user means, call resume again with that "
|
|
331
|
+
"exact topic; otherwise ask the user which topic to resume.")
|
|
332
|
+
topics = list_checkpoint_topics()
|
|
333
|
+
listing = "\n".join(f"- {t['topic']} (last saved {t['created_at']} from {t['source']})"
|
|
334
|
+
for t in topics) or "(none saved yet)"
|
|
335
|
+
return (f"No saved context matches '{query}'. Saved topics:\n{listing}\n"
|
|
336
|
+
"Call resume again with the exact topic the user means.")
|
|
337
|
+
|
|
338
|
+
with contextlib.closing(_ctx_conn()) as conn:
|
|
339
|
+
rows = conn.execute("SELECT * FROM contexts WHERE topic_key = ? ORDER BY id DESC LIMIT ?",
|
|
340
|
+
(key, max(1, history))).fetchall()
|
|
341
|
+
total = conn.execute("SELECT COUNT(*) FROM contexts WHERE topic_key = ?",
|
|
342
|
+
(key,)).fetchone()[0]
|
|
343
|
+
|
|
344
|
+
latest, earlier = rows[0], rows[1:]
|
|
345
|
+
out = [f"RESUMING '{latest['topic']}' ({total} checkpoint(s) saved; latest shown first).",
|
|
346
|
+
"", "== Latest checkpoint ==", _render_checkpoint(latest)]
|
|
347
|
+
if earlier:
|
|
348
|
+
out += ["", "== Earlier checkpoints (oldest last) =="]
|
|
349
|
+
out += [_render_checkpoint(r, full=False) for r in earlier]
|
|
350
|
+
|
|
351
|
+
if include_kb:
|
|
352
|
+
with kb_lock:
|
|
353
|
+
emb = shared_state["embeddings"]
|
|
354
|
+
related = []
|
|
355
|
+
if emb is not None and emb.count():
|
|
356
|
+
related = emb.search(
|
|
357
|
+
"select id, text, score from txtai where similar(:q) and id not like 'ctx#%'",
|
|
358
|
+
3, parameters={"q": f"{latest['topic']} {latest['summary']}"},
|
|
359
|
+
)
|
|
360
|
+
related = [r for r in related if r["score"] >= 0.3]
|
|
361
|
+
if related:
|
|
362
|
+
out += ["", "== Related knowledge-base material =="]
|
|
363
|
+
out += [f"[{r['score']:.2f}] {r['text'][:600]}" for r in related]
|
|
364
|
+
|
|
365
|
+
out += ["", "Continue from the latest checkpoint. When this conversation reaches a new "
|
|
366
|
+
"decision or stopping point, call save_context with the same topic."]
|
|
367
|
+
return "\n".join(out)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
# ------------------------------------------------------------------------------
|
|
371
|
+
# SECTION 4: FASTAPI & MCP (MODEL CONTEXT PROTOCOL) SERVER SETUP
|
|
372
|
+
# ------------------------------------------------------------------------------
|
|
373
|
+
# Create an MCP v2 server instance named "LocalKB". AI assistants like Claude or
|
|
374
|
+
# Cursor can connect to this to discover and call the @mcp.tool() functions below.
|
|
375
|
+
mcp = MCPServer(
|
|
376
|
+
"MemBannk",
|
|
377
|
+
instructions=(
|
|
378
|
+
"MemBannk is the user's personal memory shared across all their AI assistants "
|
|
379
|
+
"(Claude, ChatGPT, Gemini, Grok). When the user says resume / continue / pick up "
|
|
380
|
+
"where I left off, or refers to earlier work you have no context for, call resume "
|
|
381
|
+
"first. When they say save / checkpoint / hand off, or a conversation reaches a "
|
|
382
|
+
"decision or stopping point, call save_context with a concise, self-contained "
|
|
383
|
+
"summary that another assistant could continue from without this chat."
|
|
384
|
+
),
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
@mcp.tool()
|
|
389
|
+
def search_kb(query: str, limit: int = 3) -> str:
|
|
390
|
+
"""MCP Tool: Search the local macOS Knowledge Base by meaning (semantic search)."""
|
|
391
|
+
with kb_lock:
|
|
392
|
+
emb = shared_state["embeddings"]
|
|
393
|
+
if not emb or not emb.count():
|
|
394
|
+
return "Knowledge Base is currently empty."
|
|
395
|
+
results = emb.search(query, limit=limit)
|
|
396
|
+
|
|
397
|
+
if not results:
|
|
398
|
+
return "No matching results found."
|
|
399
|
+
|
|
400
|
+
# Format the matching results into clean, readable text for the AI agent
|
|
401
|
+
formatted = []
|
|
402
|
+
for r in results:
|
|
403
|
+
formatted.append(f"[{r['score']:.2f}] Source: {r.get('source', r.get('id'))}\n{r['text']}")
|
|
404
|
+
return "\n\n---\n\n".join(formatted)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
@mcp.tool()
|
|
408
|
+
def ingest_paths(paths: list[str]) -> str:
|
|
409
|
+
"""MCP Tool: Ingest local files, folders, or .zip archives into the Knowledge Base."""
|
|
410
|
+
valid_paths = [
|
|
411
|
+
os.path.expanduser(p) for p in paths if os.path.exists(os.path.expanduser(p))
|
|
412
|
+
]
|
|
413
|
+
if not valid_paths:
|
|
414
|
+
return "Error: None of the provided file, folder, or .zip paths exist on disk."
|
|
415
|
+
try:
|
|
416
|
+
return run_ingestion_workflows(valid_paths)
|
|
417
|
+
except Exception as e:
|
|
418
|
+
return f"Ingestion failed: {e}"
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
@mcp.tool()
|
|
422
|
+
def kb_stats() -> str:
|
|
423
|
+
"""MCP Tool: Check how many text chunks are currently stored in the Knowledge Base."""
|
|
424
|
+
with kb_lock:
|
|
425
|
+
emb = shared_state["embeddings"]
|
|
426
|
+
count = emb.count() if emb else 0
|
|
427
|
+
return f"Total indexed chunks: {count}"
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
@mcp.tool()
|
|
431
|
+
def save_context(
|
|
432
|
+
topic: str,
|
|
433
|
+
summary: str,
|
|
434
|
+
decisions: list[str] | None = None,
|
|
435
|
+
open_questions: list[str] | None = None,
|
|
436
|
+
next_steps: list[str] | None = None,
|
|
437
|
+
source: str = "unknown",
|
|
438
|
+
) -> str:
|
|
439
|
+
"""Save a checkpoint of the current conversation so any AI assistant can resume it later.
|
|
440
|
+
|
|
441
|
+
Call when the user says "save this", "checkpoint", "hand off", "remember where we are",
|
|
442
|
+
or when the conversation reaches a decision or natural stopping point.
|
|
443
|
+
|
|
444
|
+
Args:
|
|
445
|
+
topic: Short, stable name for the thread (e.g. "MemBannk launch plan"). Reuse the
|
|
446
|
+
exact same topic for later checkpoints of the same thread.
|
|
447
|
+
summary: Self-contained summary of where things stand: goal, context, what was
|
|
448
|
+
done and concluded. Write it so another assistant with no chat history can
|
|
449
|
+
continue. A few paragraphs at most.
|
|
450
|
+
decisions: Decisions made so far, one per item.
|
|
451
|
+
open_questions: Unresolved questions, one per item.
|
|
452
|
+
next_steps: Concrete next actions, one per item.
|
|
453
|
+
source: Which assistant is saving: "claude", "chatgpt", "gemini", "grok", ...
|
|
454
|
+
"""
|
|
455
|
+
try:
|
|
456
|
+
r = save_checkpoint(topic, summary, decisions, open_questions, next_steps, source)
|
|
457
|
+
except ValueError as e:
|
|
458
|
+
return f"Error: {e}"
|
|
459
|
+
return (f"Saved checkpoint #{r['id']} for '{r['topic']}' "
|
|
460
|
+
f"({r['checkpoints_for_topic']} checkpoint(s) on this topic). "
|
|
461
|
+
f"Resume anywhere with: resume('{r['topic']}').")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
@mcp.tool()
|
|
465
|
+
def resume(query: str, history: int = 3, include_kb: bool = True) -> str:
|
|
466
|
+
"""Load the saved context for a conversation thread started in any AI assistant.
|
|
467
|
+
|
|
468
|
+
Call FIRST when the user says "resume", "continue", "pick up where I left off", or
|
|
469
|
+
mentions earlier work you have no context for. Matches the topic by exact name,
|
|
470
|
+
then by meaning, then by keyword. Returns the latest checkpoint, earlier checkpoints,
|
|
471
|
+
and related knowledge-base material. If nothing matches, lists the saved topics.
|
|
472
|
+
|
|
473
|
+
Args:
|
|
474
|
+
query: Topic name or a description of the thread (e.g. "the memory bank launch").
|
|
475
|
+
history: How many recent checkpoints to include (latest first).
|
|
476
|
+
include_kb: Also include related chunks from ingested documents.
|
|
477
|
+
"""
|
|
478
|
+
return resume_context(query, history, include_kb)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
@mcp.tool()
|
|
482
|
+
def list_topics(limit: int = 20) -> str:
|
|
483
|
+
"""List saved conversation topics, most recently updated first."""
|
|
484
|
+
topics = list_checkpoint_topics(limit)
|
|
485
|
+
if not topics:
|
|
486
|
+
return "No conversation checkpoints saved yet."
|
|
487
|
+
return "\n".join(f"- {t['topic']}: {t['n']} checkpoint(s), last saved {t['created_at']} "
|
|
488
|
+
f"from {t['source']}" for t in topics)
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
# Build the HTTP sub-application for MCP. Doing this first initializes
|
|
492
|
+
# `mcp.session_manager`, which we start inside FastAPI's lifespan below.
|
|
493
|
+
# streamable_http_path="/" so the endpoint is /mcp (mounted below), not /mcp/mcp.
|
|
494
|
+
mcp_app = mcp.streamable_http_app(streamable_http_path="/")
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
@contextlib.asynccontextmanager
|
|
498
|
+
async def lifespan(app: FastAPI):
|
|
499
|
+
"""Starts and cleanly shuts down the MCP session manager alongside FastAPI."""
|
|
500
|
+
async with mcp.session_manager.run():
|
|
501
|
+
yield
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
# Create the main FastAPI web application and attach the MCP server at "/mcp"
|
|
505
|
+
api = FastAPI(title="LocalKB API & MCP", lifespan=lifespan)
|
|
506
|
+
api.mount("/mcp", mcp_app)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
class PathTokenGate:
|
|
510
|
+
"""ASGI wrapper. When MEMBANNK_PATH_TOKEN is set, only /<token>/... is served (with the
|
|
511
|
+
token stripped before routing); everything else, including /health, returns 404.
|
|
512
|
+
It also serves /mcp directly as /mcp/, so clients are never redirected (a redirect
|
|
513
|
+
would drop the token from the URL)."""
|
|
514
|
+
|
|
515
|
+
def __init__(self, app, prefix: str):
|
|
516
|
+
self.app, self.prefix = app, prefix
|
|
517
|
+
|
|
518
|
+
async def __call__(self, scope, receive, send):
|
|
519
|
+
if scope["type"] in ("http", "websocket"):
|
|
520
|
+
path = scope.get("path", "")
|
|
521
|
+
if path != self.prefix and not path.startswith(self.prefix + "/"):
|
|
522
|
+
if scope["type"] == "http":
|
|
523
|
+
await send({"type": "http.response.start", "status": 404,
|
|
524
|
+
"headers": [(b"content-type", b"text/plain")]})
|
|
525
|
+
await send({"type": "http.response.body", "body": b"Not Found"})
|
|
526
|
+
return
|
|
527
|
+
inner = path[len(self.prefix):] or "/"
|
|
528
|
+
if inner == "/mcp":
|
|
529
|
+
inner = "/mcp/"
|
|
530
|
+
scope = dict(scope, path=inner, raw_path=inner.encode())
|
|
531
|
+
await self.app(scope, receive, send)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
server_app = PathTokenGate(api, BASE_PATH)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
# Pydantic model defining the expected JSON body for POST /ingest requests
|
|
538
|
+
class IngestRequest(BaseModel):
|
|
539
|
+
paths: list[str]
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
@api.post("/ingest")
|
|
543
|
+
def api_ingest(req: IngestRequest):
|
|
544
|
+
"""Standard HTTP REST endpoint to ingest files, folders, or .zip archives."""
|
|
545
|
+
valid_paths = [
|
|
546
|
+
os.path.expanduser(p) for p in req.paths if os.path.exists(os.path.expanduser(p))
|
|
547
|
+
]
|
|
548
|
+
if not valid_paths:
|
|
549
|
+
raise HTTPException(status_code=400, detail="No valid local paths provided.")
|
|
550
|
+
try:
|
|
551
|
+
message = run_ingestion_workflows(valid_paths)
|
|
552
|
+
return {"status": "ok", "message": message}
|
|
553
|
+
except Exception as e:
|
|
554
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
@api.get("/search")
|
|
558
|
+
def api_search(query: str, limit: int = 3):
|
|
559
|
+
"""Standard HTTP REST endpoint for semantic search."""
|
|
560
|
+
with kb_lock:
|
|
561
|
+
emb = shared_state["embeddings"]
|
|
562
|
+
if not emb or not emb.count():
|
|
563
|
+
return {"results": []}
|
|
564
|
+
return {"results": emb.search(query, limit=limit)}
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
@api.get("/health")
|
|
568
|
+
def health():
|
|
569
|
+
"""Simple health-check endpoint to verify the server is running."""
|
|
570
|
+
with kb_lock:
|
|
571
|
+
emb = shared_state["embeddings"]
|
|
572
|
+
return {"status": "ok", "indexed_chunks": emb.count() if emb else 0}
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def start_tunnel() -> str:
|
|
576
|
+
"""Opens an ngrok tunnel to the local server using ngrok's Python SDK (no separate
|
|
577
|
+
ngrok binary needed). Returns the public MCP URL to paste into ChatGPT / Gemini / Claude."""
|
|
578
|
+
import ngrok # imported lazily: only needed when the tunnel is on
|
|
579
|
+
|
|
580
|
+
token = os.environ.get("NGROK_AUTHTOKEN", "").strip()
|
|
581
|
+
token_file = os.path.expanduser("~/.membannk/ngrok_auth")
|
|
582
|
+
if not token and os.path.exists(token_file):
|
|
583
|
+
with open(token_file) as f:
|
|
584
|
+
token = f.read().strip()
|
|
585
|
+
if not token:
|
|
586
|
+
raise RuntimeError("No ngrok authtoken. Run `membannk --set-ngrok-token <token>` "
|
|
587
|
+
"or set NGROK_AUTHTOKEN.")
|
|
588
|
+
options = {"authtoken": token}
|
|
589
|
+
domain = os.environ.get("MEMBANNK_NGROK_DOMAIN", "").strip()
|
|
590
|
+
if domain:
|
|
591
|
+
options["domain"] = domain.removeprefix("https://").strip("/")
|
|
592
|
+
listener = ngrok.forward(f"{HOST}:{PORT}", **options)
|
|
593
|
+
return f"{listener.url()}{BASE_PATH}/mcp"
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def start_api_server():
|
|
597
|
+
"""Runs the FastAPI + MCP web server (default http://127.0.0.1:8000)."""
|
|
598
|
+
uvicorn.run(server_app, host=HOST, port=PORT, log_level="warning")
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
# ------------------------------------------------------------------------------
|
|
602
|
+
# SECTION 5: BACKGROUND WORKER THREADS (Keeping the Desktop UI Responsive)
|
|
603
|
+
# ------------------------------------------------------------------------------
|
|
604
|
+
# In desktop apps, if you download models or transcribe a video on the main UI
|
|
605
|
+
# thread, the macOS spinning beachball appears. QThread runs heavy work in the
|
|
606
|
+
# background and uses 'Signal' to safely send updates back to the UI window.
|
|
607
|
+
|
|
608
|
+
class ModelLoader(QThread):
|
|
609
|
+
"""Downloads/loads txtai models in the background right after the window opens."""
|
|
610
|
+
loaded = Signal(object, object, object) # Emits (embeddings, doc_workflow, media_workflow)
|
|
611
|
+
status = Signal(str) # Emits progress text to display in the UI
|
|
612
|
+
|
|
613
|
+
def run(self):
|
|
614
|
+
self.status.emit("Loading txtai, FileTask workflows & models...")
|
|
615
|
+
|
|
616
|
+
# Import txtai inside the background thread so the window pops open instantly
|
|
617
|
+
from txtai import Embeddings
|
|
618
|
+
from txtai.pipeline import Textractor, Transcription
|
|
619
|
+
from txtai.workflow import Workflow, FileTask
|
|
620
|
+
|
|
621
|
+
# Initialize the embeddings database (downloads ~80 MB MiniLM model on first run)
|
|
622
|
+
embeddings = Embeddings(path="sentence-transformers/all-MiniLM-L6-v2", content=True)
|
|
623
|
+
if os.path.exists(INDEX_DIR):
|
|
624
|
+
embeddings.load(INDEX_DIR) # Reload existing Knowledge Base from disk if present
|
|
625
|
+
with kb_lock: # Index any conversation checkpoints saved before models were ready
|
|
626
|
+
backfill_checkpoint_index(embeddings)
|
|
627
|
+
|
|
628
|
+
# Initialize Docling parser (for documents) and Whisper (for video/audio)
|
|
629
|
+
textractor = Textractor(sections=True, backend="docling")
|
|
630
|
+
transcriber = Transcription("openai/whisper-base")
|
|
631
|
+
|
|
632
|
+
# Wrap pipelines in txtai FileTask workflows with regex file filters.
|
|
633
|
+
# `unpack=True` tells txtai to automatically unzip .zip/.tar archives.
|
|
634
|
+
doc_workflow = Workflow([
|
|
635
|
+
FileTask(textractor, r"\.(md|txt|pdf)$", unpack=True)
|
|
636
|
+
])
|
|
637
|
+
media_workflow = Workflow([
|
|
638
|
+
FileTask(transcriber, r"\.(mp4|mov|mkv|mp3|wav)$", unpack=True)
|
|
639
|
+
])
|
|
640
|
+
|
|
641
|
+
# Notify the main window that everything is loaded and ready
|
|
642
|
+
self.loaded.emit(embeddings, doc_workflow, media_workflow)
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
class IngestWorker(QThread):
|
|
646
|
+
"""Runs file/zip ingestion in the background when you drop files into the window."""
|
|
647
|
+
finished = Signal(str) # Emits completion message when done
|
|
648
|
+
|
|
649
|
+
def __init__(self, file_paths):
|
|
650
|
+
super().__init__()
|
|
651
|
+
self.file_paths = file_paths
|
|
652
|
+
|
|
653
|
+
def run(self):
|
|
654
|
+
try:
|
|
655
|
+
msg = run_ingestion_workflows(self.file_paths)
|
|
656
|
+
self.finished.emit(msg)
|
|
657
|
+
except Exception as e:
|
|
658
|
+
self.finished.emit(f"Workflow error: {e}")
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
# ------------------------------------------------------------------------------
|
|
662
|
+
# SECTION 6: MAIN DESKTOP CHAT WINDOW (PySide6 GUI)
|
|
663
|
+
# ------------------------------------------------------------------------------
|
|
664
|
+
class KBChatWindow(QMainWindow):
|
|
665
|
+
"""The standalone macOS window containing the status bar, chat log, and input controls."""
|
|
666
|
+
|
|
667
|
+
def __init__(self):
|
|
668
|
+
super().__init__()
|
|
669
|
+
self.setWindowTitle("MemBannk")
|
|
670
|
+
self.resize(750, 600)
|
|
671
|
+
self.setAcceptDrops(True) # Allow dragging files/folders onto this window
|
|
672
|
+
|
|
673
|
+
# Create the main layout container
|
|
674
|
+
central = QWidget()
|
|
675
|
+
self.setCentralWidget(central)
|
|
676
|
+
layout = QVBoxLayout(central)
|
|
677
|
+
|
|
678
|
+
# 1. Top status label
|
|
679
|
+
self.status_label = QLabel("Starting up...")
|
|
680
|
+
layout.addWidget(self.status_label)
|
|
681
|
+
|
|
682
|
+
# 2. Middle scrollable chat history area
|
|
683
|
+
self.chat_display = QTextBrowser()
|
|
684
|
+
self.chat_display.setAcceptDrops(False) # Pass drag events up to QMainWindow
|
|
685
|
+
layout.addWidget(self.chat_display)
|
|
686
|
+
|
|
687
|
+
# 3. Bottom horizontal row: [+ Add Files button] [Question input box] [Ask button]
|
|
688
|
+
input_row = QHBoxLayout()
|
|
689
|
+
|
|
690
|
+
self.add_btn = QPushButton("+ Add Files / Zip / Videos")
|
|
691
|
+
self.add_btn.setEnabled(False) # Disabled until models finish loading
|
|
692
|
+
self.add_btn.clicked.connect(self.select_files)
|
|
693
|
+
input_row.addWidget(self.add_btn)
|
|
694
|
+
|
|
695
|
+
self.input_box = QLineEdit()
|
|
696
|
+
self.input_box.setPlaceholderText(
|
|
697
|
+
"Drag & drop files, folders, or .zip archives, or ask a question..."
|
|
698
|
+
)
|
|
699
|
+
self.input_box.setEnabled(False)
|
|
700
|
+
self.input_box.returnPressed.connect(self.handle_query) # Trigger search on Enter key
|
|
701
|
+
input_row.addWidget(self.input_box)
|
|
702
|
+
|
|
703
|
+
self.send_btn = QPushButton("Ask")
|
|
704
|
+
self.send_btn.setEnabled(False)
|
|
705
|
+
self.send_btn.clicked.connect(self.handle_query)
|
|
706
|
+
input_row.addWidget(self.send_btn)
|
|
707
|
+
|
|
708
|
+
layout.addLayout(input_row)
|
|
709
|
+
|
|
710
|
+
# Start loading txtai models in the background right away
|
|
711
|
+
self.loader = ModelLoader()
|
|
712
|
+
self.loader.status.connect(self.on_status)
|
|
713
|
+
self.loader.loaded.connect(self.on_models_ready)
|
|
714
|
+
self.loader.start()
|
|
715
|
+
|
|
716
|
+
# --- Drag-and-Drop Event Handlers ---
|
|
717
|
+
def dragEnterEvent(self, event):
|
|
718
|
+
"""Accepts the drag hover if it contains local files and models are ready."""
|
|
719
|
+
if event.mimeData().hasUrls() and shared_state["embeddings"] is not None:
|
|
720
|
+
event.acceptProposedAction()
|
|
721
|
+
|
|
722
|
+
def dropEvent(self, event):
|
|
723
|
+
"""Extracts local file/folder paths when dropped and starts ingestion."""
|
|
724
|
+
files = [url.toLocalFile() for url in event.mimeData().urls() if url.isLocalFile()]
|
|
725
|
+
if files:
|
|
726
|
+
self.start_ingestion(files)
|
|
727
|
+
|
|
728
|
+
# --- UI Helper & Callback Methods ---
|
|
729
|
+
def append_chat(self, sender: str, html_text: str):
|
|
730
|
+
"""Appends a formatted message block to the chat window."""
|
|
731
|
+
self.chat_display.append(f"<p><b>{sender}:</b><br>{html_text}</p><hr>")
|
|
732
|
+
|
|
733
|
+
def on_status(self, msg: str):
|
|
734
|
+
"""Updates the top status bar and chat log during startup."""
|
|
735
|
+
self.status_label.setText(msg)
|
|
736
|
+
self.append_chat("System", msg)
|
|
737
|
+
|
|
738
|
+
def on_models_ready(self, embeddings, doc_workflow, media_workflow):
|
|
739
|
+
"""Called once ModelLoader finishes; enables controls and starts the MCP server."""
|
|
740
|
+
with kb_lock:
|
|
741
|
+
shared_state["embeddings"] = embeddings
|
|
742
|
+
shared_state["doc_workflow"] = doc_workflow
|
|
743
|
+
shared_state["media_workflow"] = media_workflow
|
|
744
|
+
|
|
745
|
+
# Start FastAPI + MCP server in a background daemon thread (auto-closes when app exits)
|
|
746
|
+
threading.Thread(target=start_api_server, daemon=True).start()
|
|
747
|
+
|
|
748
|
+
public_note = ""
|
|
749
|
+
if os.environ.get("MEMBANNK_TUNNEL") == "1":
|
|
750
|
+
try:
|
|
751
|
+
public_url = start_tunnel()
|
|
752
|
+
print(f"MemBannk public MCP URL: {public_url}", flush=True)
|
|
753
|
+
public_note = (f"<b>Public MCP URL (keep it secret):</b> "
|
|
754
|
+
f"<code>{public_url}</code><br>")
|
|
755
|
+
except Exception as e:
|
|
756
|
+
print(f"MemBannk: ngrok tunnel failed: {e}", flush=True)
|
|
757
|
+
public_note = f"<b>ngrok tunnel failed:</b> {e}<br>"
|
|
758
|
+
|
|
759
|
+
# Enable the UI buttons and text box
|
|
760
|
+
self.add_btn.setEnabled(True)
|
|
761
|
+
self.input_box.setEnabled(True)
|
|
762
|
+
self.send_btn.setEnabled(True)
|
|
763
|
+
|
|
764
|
+
self.status_label.setText(f"Ready | MCP: {MCP_URL} | REST: /ingest, /search")
|
|
765
|
+
self.append_chat(
|
|
766
|
+
"System",
|
|
767
|
+
"Ready! Drag & drop files, folders, or <b>.zip</b> archives into this window.<br>"
|
|
768
|
+
+ public_note +
|
|
769
|
+
f"<b>MCP Endpoint:</b> <code>{MCP_URL}</code> "
|
|
770
|
+
"(tools: <code>resume</code>, <code>save_context</code>, <code>list_topics</code>, "
|
|
771
|
+
"<code>search_kb</code>, <code>ingest_paths</code>, <code>kb_stats</code>)<br>"
|
|
772
|
+
"<b>REST Endpoints:</b> <code>POST /ingest</code>, <code>GET /search</code>, <code>GET /health</code>",
|
|
773
|
+
)
|
|
774
|
+
|
|
775
|
+
def select_files(self):
|
|
776
|
+
"""Opens the native macOS Finder dialog to choose files or .zip archives."""
|
|
777
|
+
files, _ = QFileDialog.getOpenFileNames(
|
|
778
|
+
self,
|
|
779
|
+
"Select Markdown, PDFs, Zip Archives, or Videos",
|
|
780
|
+
"",
|
|
781
|
+
"Supported Files (*.md *.txt *.pdf *.zip *.mp4 *.mov *.mkv *.mp3 *.wav)",
|
|
782
|
+
)
|
|
783
|
+
if files:
|
|
784
|
+
self.start_ingestion(files)
|
|
785
|
+
|
|
786
|
+
def start_ingestion(self, files: list[str]):
|
|
787
|
+
"""Disables the add button and launches IngestWorker in the background."""
|
|
788
|
+
self.add_btn.setEnabled(False)
|
|
789
|
+
self.status_label.setText(f"Ingesting {len(files)} item(s)...")
|
|
790
|
+
self.append_chat("System", f"Ingesting {len(files)} item(s) via txtai FileTask workflow...")
|
|
791
|
+
|
|
792
|
+
self.worker = IngestWorker(files)
|
|
793
|
+
self.worker.finished.connect(self.on_ingest_done)
|
|
794
|
+
self.worker.start()
|
|
795
|
+
|
|
796
|
+
def on_ingest_done(self, message: str):
|
|
797
|
+
"""Re-enables the add button and displays the ingestion summary."""
|
|
798
|
+
self.add_btn.setEnabled(True)
|
|
799
|
+
self.status_label.setText(f"Ready | MCP: {MCP_URL} | REST: /ingest, /search")
|
|
800
|
+
self.append_chat("System", message)
|
|
801
|
+
|
|
802
|
+
def handle_query(self):
|
|
803
|
+
"""Runs a semantic search on the user's typed question and shows top 3 matches."""
|
|
804
|
+
query = self.input_box.text().strip()
|
|
805
|
+
if not query:
|
|
806
|
+
return
|
|
807
|
+
|
|
808
|
+
self.input_box.clear()
|
|
809
|
+
self.append_chat("You", query)
|
|
810
|
+
|
|
811
|
+
# Safely query the shared txtai embeddings database
|
|
812
|
+
with kb_lock:
|
|
813
|
+
emb = shared_state["embeddings"]
|
|
814
|
+
if not emb or not emb.count():
|
|
815
|
+
self.append_chat(
|
|
816
|
+
"KB", "Knowledge Base is empty. Drag & drop files or a .zip archive first."
|
|
817
|
+
)
|
|
818
|
+
return
|
|
819
|
+
results = emb.search(query, limit=3)
|
|
820
|
+
|
|
821
|
+
# Format each search hit with its similarity score, source name, and text snippet
|
|
822
|
+
formatted = []
|
|
823
|
+
for r in results:
|
|
824
|
+
snippet = r["text"].replace("\n", " ")[:350]
|
|
825
|
+
formatted.append(f"<b>[{r['score']:.2f}] {r['source']}</b><br><i>{snippet}...</i>")
|
|
826
|
+
|
|
827
|
+
self.append_chat("KB", "<br><br>".join(formatted))
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
# ------------------------------------------------------------------------------
|
|
831
|
+
# SECTION 7: APPLICATION ENTRY POINT
|
|
832
|
+
# ------------------------------------------------------------------------------
|
|
833
|
+
def main():
|
|
834
|
+
# Create the Qt application, show our main window, and start the event loop
|
|
835
|
+
app = QApplication(sys.argv)
|
|
836
|
+
window = KBChatWindow()
|
|
837
|
+
window.show()
|
|
838
|
+
window.raise_()
|
|
839
|
+
sys.exit(app.exec())
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
if __name__ == "__main__":
|
|
843
|
+
main()
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Command line entry point: `membannk`.
|
|
2
|
+
|
|
3
|
+
membannk start the desktop app + local MCP server
|
|
4
|
+
membannk --tunnel ... and expose it through ngrok with a secret URL
|
|
5
|
+
membannk --set-ngrok-token TOKEN save your ngrok authtoken (once)
|
|
6
|
+
membannk --show-url print the MCP URL(s) without starting anything
|
|
7
|
+
membannk --new-secret replace the secret path (old public URLs stop working)
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import os
|
|
12
|
+
import secrets
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
|
|
17
|
+
CONFIG_DIR = os.path.expanduser("~/.membannk")
|
|
18
|
+
NGROK_TOKEN_FILE = os.path.join(CONFIG_DIR, "ngrok_auth")
|
|
19
|
+
PATH_TOKEN_FILE = os.path.join(CONFIG_DIR, "path_token")
|
|
20
|
+
DOMAIN_FILE = os.path.join(CONFIG_DIR, "ngrok_domain")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _write_private(path: str, value: str) -> None:
|
|
24
|
+
os.makedirs(CONFIG_DIR, mode=0o700, exist_ok=True)
|
|
25
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
26
|
+
with os.fdopen(fd, "w") as f:
|
|
27
|
+
f.write(value.strip() + "\n")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _read(path: str) -> str:
|
|
31
|
+
if os.path.exists(path):
|
|
32
|
+
with open(path) as f:
|
|
33
|
+
return f.read().strip()
|
|
34
|
+
return ""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _path_token(renew: bool = False) -> str:
|
|
38
|
+
token = "" if renew else _read(PATH_TOKEN_FILE)
|
|
39
|
+
if not token:
|
|
40
|
+
token = secrets.token_urlsafe(24)
|
|
41
|
+
_write_private(PATH_TOKEN_FILE, token)
|
|
42
|
+
return token
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(argv=None) -> None:
|
|
46
|
+
p = argparse.ArgumentParser(prog="membannk", description=__doc__,
|
|
47
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
48
|
+
p.add_argument("--tunnel", action="store_true",
|
|
49
|
+
help="expose the MCP server through ngrok (for ChatGPT / Gemini / claude.ai)")
|
|
50
|
+
p.add_argument("--port", type=int, default=int(os.environ.get("MEMBANNK_PORT", "8000")))
|
|
51
|
+
p.add_argument("--domain", help="your static ngrok domain (saved for next time)")
|
|
52
|
+
p.add_argument("--set-ngrok-token", metavar="TOKEN", help="save your ngrok authtoken and exit")
|
|
53
|
+
p.add_argument("--show-url", action="store_true", help="print the MCP URL(s) and exit")
|
|
54
|
+
p.add_argument("--new-secret", action="store_true",
|
|
55
|
+
help="generate a new secret URL path and exit")
|
|
56
|
+
p.add_argument("--version", action="version", version=f"membannk {__version__}")
|
|
57
|
+
args = p.parse_args(argv)
|
|
58
|
+
|
|
59
|
+
if args.set_ngrok_token:
|
|
60
|
+
_write_private(NGROK_TOKEN_FILE, args.set_ngrok_token)
|
|
61
|
+
print(f"Saved ngrok authtoken to {NGROK_TOKEN_FILE}")
|
|
62
|
+
return
|
|
63
|
+
if args.new_secret:
|
|
64
|
+
_path_token(renew=True)
|
|
65
|
+
print("New secret path saved. Update the MCP URL in your assistants (membannk --show-url).")
|
|
66
|
+
return
|
|
67
|
+
if args.domain:
|
|
68
|
+
_write_private(DOMAIN_FILE, args.domain)
|
|
69
|
+
|
|
70
|
+
os.environ["MEMBANNK_PORT"] = str(args.port)
|
|
71
|
+
domain = os.environ.get("MEMBANNK_NGROK_DOMAIN") or _read(DOMAIN_FILE)
|
|
72
|
+
if domain:
|
|
73
|
+
os.environ["MEMBANNK_NGROK_DOMAIN"] = domain
|
|
74
|
+
|
|
75
|
+
if args.tunnel or args.show_url:
|
|
76
|
+
# Anything reachable from the internet must sit behind a secret path.
|
|
77
|
+
os.environ.setdefault("MEMBANNK_PATH_TOKEN", _path_token())
|
|
78
|
+
|
|
79
|
+
if args.show_url:
|
|
80
|
+
base = f"/{os.environ['MEMBANNK_PATH_TOKEN']}"
|
|
81
|
+
print(f"Local: http://127.0.0.1:{args.port}/mcp (when started without --tunnel)")
|
|
82
|
+
print(f"Local: http://127.0.0.1:{args.port}{base}/mcp (when started with --tunnel)")
|
|
83
|
+
if domain:
|
|
84
|
+
print(f"Public: https://{domain.removeprefix('https://').strip('/')}{base}/mcp")
|
|
85
|
+
else:
|
|
86
|
+
print("Public: shown in the app window once `membannk --tunnel` is running "
|
|
87
|
+
"(set --domain to keep it fixed)")
|
|
88
|
+
return
|
|
89
|
+
|
|
90
|
+
if args.tunnel:
|
|
91
|
+
os.environ["MEMBANNK_TUNNEL"] = "1"
|
|
92
|
+
if not (os.environ.get("NGROK_AUTHTOKEN") or _read(NGROK_TOKEN_FILE)):
|
|
93
|
+
sys.exit("No ngrok authtoken yet. Get one at https://dashboard.ngrok.com/get-started/"
|
|
94
|
+
"your-authtoken and run: membannk --set-ngrok-token <token>")
|
|
95
|
+
|
|
96
|
+
# Import after the environment is set: app.py reads its settings at import time.
|
|
97
|
+
from .app import main as run_app
|
|
98
|
+
run_app()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
if __name__ == "__main__":
|
|
102
|
+
main()
|