MCP-сервер для управления памятью агента: memory_server.py
This commit is contained in:
+115
@@ -0,0 +1,115 @@
|
||||
<|channel|>final code<|message|>import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastmcp import FastMCP
|
||||
|
||||
|
||||
class MemoryServer:
|
||||
def __init__(self):
|
||||
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)
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
return {}
|
||||
|
||||
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:
|
||||
"""Сохраняет значение по ключу в память сервера."""
|
||||
if not isinstance(key, str) or not key.strip():
|
||||
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]:
|
||||
"""Возвращает значение по ключу с метаданными."""
|
||||
if not isinstance(key, str):
|
||||
return 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:
|
||||
"""Удаляет ключ из памяти сервера."""
|
||||
if not isinstance(key, str):
|
||||
return 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-паттерна."""
|
||||
if not isinstance(pattern, str):
|
||||
pattern = "*"
|
||||
data = self._load_memory()
|
||||
import fnmatch
|
||||
|
||||
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:
|
||||
"""Сохраняет значение с указанием пространства имён."""
|
||||
if not isinstance(namespace, str) or not namespace.strip():
|
||||
return False
|
||||
full_key = f"{namespace}:{key}"
|
||||
return self.save(full_key, value)
|
||||
|
||||
@self.mcp.tool()
|
||||
def get_by_namespace(namespace: str = "default") -> list[dict]:
|
||||
"""Возвращает все ключи из указанного namespace."""
|
||||
if not isinstance(namespace, str) or not namespace.strip():
|
||||
return []
|
||||
data = self._load_memory()
|
||||
prefix = f"{namespace}:"
|
||||
result = []
|
||||
for k, v in data.items():
|
||||
if k.startswith(prefix):
|
||||
key_part = k[len(prefix) :]
|
||||
result.append(
|
||||
{"key": key_part, "value": v["value"], "timestamp": v["timestamp"]}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Запуск сервера
|
||||
# ----------------------------------------------------------------------
|
||||
if __name__ == "__main__":
|
||||
server = MemoryServer()
|
||||
server.mcp.run(transport="stdio", show_banner=False, log_level="ERROR")
|
||||
Reference in New Issue
Block a user