Добавлен README.md

This commit is contained in:
2026-05-28 13:43:33 +00:00
parent fd0a59ae5f
commit b124a12601
+92 -131
View File
@@ -1,167 +1,128 @@
# MCPMemory 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 MCPcompatible 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 **MCPMemory Server** is a minimal, selfcontained 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.
Its ideal for prototyping multiagent 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 lowlatency 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 dont 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 doesnt 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 multiagent systems.
---
**Автор:** *Ваше имя*
**Дата:** 20260528