MCP-сервер для управления памятью агента: README.md

This commit is contained in:
2026-05-27 11:31:30 +00:00
parent b67cd41af5
commit be2665f8c9
@@ -1,119 +1,145 @@
# MCP Memory Server # MCPMemory Server
## 📌 Описание проекта A lightweight **Model Context Protocol (MCP)** server that exposes a simple key/value memory store to any agent or client via the `fastmcp` protocol.
Этот проект реализует **MCP‑сервер (Model Context Protocol)**, который предоставляет API для управления памятью агента в распределённой системе.
Сервер хранит данные в JSON‑файле и поддерживает:
- *namespaces* – логическое разделение данных;
- *wildcard‑поиск* ключей (`fnmatch`);
- простую модель CRUD через протокол MCP.
Клиентский скрипт `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 multiagent 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 crossagent coordination.
--- ---
## ⚙️ Предварительные требования ## Features
| Компонент | Версия | Как установить |
|-----------|--------|----------------|
| Python | 3.10+ | `python -m venv .venv && source .venv/bin/activate` (Linux/macOS) / `.venv\Scripts\activate` (Windows) |
| pip | — | Встроен в Python |
| **Библиотеки** | — | Установить из `requirements.txt` |
> **Важно:** Сервер не требует внешних сервисов, но при желании можно подключить к базе данных или использовать 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.
- **Zeroconfiguration** 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 ```bash
# Клонируйте репозиторий (или скачайте архив) # Clone the repo
git clone https://github.com/your-org/mcp-memory-server.git git clone https://github.com/your-org/mcp-memory-server.git
cd mcp-memory-server cd mcp-memory-server
# Создайте виртуальное окружение и активируйте его # Create a virtual environment (optional but recommended)
python -m venv .venv python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate source .venv/bin/activate # Windows: .venv\Scripts\activate
# Установите зависимости # Install dependencies
pip install -r requirements.txt pip install -r requirements.txt
``` ```
`requirements.txt` `requirements.txt` contains:
```text ```text
fastmcp>=0.1.0 fastmcp>=0.2.0
pydantic>=2.0 pydantic>=1.10.0
python-dotenv>=1.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 ```bash
# В корне проекта # Direct execution
python memory_server.py python memory_server.py
``` ```
Сервер будет слушать по адресу `http://127.0.0.1:8000` (по умолчанию).
При первом запуске создастся файл `memory_data.json`.
### 2️⃣ Запустить клиент You should see:
```bash
# В другом терминале, в той же виртуальной среде ```
python memory_client.py [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 ```bash
# 1. Запускаем сервер
python memory_server.py
# 2. В другом терминале запускаем клиент (или пишем свой скрипт)
python memory_client.py python memory_client.py
``` ```
### Вывод клиента Output example:
``` ```
Added record: {'namespace': 'chat', 'key': 'msg_001', 'value': 'Hello, world!'} Сохранено: {'status': 'ok'}
All records: Загружено: {'value': 'Алексей', 'namespace': 'default'}
[{'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'}
``` ```
--- ---
## 📁 Структура проекта ## API Reference
```text
mcp-memory-server/ The server exposes three tools via MCP:
├── memory_server.py # Сервер MCP
├── memory_client.py # Демонстрационный клиент | Tool | Parameters | Returns |
├── requirements.txt # Зависимости |------|------------|---------|
└── README.md # Это файл | `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 JSONserializable dictionaries.
--- ---
## 🔧 Настройка ## Example Usage in an Agent
Если нужно изменить порт или путь к файлу хранения, отредактируйте конструктор `MemoryServer` в `memory_server.py`:
```python ```python
self.mcp = FastMCP("Memory-Server", host="0.0.0.0", port=8080) from fastmcp import Client
self.storage_path = Path("./data/memory.json") 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 inmemory 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!