feat: add Moss-backed archival memory package for Letta - #406
feat: add Moss-backed archival memory package for Letta#406rohanshrma222 wants to merge 6 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
Adds a new Python integration package packages/letta-moss/ that exposes Moss as a Letta (MemGPT) archival-memory provider via (1) in-sandbox custom tools and (2) an out-of-process FastMCP server, without modifying Letta itself.
Changes:
- Introduces
MossLettaMemoryadapter with insert/search/delete/get/list operations backed by a Moss index, including metadata (typed) round-tripping and tag post-filtering. - Adds two integration surfaces: plain async
moss_memory_*functions (forupsert_from_function) and a FastMCP app factory (create_mcp_app). - Adds a full unit test suite (mocked client) plus a credential-gated MCP roundtrip test, and documents usage in
README.md+AGENTS.md.
Reviewed changes
Copilot reviewed 11 out of 12 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/letta-moss/src/letta_moss/memory.py | Implements the Moss-backed archival memory adapter and metadata/tag handling logic. |
| packages/letta-moss/src/letta_moss/tools.py | Adds plain async tool functions with a lazy singleton memory instance for Letta tool execution. |
| packages/letta-moss/src/letta_moss/mcp_app.py | Exposes the memory adapter via a FastMCP server with tool wrappers. |
| packages/letta-moss/src/letta_moss/init.py | Defines the package’s public API surface. |
| packages/letta-moss/tests/test_memory.py | Unit-tests the adapter behaviors (create/load/query/get/list + metadata roundtrip). |
| packages/letta-moss/tests/test_tools.py | Unit-tests lazy singleton construction and tool function delegation/shape. |
| packages/letta-moss/tests/test_mcp_app.py | Unit-tests MCP tool registration, error mapping, and a credential-gated roundtrip. |
| packages/letta-moss/tests/init.py | Marks the tests package. |
| packages/letta-moss/README.md | Documents install, both integration options, and API/behavior notes. |
| packages/letta-moss/pyproject.toml | Declares the new package metadata, dependencies, and test/lint config. |
| packages/letta-moss/LICENSE | Adds package-level BSD-2-Clause license file. |
| AGENTS.md | Registers the new package in the repository’s agent guidance index. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| """Delete a memory from Moss-backed archival storage by id.""" | ||
| try: | ||
| await memory.delete_memory(memory_id) | ||
| except Exception as e: | ||
| raise RuntimeError(f"Moss memory delete failed: {e}") from e |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 11 out of 12 changed files in this pull request and generated 4 comments.
Comments suppressed due to low confidence (1)
packages/letta-moss/src/letta_moss/tools.py:43
- _get_memory() reads MOSS_INDEX_NAME via os.environ["MOSS_INDEX_NAME"], which raises a KeyError with a poor message if the env var is missing. Since this is user configuration, fail with a clear ValueError explaining how to configure it.
async with _memory_lock:
if _memory is None:
memory = MossLettaMemory(index_name=os.environ["MOSS_INDEX_NAME"])
await memory.load_index()
_memory = memory
| @app.tool(name=tools.moss_memory_search.__name__) | ||
| async def _search(query: str, top_k: int = 5) -> list[dict]: | ||
| """Search Moss-backed archival storage for memories relevant to a query.""" | ||
| try: | ||
| items = await memory.search_memory(query, top_k=top_k) | ||
| except Exception as e: | ||
| raise RuntimeError(f"Moss memory search failed: {e}") from e | ||
| return [dataclasses.asdict(item) for item in items] |
| async def moss_memory_search(query: str, top_k: int = 5) -> list[dict]: | ||
| """Search Moss-backed archival storage for memories relevant to a query. | ||
|
|
||
| Args: | ||
| query: Natural-language query to search for. | ||
| top_k: Maximum number of results to return. | ||
|
|
||
| Returns: | ||
| A list of matching memories, each with ``id``, ``content``, ``tags``, | ||
| ``metadata``, and ``score`` fields. | ||
| """ | ||
| memory = await _get_memory() | ||
| items = await memory.search_memory(query, top_k=top_k) | ||
| return [dataclasses.asdict(item) for item in items] |
| | `MossLettaMemory(*, project_id=None, project_key=None, index_name, top_k=5, alpha=0.8)` | class | Core adapter; `async load_index()`, `async insert_memory(content, tags=, metadata=) -> str`, `async search_memory(query, top_k=, tags=) -> list[ArchivalMemoryItem]`, `async delete_memory(memory_id)`, `async get_memory(memory_id) -> ArchivalMemoryItem \| None`, `async list_memories(limit=) -> list[ArchivalMemoryItem]`. Falls back to `MOSS_PROJECT_ID`/`MOSS_PROJECT_KEY` env vars when credentials are omitted. | | ||
| | `moss_memory_insert(content, tags=None) -> str` | async function | Custom-tool wrapper; insert a memory, return its id. | | ||
| | `moss_memory_search(query, top_k=5) -> list[dict]` | async function | Custom-tool wrapper; search memories, return dicts. | | ||
| | `moss_memory_delete(memory_id) -> None` | async function | Custom-tool wrapper; delete a memory by id. | | ||
| | `create_mcp_app(memory) -> FastMCP` | function | Returns a FastMCP server exposing `moss_memory_insert`/`moss_memory_search`/`moss_memory_delete`; runs `memory.load_index()` in its lifespan. | |
Codex reviewThe PR adds a coherent Letta memory adapter, but a few safety and edge-case paths need tightening before this is safe to expose as a reusable integration. |
| raise RuntimeError("Moss memory search failed") from e | ||
| return [dataclasses.asdict(item) for item in items] | ||
|
|
||
| @app.tool(name=tools.moss_memory_delete.__name__) |
There was a problem hiding this comment.
BLOCKING @app.tool(name=tools.moss_memory_delete.__name__) registers the destructive delete tool for every MCP app by default, even though the README correctly treats deletion as opt-in for prompt-injection/data-loss reasons. Make MCP deletion opt-in too, e.g. create_mcp_app(memory, include_delete=False) and only register this block when explicitly enabled.
| polling_interval_in_seconds=self._refresh_interval_seconds, | ||
| ) | ||
| except RuntimeError as e: | ||
| if "not found" not in str(e).lower(): |
There was a problem hiding this comment.
CONSIDER if "not found" not in str(e).lower(): uses substring matching to decide that a missing index should be treated as empty memory. This can also swallow unrelated 404-style failures such as a missing project/model and make searches return [] instead of surfacing misconfiguration. Catch the SDK's structured not-found/index-not-found exception or centralize a helper that verifies the failed resource is exactly self._index_name.
| # than failing an insert_memory() call that promises to create a | ||
| # missing index. | ||
| self._index_created = False | ||
| await self._client.create_index(self._index_name, [doc]) |
There was a problem hiding this comment.
CONSIDER await self._client.create_index(self._index_name, [doc]) retries after add_docs reports a missing index, but it does not handle the race where another worker recreates the index between those two calls. In that case this insert fails with "already exists" instead of adding the doc. Mirror the first-insert path here: catch already exists from create_index and retry add_docs(..., upsert=True) once.
|
|
||
| async def list_memories(self, limit: int | None = None) -> list[ArchivalMemoryItem]: | ||
| """List all archival memories in the index, optionally capped at ``limit``.""" | ||
| docs = await self._client.get_docs(self._index_name) |
There was a problem hiding this comment.
CONSIDER docs = await self._client.get_docs(self._index_name) fetches the whole index before applying return items[:limit], so list_memories(limit=10) can still download and deserialize every memory in a large index. Push the limit into GetDocumentsOptions or page through get_docs until the requested limit is reached.
Pull Request Checklist
Description
Adds
packages/letta-moss/, a Python package that backs Letta (MemGPT) archival memory with a Moss index.Letta removed its old pluggable storage-backend abstraction for archival memory today it's hardcoded to Postgres/pgvector, Turbopuffer, or Pinecone with no public extension point to register a fourth backend without forking Letta. Letta's own docs recommend "External RAG through custom tools or MCP" as the sanctioned path for exactly this case.
This PR follows that pattern:
MossLettaMemorywraps the Moss SDK with insert/search/delete/get/list operations, exposed through two integration surfaces plain async functions forclient.tools.upsert_from_function(), and a FastMCP server for out-of-process use. No code in thelettapackage is touched. Users opt in withinclude_base_tools=Falseat agent creation.Fixes #339
Type of Change
Testing
MossClient; 1 credential-gated test skips in CI.ruff checkpasses clean.mosspackage.