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

This commit is contained in:
2026-05-27 08:04:20 +00:00
parent 29a7f2c237
commit 8cd5e7ecc8
@@ -1,116 +1,160 @@
# MCPMemory Server
A lightweight **Model Context Protocol (MCP)** server that exposes a simple key/value memory store for agents and other clients.
A lightweight **FastMCP** server that exposes a simple key/value store with optional namespaces.
The project contains two scripts:
| File | Purpose |
|------|---------|
| `memory_server.py` | Runs the MCP server, exposing *set*, *get* and *delete* operations on a JSONbacked storage. |
| `memory_client.py` | Demonstrates how to connect to the server and use its tools from a client script. |
| `memory_server.py` | FastMCP RPC server implementing `save`, `get`, `delete`, `list_keys`, `save_with_namespace`, `get_by_namespace`. |
| `memory_client.py` | Example client that demonstrates how to call the RPC methods. |
> **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 multiagent systems to share state without tight coupling.
> **TL;DR** Run the server, then use the client (or any MCPcompatible tool) to store and retrieve data.
---
## 📦 Installation
## Table of Contents
- [Features](#features)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Running the Server](#running-the-server)
- [Using the Client](#using-the-client)
- [Example Usage](#example-usage)
- [API Reference](#api-reference)
- [License](#license)
---
## Features
| RPC | Description |
|-----|-------------|
| `save` | Store a value under a key. |
| `get` | Retrieve the value for a key. |
| `delete` | Remove a key/value pair. |
| `list_keys` | List all keys in the store. |
| `save_with_namespace` | Store a value inside a namespace. |
| `get_by_namespace` | Retrieve a value from a namespace. |
All data is kept **inmemory** it disappears when the server restarts.
---
## Prerequisites
- Python 3.10+
- `pip` (or any other package manager)
The project uses only two external libraries:
```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
fastmcp==0.1.0 # or the latest release on PyPI
pydantic==2.6.4 # for request/response validation
```
> **Tip:**
> `fastmcp` is a minimal framework for building MCP servers and clients.
> `pydantic` is used internally by `fastmcp` for data validation.
---
## 🚀 Running the Server
## Installation
Clone the repository and install dependencies:
```bash
git clone https://github.com/yourname/mcp-memory-server.git
cd mcp-memory-server
python -m venv .venv # optional but recommended
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt # or pip install fastmcp pydantic
```
> **Tip** If you prefer not to create a virtual environment, just run `pip install fastmcp pydantic`.
---
## 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.
The server listens on the default MCP port (`5000`).
You should see output similar to:
### Available Tools
```
INFO:root:FastMCP server started at 127.0.0.1:5000
```
| 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. |
If you need a different host/port, edit `memory_server.py` or set environment variables before launching.
---
## 🧪 Running the Client
## Using the Client
The client demonstrates how to call each RPC method.
```bash
python memory_client.py
```
The client script demonstrates:
It will:
1. Setting a value (`foo = "bar"`).
2. Getting that value back.
3. Deleting the key and verifying its gone.
1. Save two keys (`foo`, `bar`).
2. Retrieve them.
3. Delete one key.
4. List remaining keys.
5. Work with a namespace called `"demo"`.
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).
All interactions are printed to the console.
---
## 📄 Example Usage
## Example Usage
Below is a quick manual example using the client as a reference:
```python
# memory_client.py snippet
from fastmcp import FastMCPClient
import asyncio
client = FastMCPClient("Memory-Server", host="localhost", port=8000)
async def main():
async with FastMCPClient("127.0.0.1", 5000) as client:
# Save a key/value pair
await client.rpc("save", {"key": "greeting", "value": "Hello, world!"})
# Set a key/value pair
client.call_tool("set", {"key": "greeting", "value": "Hello, world!"})
# Retrieve it
result = await client.rpc("get", {"key": "greeting"})
print(result) # {'value': 'Hello, world!'}
# Retrieve the value
response = client.call_tool("get", {"key": "greeting"})
print(response) # Output: Hello, world!
# List all keys
keys = await client.rpc("list_keys")
print(keys) # {'keys': ['greeting']}
# Delete the key
client.call_tool("delete", {"key": "greeting"})
# Work with namespace
await client.rpc("save_with_namespace", {"namespace": "ns1", "key": "x", "value": 42})
ns_val = await client.rpc("get_by_namespace", {"namespace": "ns1", "key": "x"})
print(ns_val) # {'value': 42}
# 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
asyncio.run(main())
```
---
## 🔧 Customization
## API Reference
- **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.
| Method | Request Schema | Response |
|--------|----------------|----------|
| `save` | `{ key: str, value: str }` | `None` |
| `get` | `{ key: str }` | `{ value: any }` |
| `delete` | `{ key: str }` | `None` |
| `list_keys` | `None` | `{ keys: List[str] }` |
| `save_with_namespace` | `{ namespace: str, key: str, value: str }` | `None` |
| `get_by_namespace` | `{ namespace: str, key: str }` | `{ value: any }` |
All RPC calls are asynchronous and return a JSONserialisable dictionary.
---
## 📜 License
## License
This project is released under the MIT license. Feel free to fork, extend or use it in your own projects.
MIT © 2026 Your Name
---