Delete directory 'solutions/69f8e929da860fb4533faa2a_MCP_сервер_для_управления_памятью_агента'

This commit is contained in:
2026-05-27 15:39:09 +00:00
parent 39134c9f91
commit 1cddfbc671
4 changed files with 0 additions and 367 deletions
@@ -1,138 +0,0 @@
# MCP Memory Server
A lightweight **Model Context Protocol (MCP)** server that exposes a simple keyvalue store to other agents or CLI tools.
The server is built with `fastmcp` and uses a JSON file as persistent storage.
---
## Table of Contents
- [Features](#features)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Running the Server](#running-the-server)
- [Running the Client](#running-the-client)
- [Example Usage](#example-usage)
- [Project Structure](#project-structure)
---
## Features
| Operation | Description |
|-----------|-------------|
| `set` | Store a value under a key (optionally in a namespace). |
| `get` | Retrieve a stored value. |
| `delete` | Remove a key from storage. |
| `keys` | List all keys, optionally filtered by pattern or namespace. |
All operations are performed through the MCP protocol over **STDIO**.
---
## Prerequisites
- Python 3.10+
- pip
---
## Installation
```bash
# Clone the repository (or copy the files)
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 fastmcp pydantic python-dotenv
```
> **Tip:** The `memory_server.py` and `memory_client.py` files are selfcontained; no additional packages are required beyond those listed.
---
## Running the Server
```bash
python memory_server.py
```
The server starts listening on STDIO.
It will create (or load) a file named `memory_data.json` in the current directory to persist data.
**Server output example**
```
[Memory-Server] Listening on stdin/stdout...
```
---
## Running the Client
```bash
python memory_client.py
```
The client demonstrates basic usage: setting, getting, listing keys, and deleting a key.
It communicates with the server over STDIO using `fastmcp`.
**Client output example**
```
Set key 'foo' to value 'bar'
Get key 'foo': bar
All keys: ['foo']
Deleted key 'foo'
All keys after deletion: []
```
---
## Example Usage
Below is a quick script that shows how you can interact with the server programmatically.
```python
from fastmcp import FastMCPClient
import json
# Connect to the running MCP server (STDIO)
client = FastMCPClient("Memory-Server")
# Set a key
client.send({"action": "set", "key": "greeting", "value": "Hello, world!"})
# Get the key
response = client.receive()
print(response) # {'status': 'ok', 'value': 'Hello, world!'}
# List all keys
client.send({"action": "keys"})
print(client.receive()) # {'status': 'ok', 'keys': ['greeting']}
# Delete the key
client.send({"action": "delete", "key": "greeting"})
print(client.receive()) # {'status': 'ok'}
```
> **Note:** The client and server communicate via JSON messages.
> Each message must contain an `"action"` field that matches one of the supported operations.
---
## Project Structure
```
mcp-memory-server/
├── memory_server.py # MCP server implementation
├── memory_client.py # Demo client script
└── README.md # This file
```
- `memory_server.py` defines the `MemoryServer` class and starts the MCP service.
- `memory_client.py` simple CLI client that exercises all operations.
Feel free to extend the server with authentication, more sophisticated storage backends, or additional MCP actions. Happy hacking!
@@ -1,39 +0,0 @@
# memory_client.py
from fastmcp import Client
import asyncio
async def main():
# Подключаемся к серверу через stdio (запускаем скрипт сервера как subprocess)
client = Client("python memory_server.py")
await client.connect()
try:
# Сохраняем данные в namespace "default"
result = await client.call_tool(
"save_with_namespace",
{"key": "username", "value": "Алексей", "namespace": "default"}
)
print(f"Сохранено: {result}")
# Читаем все ключи из namespace "default"
result = await client.call_tool(
"get_by_namespace",
{"namespace": "default"}
)
print("Данные namespace 'default':")
for item in result:
print(f" {item['key']}: {item['value']}")
# Получаем ключи, удовлетворяющие паттерну
keys = await client.call_tool(
"list_keys",
{"pattern": "*name"}
)
print("Ключи с 'name':", keys)
finally:
await client.close()
if __name__ == "__main__":
asyncio.run(main())
@@ -1,189 +0,0 @@
# memory_server.py
"""
FastMCP сервер для управления памятью агента.
Поддерживает операции сохранения, чтения, удаления и списка ключей,
а также работу с пространствами имён (namespaces).
"""
from fastmcp import FastMCP
import json
from datetime import datetime
from pathlib import Path
from typing import Any, Optional, Dict, List
import fnmatch
class MemoryServer:
"""
Сервер памяти. Хранит данные в JSON‑файле с метаданными.
"""
def __init__(self) -> None:
self.mcp = FastMCP("Memory-Server")
self.storage_path = Path("./memory_data.json")
# ------------------------------------------------------------------
# Внутренние методы работы с файлом
# ------------------------------------------------------------------
def _load_memory(self) -> Dict[str, Any]:
"""Загружает память из JSON‑файла."""
if not self.storage_path.exists():
return {}
with open(self.storage_path, "r", encoding="utf-8") as f:
try:
data = json.load(f)
except json.JSONDecodeError:
# Если файл повреждён – начинаем с пустого словаря
data = {}
return data
def _save_memory(self, data: Dict[str, Any]) -> None:
"""Сохраняет память в JSON‑файл."""
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.storage_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# ------------------------------------------------------------------
# Инструменты без namespace
# ------------------------------------------------------------------
@self.mcp.tool()
def save(key: str, value: Any) -> bool:
"""
Сохраняет значение по ключу в память сервера.
Args:
key: Идентификатор для сохранения (уникальный ключ).
value: Любое сериализуемое значение.
Returns:
True при успешном сохранении, False иначе.
"""
if not isinstance(key, str) or "/" in key:
return False
data = self._load_memory()
data[key] = {
"value": value,
"timestamp": datetime.utcnow().isoformat(),
}
self._save_memory(data)
return True
@self.mcp.tool()
def get(key: str) -> Optional[Dict[str, Any]]:
"""
Возвращает значение по ключу с метаданными.
Args:
key: Идентификатор для поиска.
Returns:
Словарь с полями {"key": ..., "value": ..., "timestamp": ...}
или None если ключ не найден.
"""
data = self._load_memory()
entry = data.get(key)
if entry is None:
return None
return {
"key": key,
"value": entry["value"],
"timestamp": entry["timestamp"],
}
@self.mcp.tool()
def delete(key: str) -> bool:
"""
Удаляет ключ из памяти сервера.
Args:
key: Идентификатор для удаления.
Returns:
True при успешном удалении, False если ключ не найден.
"""
data = self._load_memory()
if key in data:
del data[key]
self._save_memory(data)
return True
return False
@self.mcp.tool()
def list_keys(pattern: str = "*") -> List[str]:
"""
Возвращает список всех ключей с поддержкой wildcard‑паттерна.
Args:
pattern: Паттерн для фильтрации (поддерживает * и ?).
Returns:
Список совпадающих ключей.
"""
data = self._load_memory()
return [k for k in data.keys() if fnmatch.fnmatch(k, pattern)]
# ------------------------------------------------------------------
# Инструменты с namespace
# ------------------------------------------------------------------
@self.mcp.tool()
def save_with_namespace(key: str, value: Any, namespace: str = "default") -> bool:
"""
Сохраняет значение с указанием пространства имён.
Args:
key: Идентификатор.
value: Значение для сохранения.
namespace: Пространство имён (по умолчанию 'default').
Returns:
True при успехе, False иначе.
"""
if not isinstance(key, str) or "/" in key:
return False
full_key = f"{namespace}:{key}"
data = self._load_memory()
data[full_key] = {
"value": value,
"timestamp": datetime.utcnow().isoformat(),
}
self._save_memory(data)
return True
@self.mcp.tool()
def get_by_namespace(namespace: str = "default") -> List[Dict[str, Any]]:
"""
Возвращает все ключи из указанного namespace.
Args:
namespace: Пространство имён для чтения.
Returns:
Список словарей с метаданными всех ключей namespace.
"""
prefix = f"{namespace}:"
data = self._load_memory()
result = []
for full_key, entry in data.items():
if full_key.startswith(prefix):
key_part = full_key[len(prefix) :]
result.append(
{
"key": key_part,
"value": entry["value"],
"timestamp": entry["timestamp"],
}
)
return result
# ----------------------------------------------------------------------
# Запуск сервера
# ----------------------------------------------------------------------
if __name__ == "__main__":
server = MemoryServer()
server.mcp.run(
transport="stdio",
show_banner=False,
log_level="ERROR",
)