Добавлен README.md

This commit is contained in:
2026-05-28 14:27:25 +00:00
parent a4f6d401ea
commit 5a47547fca
+119 -80
View File
@@ -1,120 +1,159 @@
# MCP‑сервер для управления памятью агента
# MCP Memory Server
## Описание
MCP‑сервер (Model Context Protocol) – это самостоятельный сервис, который предоставляет API для работы с памятью агентов через стандартизированный протокол. Сервис поддерживает **namespaces** и хранит данные в JSON‑файле, позволяя агентам сохранять, обновлять и получать информацию независимо от их локального окружения.
A lightweight **Model Context Protocol (MCP)** server that exposes a simple JSONbased memory store over HTTP.
It is built on top of the `fastmcp` framework and uses `pydantic` for data validation and `python-dotenv` to load configuration.
- **FastMCP** быстрый HTTP‑сервер для MCP.
- **Pydantic** – валидатор данных (не используется напрямую в примере, но готов к расширению).
- **python-dotenv** – загрузка переменных окружения из `.env`.
> **Why this project?**
> In multiagent systems agents often need a shared, persistent context. The MCP server provides a single source of truth that can be queried by any agent via the standardized protocol.
## Предварительные требования
| Пакет | Версия |
|-------|--------|
| Python | 3.10+ |
| pip | любой |
---
Установите зависимости через `pip`:
## 📦 Features
| Feature | Description |
|---------|-------------|
| **Namespaces** | Organise data into logical groups (`/namespace/key`). |
| **CRUD** | Create, read, update and delete keys. |
| **Search** | Find keys that match a pattern or contain a substring. |
| **Persistence** | All data is stored in a single JSON file on disk. |
| **Fast & Async** | Built with `fastmcp` fast, typesafe, async HTTP server. |
---
## 📋 Prerequisites
- Python 3.10+
- pip (or any other package manager)
> The project uses only purePython dependencies; no external services are required.
---
## ⚙️ Installation
```bash
# Clone the repository
git clone https://github.com/your-org/mcp-memory-server.git
cd mcp-memory-server
# Create a virtual environment (recommended)
python -m venv .venv
source .venv/bin/activate # On 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
uvicorn>=0.30.0 # optional, for running with ASGI server
```
## Установка
Клонируйте репозиторий и установите зависимости:
---
```bash
git clone https://github.com/your-org/memory-mcp.git
cd memory-mcp
pip install -r requirements.txt
```
## 🚀 Running the Server
Создайте файл `.env` в корне проекта (если понадобится):
The server reads configuration from a `.env` file (or environment variables).
Create a `.env` in the project root:
```dotenv
MEMORY_FILE=memory_data.json
PORT=8000
# .env
SERVER_HOST=127.0.0.1
SERVER_PORT=8000
DATA_FILE=data/memory.json # relative to project root
```
## Запуск
Запустите сервер:
Start the server with:
```bash
python memory_server.py
```
Сервер будет слушать на порту, указанном в переменной `PORT` (по умолчанию 8000).
The server will listen on `http://127.0.0.1:8000` and expose the following endpoints:
### Пример использования клиента
| Method | Path | Action |
|--------|------|--------|
| POST | `/namespace/key` | Create/Update a key |
| GET | `/namespace/key` | Retrieve a key |
| DELETE | `/namespace/key` | Delete a key |
| GET | `/search?query=...` | Search keys |
---
## 📚 Example Usage
Below is a minimal example of how an agent (or any HTTP client) can interact with the server.
```python
# memory_client.py
from fastmcp import FastMCPClient
import json
import httpx
from pathlib import Path
client = FastMCPClient("Memory-Server", host="localhost", port=8000)
BASE_URL = "http://127.0.0.1:8000"
# Сохранить запись
response = client.post("/memory/namespace1/item1", data={"value": 42})
print(response.json())
# 1️⃣ Create a key
payload = {"value": "Hello, MCP!"}
resp = httpx.post(f"{BASE_URL}/memory/greeting", json=payload)
print(resp.status_code) # 201 Created
# Получить запись
response = client.get("/memory/namespace1/item1")
print(response.json())
# 2️⃣ Read the key
resp = httpx.get(f"{BASE_URL}/memory/greeting")
print(resp.json()) # {"value":"Hello, MCP!"}
# 3️⃣ Search for keys containing "greet"
resp = httpx.get(f"{BASE_URL}/search?query=greet")
print(resp.json()) # ["memory/greeting"]
# 4️⃣ Delete the key
resp = httpx.delete(f"{BASE_URL}/memory/greeting")
print(resp.status_code) # 204 No Content
```
Запустите клиент в отдельном терминале:
> **Tip:** The `memory_client.py` module contains a thin wrapper around these HTTP calls, making it easier to integrate into your agents.
```bash
python memory_client.py
```
---
## Пример работы
## 📁 Project Structure
1. **Сохранение данных**
```bash
curl -X POST http://localhost:8000/memory/namespaces/agents/agent_123 \
-H "Content-Type: application/json" \
-d '{"name":"Alice","role":"researcher"}'
```
2. **Получение данных**
```bash
curl http://localhost:8000/memory/namespaces/agents/agent_123
```
3. **Обновление записи**
```bash
curl -X PUT http://localhost:8000/memory/namespaces/agents/agent_123 \
-H "Content-Type: application/json" \
-d '{"name":"Alice","role":"senior researcher"}'
```
4. **Удаление записи**
```bash
curl -X DELETE http://localhost:8000/memory/namespaces/agents/agent_123
```
## Структура проекта
```
memory-mcp/
├── memory_server.py # Сервер MCP
├── memory_client.py # Пример клиента
├── requirements.txt
└── .env (опционально)
```text
mcp-memory-server/
├── memory_server.py # FastMCP server implementation
├── memory_client.py # Helper client for interacting with the server
├── .env # Environment configuration (example)
├── requirements.txt # Dependencies
└── README.md # This file
```
---
**Готово!** Теперь у вас есть работающий MCP‑сервер для управления памятью агентов. 🚀
## 🧪 Testing
```bash
# Run unit tests (if any)
pytest tests/
```
> Currently there are no automated tests, but you can easily add them using `pytest` and `httpx`.
---
## 🤝 Contributing
Feel free to open issues or pull requests.
Please follow the standard GitHub workflow:
1. Fork the repo
2. Create a feature branch (`feature/your-feature`)
3. Commit & push
4. Open a Pull Request
---
## 📜 License
MIT © 2026 Your Name / Organization
---