Skip to content

feat(tools): add Mengram memory tools (search, save, learned procedures) - #6687

Open
alibaizhanov wants to merge 8 commits into
crewAIInc:mainfrom
alibaizhanov:add-mengram-memory-tools
Open

feat(tools): add Mengram memory tools (search, save, learned procedures)#6687
alibaizhanov wants to merge 8 commits into
crewAIInc:mainfrom
alibaizhanov:add-mengram-memory-tools

Conversation

@alibaizhanov

Copy link
Copy Markdown

Summary

Adds three memory tools backed by Mengram — a memory layer with semantic (facts), episodic (events), and procedural memory (workflows that learn from successes and failures):

  • MengramSearchTool — semantic search over the user's long-term memory
  • MengramSaveTool — save durable facts/preferences/decisions
  • MengramProceduresTool — retrieve learned workflows with a success/failure track record and preconditions (assumptions violated in past failures), so agents stop repeating mistakes they already made

Follows existing tool conventions (Browserbase-style): lazy vendor import, package_dependencies, env_vars with MENGRAM_API_KEY, optional-dependency extra mengram, per-tool README, registered in tool/package __init__ and __all__. Multi-user isolation via user_id — one API key, isolated memory per end-user.

Underlying client: mengram-ai (Apache 2.0 core, free tier, self-hostable). Tool logic is unit-tested downstream against crewai 1.15.7 in our repo.

Happy to adjust naming, category, or add a docs page under docs/edge/en/tools/ if you'd like.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: cf040020-b0a1-4299-99f7-a552c3ab3d74

📥 Commits

Reviewing files that changed from the base of the PR and between daa7019 and 9afcc18.

📒 Files selected for processing (6)
  • lib/crewai-tools/pyproject.toml
  • lib/crewai-tools/src/crewai_tools/__init__.py
  • lib/crewai-tools/src/crewai_tools/tools/__init__.py
  • lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/README.md
  • lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/__init__.py
  • lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • lib/crewai-tools/src/crewai_tools/tools/init.py
  • lib/crewai-tools/src/crewai_tools/init.py
  • lib/crewai-tools/pyproject.toml
  • lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/README.md
  • lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py

📝 Walkthrough

Walkthrough

Adds three Mengram-backed CrewAI tools for searching, saving, and retrieving procedures from long-term memory. The change includes shared client configuration, an optional dependency, public package exports, and usage documentation.

Changes

Mengram Memory Tools

Layer / File(s) Summary
Tool contracts and client configuration
lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py
Defines Pydantic inputs and shared Mengram client setup with API-key validation, configurable endpoint, user ID, and result limit.
Memory operations and formatting
lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py
Implements memory search, text saving, and procedure retrieval through Mengram APIs, including formatted responses and empty-result messages.
Package integration and setup
lib/crewai-tools/pyproject.toml, lib/crewai-tools/src/crewai_tools/__init__.py, lib/crewai-tools/src/crewai_tools/tools/__init__.py, lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/README.md
Adds the mengram optional dependency, exports the three tools, and documents installation, configuration, usage, and arguments.

Sequence Diagram(s)

sequenceDiagram
  participant CrewAIAgent
  participant MengramTool
  participant MengramAPI
  CrewAIAgent->>MengramTool: Provide search, save, or procedure request
  MengramTool->>MengramAPI: Call search, add_text, or procedures
  MengramAPI-->>MengramTool: Return memory data or status
  MengramTool-->>CrewAIAgent: Return formatted result
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the new Mengram memory tools and matches the main change set.
Description check ✅ Passed The description is directly about the added Mengram-backed tools and supporting docs/config.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (1)
lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py (1)

8-22: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the public schemas and tool classes.

These public Python APIs currently rely on field/runtime metadata but have no class docstrings. Add concise docstrings for the three schemas and three public tools.

As per coding guidelines, public APIs and complex logic in Python code must be documented.

