+116
@@ -0,0 +1,116 @@
|
||||
# MCP‑Memory Server
|
||||
|
||||
A lightweight **Model Context Protocol (MCP)** server that exposes a simple key/value memory store for agents and other clients.
|
||||
The project contains two scripts:
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `memory_server.py` | Runs the MCP server, exposing *set*, *get* and *delete* operations on a JSON‑backed storage. |
|
||||
| `memory_client.py` | Demonstrates how to connect to the server and use its tools from a client script. |
|
||||
|
||||
> **Why MCP?**
|
||||
> MCP is a lightweight protocol for exchanging structured data between agents, services or CLI utilities. By running this server as a separate process we enable distributed multi‑agent systems to share state without tight coupling.
|
||||
|
||||
---
|
||||
|
||||
## 📦 Installation
|
||||
|
||||
```bash
|
||||
# Create and activate a virtual environment (optional but recommended)
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate # Windows: .\.venv\Scripts\activate
|
||||
|
||||
# Install the required packages
|
||||
pip install fastmcp pydantic python-dotenv
|
||||
```
|
||||
|
||||
> **Tip:**
|
||||
> `fastmcp` is a minimal framework for building MCP servers and clients.
|
||||
> `pydantic` is used internally by `fastmcp` for data validation.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Running the Server
|
||||
|
||||
```bash
|
||||
python memory_server.py
|
||||
```
|
||||
|
||||
The server starts on the default port **8000** (you can change it in the script).
|
||||
It will create a file called `memory_data.json` in the current directory to persist data between restarts.
|
||||
|
||||
### Available Tools
|
||||
|
||||
| Tool | Parameters | Description |
|
||||
|------|------------|-------------|
|
||||
| `set` | `key: str`, `value: Any` | Stores a value under the given key. |
|
||||
| `get` | `key: str` | Retrieves the value for the key (or `null`). |
|
||||
| `delete` | `key: str` | Removes the key from storage. |
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Running the Client
|
||||
|
||||
```bash
|
||||
python memory_client.py
|
||||
```
|
||||
|
||||
The client script demonstrates:
|
||||
|
||||
1. Setting a value (`foo = "bar"`).
|
||||
2. Getting that value back.
|
||||
3. Deleting the key and verifying it’s gone.
|
||||
|
||||
You can also use the client interactively by editing `memory_client.py` or by sending raw MCP messages via another tool (e.g., `curl`, Postman, or a custom agent).
|
||||
|
||||
---
|
||||
|
||||
## 📄 Example Usage
|
||||
|
||||
```python
|
||||
# memory_client.py snippet
|
||||
|
||||
from fastmcp import FastMCPClient
|
||||
|
||||
client = FastMCPClient("Memory-Server", host="localhost", port=8000)
|
||||
|
||||
# Set a key/value pair
|
||||
client.call_tool("set", {"key": "greeting", "value": "Hello, world!"})
|
||||
|
||||
# Retrieve the value
|
||||
response = client.call_tool("get", {"key": "greeting"})
|
||||
print(response) # Output: Hello, world!
|
||||
|
||||
# Delete the key
|
||||
client.call_tool("delete", {"key": "greeting"})
|
||||
|
||||
# Verify deletion
|
||||
assert client.call_tool("get", {"key": "greeting"}) is None
|
||||
```
|
||||
|
||||
Feel free to integrate this server into your own agent framework or use it as a standalone memory service.
|
||||
|
||||
---
|
||||
|
||||
## 📁 Project Structure
|
||||
|
||||
```
|
||||
.
|
||||
├── memory_server.py # MCP server implementation
|
||||
├── memory_client.py # Example client script
|
||||
└── memory_data.json # (generated) persistent storage
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Customization
|
||||
|
||||
- **Port** – change the `port` argument in `FastMCP("Memory-Server", port=8000)` inside `memory_server.py`.
|
||||
- **Storage Path** – modify `self.storage_path = Path("./memory_data.json")` to point elsewhere.
|
||||
- **Additional Tools** – add new methods decorated with `@self.mcp.tool(...)` following the pattern in the script.
|
||||
|
||||
---
|
||||
|
||||
## 📜 License
|
||||
|
||||
This project is released under the MIT license. Feel free to fork, extend or use it in your own projects.
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
# memory_client.py
|
||||
"""
|
||||
Клиент для тестирования MCP‑сервера памяти.
|
||||
Подключается к серверу через stdio и демонстрирует работу инструментов:
|
||||
- save_with_namespace
|
||||
- get_by_namespace
|
||||
- list_keys
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from fastmcp import Client
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""
|
||||
Основная асинхронная функция, которая:
|
||||
1. Создаёт клиент для сервера memory_server.py.
|
||||
2. Подключается к серверу.
|
||||
3. Выполняет серию вызовов инструментов и выводит результаты.
|
||||
4. Закрывает соединение.
|
||||
"""
|
||||
# Инициализируем клиента, указывая путь к исполняемому скрипту сервера
|
||||
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']}")
|
||||
|
||||
# Ищем ключи, содержащие подстроку 'name'
|
||||
keys = await client.call_tool(
|
||||
"list_keys",
|
||||
{"pattern": "*name"},
|
||||
)
|
||||
print("Ключи с 'name':", keys)
|
||||
|
||||
finally:
|
||||
# Завершаем соединение
|
||||
await client.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
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")
|
||||
+1
@@ -0,0 +1 @@
|
||||
fastmcp
|
||||
Reference in New Issue
Block a user