knoweldge-base README

The project's README from github.com/rgem227/knoweldge-base. As one markdown file: README.md.

Knowledge Base Phase 1

This repository contains the phase 1 minimum viable file knowledge base.

Current Stack

PostgreSQL and object storage are reserved for a later migration. The current version does not require Docker, MinIO, or a running database service.

Local development

  1. Copy the root environment template to backend/.env:
Copy-Item ..\.env.example .env
  1. Install dependencies:
cd backend
python -m venv .venv
.venv\Scripts\activate
pip install -r requirements.txt
  1. Initialize the SQLite database:
python -m app.db.init_db
  1. Run backend:
uvicorn app.main:app --reload

Verify

From the backend directory:

set PYTHONPATH=.
python -m pytest

PowerShell:

$env:PYTHONPATH = "."
python -m pytest

Initialize or recreate the SQLite tables:

python -m app.db.init_db

Runtime files are created under backend/data/:

The existing Docker Compose file is reserved for the later PostgreSQL and object storage migration. It is not required for the current phase.

Service start, restart, stop, and status commands are provided by the separate PowerShell control files under scripts/.

Current scope

Operational configuration is controlled through .env.example, backend/app/core/config.py, and the scripts under scripts/. The repository also includes a read-only REST API, OpenAPI endpoints, MCP integration, and the knowledge-base Skill under skills/knowledge-base/.

API examples

Log in and receive a token:

$body = @{
  username = "demo"
  password = "password-123"
} | ConvertTo-Json

Invoke-RestMethod `
  -Method Post `
  -Uri http://127.0.0.1:8000/api/v1/auth/login `
  -ContentType "application/json" `
  -Body $body

Upload a document:

$token = "<access_token>"
$knowledgeBaseId = 1

curl.exe `
  -X POST `
  "http://127.0.0.1:8000/api/v1/documents/upload" `
  -H "Authorization: Bearer $token" `
  -F "knowledge_base_id=$knowledgeBaseId" `
  -F "tags=制度,测试" `
  -F "file=@D:\path\to\guide.txt"

The generated API documentation is available at /docs.

Browser-local document preview

The frontend uses vue3-office-preview for DOCX, PPTX, XLS, and XLSX, @vue3-office/vue-pdf for PDF, and @deot/docs-markdown for Markdown. Files are fetched through the authenticated API into browser memory and rendered locally. No LibreOffice, ONLYOFFICE, Docker, or Python SDK is required for this preview path.

The original file remains in local storage. Markdown extraction and the legacy .doc, .xls, and .ppt fallback remain handled by the backend.

Folder API

Create a folder under a knowledge base:

$body = @{
  knowledge_base_id = 1
  name = "实验方案"
} | ConvertTo-Json

Invoke-RestMethod `
  -Method Post `
  -Uri http://127.0.0.1:8000/api/v1/folders `
  -Headers @{ Authorization = "Bearer $token" } `
  -ContentType "application/json" `
  -Body $body

Upload into a folder by adding folder_id to the multipart form. The web page does this automatically for the currently selected folder.

The knowledge base selector defaults to 全部. In this mode the page shows folders and root documents across all public knowledge bases. New folders are assigned to the knowledge base selected in the dialog; uploads from 全部 use the first available knowledge base unless a folder is selected.

MCP read-only service

The project includes a separate MCP service for agents. It shares the same SQLite database, local filesystem storage, JWT secret, and document reader as the FastAPI application. It supports local stdio and remote Streamable HTTP transports. Phase 1 exposes read-only tools:

The MCP process does not expose upload, move, delete, or folder-management operations. It uses the JWT identity from KB_MCP_TOKEN, so an agent cannot see documents that the corresponding user cannot read.

For local stdio clients, KB_MCP_TOKEN can be omitted. The agent must then call the authenticate tool once with the user's username and password; the short-lived session remains only in the MCP process memory.

Create the MCP environment once from PowerShell:

cd backend
python -m venv .mcp-venv
.\.mcp-venv\Scripts\python.exe -m pip install -r requirements-mcp.txt

Set the same database and storage settings as the API, then put a login access_token in KB_MCP_TOKEN:

$env:PYTHONPATH = "."
$env:KB_MCP_TOKEN = "<access_token>"
.\.mcp-venv\Scripts\python.exe -m app.mcp_server

The process speaks MCP over stdin/stdout. Do not add ordinary print() output to the service; diagnostics must go to stderr so the protocol remains valid.

For remote Streamable HTTP mode:

$env:PYTHONPATH = "."
$env:MCP_TRANSPORT = "streamable-http"
$env:MCP_HOST = "0.0.0.0"
$env:MCP_PORT = "8020"
$env:MCP_PATH = "/mcp"
$env:MCP_STATELESS_HTTP = "true"
.\.mcp-venv\Scripts\python.exe -m app.mcp_server

The remote endpoint is https://your-domain/mcp after HTTPS reverse proxy configuration. Remote clients must send Authorization: Bearer <access_token>. Configure the remote client with the same endpoint and protected Bearer credential used by the API connection.

The browser page /mcp-token.html reads the current logged-in account and requests an MCP Token without reading or storing the account password. The administrator page /admin.html is protected by the administrator role and allows user status, role, password, and MCP Token expiration policy changes.

Run the local protocol smoke test:

$env:PYTHONPATH = "."
.\.mcp-venv\Scripts\python.exe scripts\mcp_stdio_smoke.py

knoweldge-base (rgem227/knoweldge-base)

Searching Database…

Что это такое?Knowledge Base — это размещаемая у себя (self-hosted) личная или командная база знаний: вы загружаете документы во вложенные папки, смотрите их прямо в браузере, а ИИ-агенты могут читать их через MCP-сервис с доступом только на чтение. Это минимально работающая версия первой фазы.
Это облачный сервис или мне нужно запускать его самому?Это веб-приложение для самостоятельного размещения: бэкенд на FastAPI с базой данных SQLite и хранением файлов в локальной файловой системе, плюс фронтенд на Vue. В том же репозитории есть отдельный MCP-сервис для ИИ-агентов.
Как его запустить?Скопируйте корневой шаблон окружения в backend/.env, установите зависимости, инициализируйте базу данных SQLite и запустите бэкенд. PowerShell-скрипты в папке scripts/ отвечают за запуск, остановку, перезапуск и статус, а документация по API автоматически доступна по адресу /docs.
Нужен ли сначала Docker или сервер базы данных?Нет. Текущей версии не нужны Docker, MinIO или запущенная служба базы данных — достаточно SQLite и локальных файлов. Имеющийся файл Docker Compose оставлен на будущее, под переход на PostgreSQL и объектное хранилище.
Чего пока не умеет эта программа?Это явно заявленный MVP первой фазы: редактирование документов, мягкое удаление и восстановление доступны только владельцу, папки можно удалять только когда они пусты, а извлечение текста из старых форматов DOC, XLS и PPT работает как получится, без гарантии.
Какие файлы я могу туда загружать?При загрузке по одному файлу и пакетами поддерживаются PDF, текст, Markdown, HTML, изображения, файлы PowerPoint, Word и Excel, причём у каждого документа есть метаданные и теги.
Нужен ли LibreOffice или другой офисный сервер для предпросмотра в браузере?Нет — файлы загружаются через API с проверкой подлинности прямо в память браузера и отображаются локально компонентами Vue: vue3-office-preview для DOCX/PPTX/XLS(X), vue-pdf для PDF и docs-markdown для Markdown.
Кто может видеть мои документы?Доступ работает через созданных администратором пользователей и вход по JWT, а MCP-токены несут ту же личность из JWT, так что агент видит только те документы, которые может читать его пользователь. Файлы лежат в локальном хранилище с защитой от обхода путей, а администраторам доступны страницы журнала аудита.
Могу ли я вернуть документ, который удалил по ошибке?Да — удаление выполняется мягко: есть корзина со списком и восстановлением, и обе операции доступны только владельцу документа. Также можно копировать целые папки и документы между базами знаний, включая рекурсивное копирование папок.
Как ИИ-агенту войти в MCP-сервис?Либо положите долгоживущий токен доступа в переменную KBMCPTOKEN, либо для локальных stdio-клиентов не указывайте её и один раз вызовите инструмент authenticate с вашим именем пользователя и паролем — эта короткоживущая сессия хранится только в памяти процесса MCP. Страница /mcp-token.html выдаёт токены, не читая и не сохраняя ваш пароль.
А есть ли обычный REST API?Да — бэкенд предоставляет REST API только на чтение с эндпоинтами OpenAPI и сгенерированной документацией по адресу /docs. Удалённые MCP-клиенты подключаются через HTTPS reverse proxy с учётными данными Authorization: Bearer, а в репозитории также есть Skill для базы знаний в папке skills/knowledge-base/.
Creator
rgem227
Size
5.2 MB
Stars
293
Updated
CommitSep 22
Age
26d
Commits · 90 Days