Also applies to: 56-63, 76-83, 90-98

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py`
around lines 8 - 22, Add concise class docstrings to MengramSearchToolSchema,
MengramSaveToolSchema, and MengramProceduresToolSchema, and to the three
corresponding public tool classes referenced by the affected sections. Describe
each schema’s or tool’s purpose without changing behavior or field metadata.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/crewai-tools/src/crewai_tools/tools/__init__.py`:
- Around line 82-86: Update the __all__ declaration in the crewai_tools.tools
module to include MengramProceduresTool, MengramSaveTool, and MengramSearchTool
alongside the existing public tool exports, matching the imported symbols and
preserving the declared wildcard-import API.

In
`@lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py`:
- Around line 58-66: Update MengramSearchTool._run to use Mengram’s unified
memory search, such as search_all, instead of the facts-only _client().search
call, and include episodic and procedural results in the returned output while
preserving the existing query, user_id, and limit parameters.
- Line 28: Change the user_id configuration used by MengramSearchTool,
MengramSaveTool, and MengramProceduresTool so it cannot default to the shared
"default" partition: require an explicit trusted per-user identifier or reject
construction when it is missing. Update the README usage guidance to discourage
omitting user_id and explain that it must be scoped per end user.
- Around line 112-113: Update the precondition extraction in the Mengram
response handling to use top-level p.get("preconditions") when
metadata.preconditions is absent, while preserving the existing empty-list
fallback and Verify first formatting. Modify the logic near the preconditions
and pre assignments in the Mengram memory tool.
- Line 27: Resolve MENGRAM_API_KEY at MengramMemoryTool initialization rather
than class definition time. Replace the eager os.getenv default on api_key with
initialization-time lookup or a Pydantic default factory, while preserving
explicitly provided API keys so _run() and _client() use the current environment
when no key is passed.

---

Nitpick comments:
In
`@lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py`:
- Around line 8-22: Add concise class docstrings to MengramSearchToolSchema,
MengramSaveToolSchema, and MengramProceduresToolSchema, and to the three
corresponding public tool classes referenced by the affected sections. Describe
each schema’s or tool’s purpose without changing behavior or field metadata.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 376ff867-ce6b-4f89-ace3-39c02d046b56

📥 Commits

Reviewing files that changed from the base of the PR and between daa7019 and 0fbf195.

📒 Files selected for processing (6)
  • lib/crewai-tools/pyproject.toml
  • lib/crewai-tools/src/crewai_tools/__init__.py
  • lib/crewai-tools/src/crewai_tools/tools/__init__.py
  • lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/README.md
  • lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/__init__.py
  • lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py

Comment thread lib/crewai-tools/src/crewai_tools/tools/__init__.py
"""Shared config for Mengram memory tools (https://mengram.io)."""

api_key: Optional[str] = os.getenv("MENGRAM_API_KEY")
user_id: str = "default"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Files:"
git ls-files | rg 'mengram_memory_tool\.py|mengram.*memory|Memory|user_id' || true

echo
echo "Target file outline/section:"
if [ -f lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py ]; then
  wc -l lib/crewai-tools/src/crewai_tools/tools/mengai_tools/tools/mengram_memory_tool/mengram_memory_tool.py 2>/dev/null || true
  sed -n '1,240p' lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py
fi

echo
echo "Search references to mengram_memory_tool and user_id:"
rg -n "mengram_memory_tool|Mengram|user_id|default" lib/crewai-tools/src/crewai_tools/tools 2>/dev/null || true

Repository: crewAIInc/crewAI

Length of output: 50372


🌐 Web query:

mengram-ai user_id multi-user isolation documentation

💡 Result:

Mengram-ai provides multi-user isolation by allowing you to scope memory operations per end-user using a user_id parameter, enabling multiple users to exist under a single API key [1][2]. Core Mechanisms: - Scoping: When performing memory operations such as adding or searching for information, you can pass a user_id (a string identifier) to ensure data is logically separated [1][3][4]. - Default Behavior: If the user_id parameter is omitted, the system uses a default scope (often labeled as "default") tied to the API key [1][3][4]. - Isolation: Each user_id maintains their own isolated facts, episodic events, procedural workflows, and cognitive profiles [1][5][2]. Usage Examples: Python SDK: m.add([{"role": "user", "content": "Alice prefers dark mode"}], user_id="alice") m.search("preferences", user_id="alice") # Only returns Alice's memories [1] JavaScript SDK: await m.add([...], { userId: 'alice' }); await m.searchAll('prefs', { userId: 'alice' }); // Only Alice's data [2] MCP (Model Context Protocol): Every MCP tool accepts an optional user_id parameter to scope memories per end-user. This allows developers to build multi-tenant applications where a single API key serves multiple isolated users [1]. In addition to user_id, you can further refine data isolation using agent_id, run_id, and app_id to manage complex multi-agent or multi-environment systems [5][4].

