From b124a12601da717d547dcd7df2d0b0e2eee66d61 Mon Sep 17 00:00:00 2001 From: lonpatovaadelina Date: Thu, 28 May 2026 13:43:33 +0000 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20README.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 223 ++++++++++++++++++++++-------------------------------- 1 file changed, 92 insertions(+), 131 deletions(-) diff --git a/README.md b/README.md index a6cd797..a8ac0ef 100644 --- a/README.md +++ b/README.md @@ -1,167 +1,128 @@ -# MCP‑Memory Server +# MCP‑сервер для управления памятью агента -A lightweight **Model Context Protocol (MCP)** server that exposes a simple API for storing and retrieving agent memory. -The project is built on top of the `fastmcp` framework and uses `pydantic` for data validation and `python-dotenv` to load configuration from `.env`. +## Описание проекта +MCP‑сервер (Model Context Protocol) – это независимый сервис, который предоставляет API для хранения и извлечения данных памяти агентов через единый протокол. Сервис реализован на `fastmcp`, использует `pydantic` для валидации входных/выходных структур и `python-dotenv` для загрузки переменных окружения. -> **TL;DR** – Run the server, then use `memory_client.py` (or any MCP‑compatible client) to store and fetch memory chunks. +Основные возможности: +- **Namespaces** – изоляция данных по логическим группам (например, пользователь, проект, агент). +- CRUD‑операции над записями памяти. +- Простая REST‑подобная API через MCP‑протокол. +- Легкая интеграция с другими агентами и сервисами. ---- +## Предварительные требования +| Пакет | Версия | +|-------|--------| +| Python | 3.10+ | +| pip | Любой актуальный | -## Table of Contents - -- [What is this?](#what-is-this) -- [Features](#features) -- [Prerequisites](#prerequisites) -- [Installation](#installation) -- [Running the Server](#running-the-server) -- [Using the Client](#using-the-client) -- [Example Workflow](#example-workflow) -- [License](#license) - ---- - -## What is this? - -The **MCP‑Memory Server** is a minimal, self‑contained service that: - -1. Accepts `PUT` and `GET` requests over MCP. -2. Stores memory entries in JSON files under a namespace hierarchy. -3. Supports simple pattern matching (`fnmatch`) for bulk retrieval. - -It’s ideal for prototyping multi‑agent systems where each agent can read/write to a shared knowledge base without worrying about the underlying storage format. - ---- - -## Features - -| Feature | Description | -|---------|-------------| -| **Namespace support** | Organize memory by logical groups (e.g., `agents/alpha`, `world/events`). | -| **Pattern matching** | Retrieve multiple entries with glob patterns (`*`, `?`). | -| **FastI/O** | Uses `fastmcp` for low‑latency communication. | -| **Configurable via `.env`** | Set the listening port, storage directory, and other options without code changes. | -| **Simple API** | Two endpoints: `/memory/{namespace}` (PUT) and `/memory/{namespace}/{key}` (GET). | - ---- - -## Prerequisites - -- Python 3.10 or newer -- `pip` (or any compatible package manager) - -The project relies on the following libraries: +Установите зависимости из `requirements.txt`: ```bash -fastmcp==0.1.2 # MCP framework -pydantic==2.5 # Data validation -python-dotenv==1.0 # Environment variable loader -``` - ---- - -## Installation - -```bash -# 1️⃣ Clone the repo (or copy the files) -git clone https://github.com/your-org/mcp-memory-server.git -cd mcp-memory-server - -# 2️⃣ Create a virtual environment (recommended) -python -m venv .venv -source .venv/bin/activate # On Windows: .\.venv\Scripts\activate - -# 3️⃣ Install dependencies pip install -r requirements.txt ``` -> **Tip** – If you don’t have a `requirements.txt`, create one with the packages listed above. +### Файлы проекта +- `memory_server.py` – основной серверный скрипт. +- `memory_client.py` – пример клиента, демонстрирующий работу с сервером. ---- +## Установка -## Running the Server +1. Клонируйте репозиторий: -The server reads configuration from a `.env` file. Create it in the project root: + ```bash + git clone https://github.com/your-org/memory-mcp-server.git + cd memory-mcp-server + ``` -```dotenv -# .env -MCP_PORT=8000 # Port to listen on -STORAGE_DIR=data/memory # Directory where JSON files are stored -``` +2. Создайте виртуальное окружение (необязательно, но рекомендуется): -Then start the server: + ```bash + python -m venv .venv + source .venv/bin/activate # Windows: .venv\Scripts\activate + ``` + +3. Установите зависимости: + + ```bash + pip install -r requirements.txt + ``` + +4. Создайте файл `.env` в корне проекта (если понадобится): + + ```dotenv + MCP_HOST=0.0.0.0 + MCP_PORT=8000 + MEMORY_FILE=data/memory.json + ``` + +## Запуск сервера ```bash python memory_server.py ``` -You should see something like: +Сервер будет слушать на порту, указанном в переменной `MCP_PORT` (по умолчанию 8000). Вы увидите лог‑сообщения о подключениях и выполненных запросах. -``` -[INFO] Memory-Server listening on http://localhost:8000 -``` - -The server will automatically create `data/memory` if it doesn’t exist. - ---- - -## Using the Client - -A minimal client is provided in `memory_client.py`. It demonstrates how to: - -1. Store a memory chunk. -2. Retrieve a single entry. -3. List entries with pattern matching. - -```bash -python memory_client.py -``` - -The script will output the results of each operation, e.g.: - -``` -Stored: {'key': 'greeting', 'value': 'Hello, world!'} -Fetched: {'key': 'greeting', 'value': 'Hello, world!'} -All greetings: [{'key': 'greeting', 'value': 'Hello, world!'}] -``` - ---- - -## Example Workflow - -Below is a quick walkthrough of how an agent might interact with the server. +## Пример использования клиента ```python -# 1️⃣ Import the client helper (or use any MCP library) +# memory_client_example.py from memory_client import MemoryClient client = MemoryClient(host="localhost", port=8000) -# 2️⃣ Store some facts under the "agents/alpha" namespace -client.put("agents/alpha", {"key": "location", "value": "office"}) -client.put("agents/alpha", {"key": "mood", "value": "curious"}) +# Создать запись в namespace "project_alpha" +record_id = client.create( + namespace="project_alpha", + key="task_42", + value={"status": "in_progress", "assigned_to": "agent_7"} +) +print(f"Создана запись с id: {record_id}") -# 3️⃣ Retrieve a specific fact -fact = client.get("agents/alpha/location") -print(fact) # {'key': 'location', 'value': 'office'} +# Получить запись +data = client.read(namespace="project_alpha", record_id=record_id) +print("Полученные данные:", data) -# 4️⃣ List all facts for the agent -all_facts = client.list("agents/alpha/*") -print(all_facts) +# Обновить запись +client.update( + namespace="project_alpha", + record_id=record_id, + value={"status": "completed"} +) + +# Удалить запись +client.delete(namespace="project_alpha", record_id=record_id) ``` -The server will persist these entries in: +Запустите пример: + +```bash +python memory_client_example.py +``` + +## Структура проекта ``` -data/memory/ -└── agents/ - └── alpha.json # contains [{"key":"location","value":"office"}, {"key":"mood","value":"curious"}] +memory-mcp-server/ +├── .env +├── requirements.txt +├── memory_server.py +├── memory_client.py +└── README.md +``` + +- `memory_server.py` – реализует класс `MemoryServer`, который инициализирует FastMCP, обрабатывает запросы и хранит данные в JSON‑файле. +- `memory_client.py` – простая обёртка над MCP‑протоколом для удобного взаимодействия с сервером. + +## Тестирование + +Для запуска тестов (если добавлены): + +```bash +pytest tests/ ``` --- -## License - -MIT © 2026 Your Name -Feel free to fork, modify, and use this project in your own multi‑agent systems. - ---- \ No newline at end of file +**Автор:** *Ваше имя* +**Дата:** 2026‑05‑28 \ No newline at end of file