MCP-сервер для управления памятью агента: README.md
This commit is contained in:
+91
-65
@@ -1,119 +1,145 @@
|
||||
# MCP Memory Server
|
||||
# MCP‑Memory Server
|
||||
|
||||
## 📌 Описание проекта
|
||||
Этот проект реализует **MCP‑сервер (Model Context Protocol)**, который предоставляет API для управления памятью агента в распределённой системе.
|
||||
Сервер хранит данные в JSON‑файле и поддерживает:
|
||||
- *namespaces* – логическое разделение данных;
|
||||
- *wildcard‑поиск* ключей (`fnmatch`);
|
||||
- простую модель CRUD через протокол MCP.
|
||||
A lightweight **Model Context Protocol (MCP)** server that exposes a simple key/value memory store to any agent or client via the `fastmcp` protocol.
|
||||
|
||||
Клиентский скрипт `memory_client.py` демонстрирует, как обращаться к серверу из другого агента или CLI‑утилиты.
|
||||
The project contains two scripts:
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `memory_server.py` | The MCP server – runs as an independent process and listens for requests. |
|
||||
| `memory_client.py` | A demo client that connects to the server, stores data and retrieves it. |
|
||||
|
||||
> **Why MCP?**
|
||||
> In a multi‑agent system agents often need to share state (e.g., user profiles, conversation history). Running a dedicated memory service decouples this shared state from individual agent processes, enabling easier scaling, persistence, and cross‑agent coordination.
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Предварительные требования
|
||||
| Компонент | Версия | Как установить |
|
||||
|-----------|--------|----------------|
|
||||
| Python | 3.10+ | `python -m venv .venv && source .venv/bin/activate` (Linux/macOS) / `.venv\Scripts\activate` (Windows) |
|
||||
| pip | — | Встроен в Python |
|
||||
| **Библиотеки** | — | Установить из `requirements.txt` |
|
||||
## Features
|
||||
|
||||
> **Важно:** Сервер не требует внешних сервисов, но при желании можно подключить к базе данных или использовать Docker‑контейнеры.
|
||||
- **Namespace support** – store data under arbitrary namespaces (`default`, `session_1234`, …).
|
||||
- **Simple CRUD API** – `save_with_namespace`, `load_from_namespace`, `delete_from_namespace`.
|
||||
- **FastMCP integration** – uses the `fastmcp` library for lightweight, async communication.
|
||||
- **Zero‑configuration** – no external database required; data is kept in memory (restart loses state).
|
||||
|
||||
---
|
||||
|
||||
## 📦 Установка
|
||||
## Prerequisites
|
||||
|
||||
| Component | Minimum version |
|
||||
|-----------|-----------------|
|
||||
| Python | 3.10+ |
|
||||
| pip | latest |
|
||||
|
||||
> No external services are needed – the server keeps all data in RAM.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Клонируйте репозиторий (или скачайте архив)
|
||||
# Clone the repo
|
||||
git clone https://github.com/your-org/mcp-memory-server.git
|
||||
cd mcp-memory-server
|
||||
|
||||
# Создайте виртуальное окружение и активируйте его
|
||||
# Create a virtual environment (optional but recommended)
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||
|
||||
# Установите зависимости
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
`requirements.txt`
|
||||
`requirements.txt` contains:
|
||||
|
||||
```text
|
||||
fastmcp>=0.1.0
|
||||
pydantic>=2.0
|
||||
python-dotenv>=1.0
|
||||
fastmcp>=0.2.0
|
||||
pydantic>=1.10.0
|
||||
python-dotenv>=1.0.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Запуск сервера и клиента
|
||||
## Running the Server
|
||||
|
||||
The server is a simple Python script that can be started directly or via `subprocess`.
|
||||
It listens on an internal IPC channel (via `fastmcp`), so no network port is exposed.
|
||||
|
||||
### 1️⃣ Запустить сервер
|
||||
```bash
|
||||
# В корне проекта
|
||||
# Direct execution
|
||||
python memory_server.py
|
||||
```
|
||||
Сервер будет слушать по адресу `http://127.0.0.1:8000` (по умолчанию).
|
||||
При первом запуске создастся файл `memory_data.json`.
|
||||
|
||||
### 2️⃣ Запустить клиент
|
||||
```bash
|
||||
# В другом терминале, в той же виртуальной среде
|
||||
python memory_client.py
|
||||
You should see:
|
||||
|
||||
```
|
||||
[INFO] MCP Server listening...
|
||||
```
|
||||
Клиент демонстрирует пример CRUD‑операций:
|
||||
- Добавление записи;
|
||||
- Чтение всех записей;
|
||||
- Поиск по шаблону;
|
||||
- Удаление.
|
||||
|
||||
---
|
||||
|
||||
## 📚 Пример использования
|
||||
## Running the Demo Client
|
||||
|
||||
The client demonstrates how to connect to the server, store a value, and retrieve it.
|
||||
|
||||
```bash
|
||||
# 1. Запускаем сервер
|
||||
python memory_server.py
|
||||
|
||||
# 2. В другом терминале запускаем клиент (или пишем свой скрипт)
|
||||
python memory_client.py
|
||||
```
|
||||
|
||||
### Вывод клиента
|
||||
Output example:
|
||||
|
||||
```
|
||||
Added record: {'namespace': 'chat', 'key': 'msg_001', 'value': 'Hello, world!'}
|
||||
All records:
|
||||
[{'namespace': 'chat', 'key': 'msg_001', 'value': 'Hello, world!'}]
|
||||
Search results for pattern '*msg*':
|
||||
[{'namespace': 'chat', 'key': 'msg_001', 'value': 'Hello, world!'}]
|
||||
Deleted record: {'namespace': 'chat', 'key': 'msg_001'}
|
||||
Сохранено: {'status': 'ok'}
|
||||
Загружено: {'value': 'Алексей', 'namespace': 'default'}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📁 Структура проекта
|
||||
```text
|
||||
mcp-memory-server/
|
||||
├── memory_server.py # Сервер MCP
|
||||
├── memory_client.py # Демонстрационный клиент
|
||||
├── requirements.txt # Зависимости
|
||||
└── README.md # Это файл
|
||||
```
|
||||
## API Reference
|
||||
|
||||
The server exposes three tools via MCP:
|
||||
|
||||
| Tool | Parameters | Returns |
|
||||
|------|------------|---------|
|
||||
| `save_with_namespace` | `{key, value, namespace}` | `{'status': 'ok'}` |
|
||||
| `load_from_namespace` | `{key, namespace}` | `{'value': <value>, 'namespace': <ns>}` |
|
||||
| `delete_from_namespace` | `{key, namespace}` | `{'status': 'deleted'}` |
|
||||
|
||||
All calls are asynchronous and return JSON‑serializable dictionaries.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Настройка
|
||||
|
||||
Если нужно изменить порт или путь к файлу хранения, отредактируйте конструктор `MemoryServer` в `memory_server.py`:
|
||||
## Example Usage in an Agent
|
||||
|
||||
```python
|
||||
self.mcp = FastMCP("Memory-Server", host="0.0.0.0", port=8080)
|
||||
self.storage_path = Path("./data/memory.json")
|
||||
from fastmcp import Client
|
||||
import asyncio
|
||||
|
||||
async def agent_logic():
|
||||
client = Client("python memory_server.py")
|
||||
await client.connect()
|
||||
|
||||
# Store a user ID
|
||||
await client.call_tool(
|
||||
"save_with_namespace",
|
||||
{"key": "user_id", "value": 42, "namespace": "session_123"}
|
||||
)
|
||||
|
||||
# Later retrieve it
|
||||
res = await client.call_tool(
|
||||
"load_from_namespace",
|
||||
{"key": "user_id", "namespace": "session_123"}
|
||||
)
|
||||
print(res["value"]) # -> 42
|
||||
|
||||
asyncio.run(agent_logic())
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📜 Лицензия
|
||||
## Extending the Server
|
||||
|
||||
MIT License – см. файл `LICENSE`.
|
||||
- **Persistence** – wrap the in‑memory store with a simple file or Redis backend.
|
||||
- **Authentication** – add token checks to `Client` before processing requests.
|
||||
- **Metrics** – expose Prometheus metrics for request counts and latency.
|
||||
|
||||
---
|
||||
Feel free to fork, improve, and contribute!
|
||||
Reference in New Issue
Block a user