Citations:


🌐 Web query:

Mengram Python SDK add_text user_id procedures search default scope user_id

💡 Result:

In the Mengram Python SDK, the add_text method supports the user_id parameter to provide multi-user isolation for stored memories [1][2][3]. When calling add_text, the user_id parameter defaults to "default" if not explicitly provided [1][2][3]. This "default" scope is tied to your API key, meaning any memories added without a specific user_id are grouped within that global or default namespace [2][4]. To isolate memories for specific users, you should provide a unique user_id string when calling add_text, as well as when performing searches or other operations [5][4][6]. Example usage: from mengram import Mengram m = Mengram(api_key="your-api-key") # Adding text with a specific user_id m.add_text("User prefers dark mode", user_id="alice") # Searching with the same user_id to restrict scope results = m.search("preferences", user_id="alice") This pattern applies consistently across other methods in the Mengram SDK, such as add, search, and procedures, ensuring that your procedural or semantic data remains isolated by user_id [5][4].

Citations:


Do not allow the "default" Mengram user partition across end users.

MengramSearchTool, MengramSaveTool, and MengramProceduresTool all pass user_id=self.user_id to Mengram, but user_id defaults to "default". A shared API key plus omitted/request-default user IDs causes distinct end users to read/write the same memory namespace. Make user_id required, or reject construction without trusted per-user context, and update the README to discourage omitting it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py`
at line 28, Change the user_id configuration used by MengramSearchTool,
MengramSaveTool, and MengramProceduresTool so it cannot default to the shared
"default" partition: require an explicit trusted per-user identifier or reject
construction when it is missing. Update the README usage guidance to discourage
omitting user_id and explain that it must be scoped per end user.

@alibaizhanov

Copy link
Copy Markdown
Author

Thanks for the review — addressed the substantive ones in the latest commits:

  • API key at import time → now resolved at call time (explicit api_key wins, else MENGRAM_API_KEY read when the tool runs), so it picks up the environment as configured.
  • Facts-only searchMengramSearchTool now uses search_all and returns semantic + episodic + procedural results.
  • Preconditions extraction → added the top-level preconditions fallback alongside metadata.preconditions.
  • __all__ → exported the three tools in tools/__init__.py.
  • Docstrings → added to the three schemas and three tool classes.

On the user_id default: kept "default" to match every other tool's single-user ergonomics (and the other Mengram SDKs) — the README already documents passing user_id for per-end-user isolation in multi-tenant apps. Happy to make it required if the maintainers prefer that convention.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py (1)

37-39: 🔒 Security & Privacy | 🟠 Major

Require an explicit per-user partition.

Line 38 still defaults all three tools to "default". When multiple end users share one API key, omitted IDs cause cross-user reads and writes in the same Mengram namespace. Make user_id required (or reject the shared default) and document the trusted per-user requirement. Mengram documents "default" as the shared fallback scope. (docs.mengram.io)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py`
around lines 37 - 39, Update the configuration containing api_key, user_id, and
base_url to require an explicit user_id instead of defaulting to "default";
reject omitted or shared fallback values if the framework requires an optional
field, and document that callers must provide a trusted per-user identifier to
isolate Mengram reads and writes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In
`@lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py`:
- Around line 37-39: Update the configuration containing api_key, user_id, and
base_url to require an explicit user_id instead of defaulting to "default";
reject omitted or shared fallback values if the framework requires an optional
field, and document that callers must provide a trusted per-user identifier to
isolate Mengram reads and writes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 678c432c-4173-4d68-abf7-8a52d5b91847

📥 Commits

Reviewing files that changed from the base of the PR and between 0fbf195 and 9afcc18.

📒 Files selected for processing (2)
  • lib/crewai-tools/src/crewai_tools/tools/__init__.py
  • lib/crewai-tools/src/crewai_tools/tools/mengram_memory_tool/mengram_memory_tool.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant