Skip to main content
Glama

search

Find relevant information across memory files by keyword. Returns matching file names, titles, strengths, and context snippets for quick retrieval.

Instructions

Search across all memory files by keyword. Returns matching file names, titles, strengths, and context snippets.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesKeyword or phrase to search for

Implementation Reference

  • Handler function for the 'search' MCP tool. Reads all memory files, performs keyword matching on the content, extracts context snippets around matches, and returns formatted results with file name, tier, strength, and up to 3 snippets per match.
    def handle_tools_call(req_id, name, args):
        if name == "search":
            query = args.get("query", "").lower()
            if not query:
                return {"content": [{"type": "text", "text": "No query provided."}]}, None
            files = list_memory_files()
            results = []
            for f in files:
                with open(os.path.join(MEMORY_DIR, f["path"]), encoding="utf-8") as fh:
                    text = fh.read().lower()
                if query in text:
                    lines = text.splitlines()
                    snippets = []
                    for i, line in enumerate(lines):
                        if query in line.lower():
                            start = max(0, i - 1)
                            end = min(len(lines), i + 2)
                            snippet = "\n".join(lines[start:end]).strip()
                            if len(snippet) > 200:
                                snippet = snippet[:200] + "..."
                            snippets.append(snippet)
                    results.append({
                        "title": f["title"] or f["name"],
                        "path": f["path"],
                        "tier": f["tier"],
                        "strength": f["strength"],
                        "snippets": snippets[:3],
                    })
            if not results:
                return {"content": [{"type": "text", "text": f"No memories matched '{query}'."}]}, None
            lines = [f"Found {len(results)} memory(s) for '{query}':", ""]
            for r in results:
                lines.append(f"  [{r['tier']}] {r['title']}  (strength: {r['strength']:.2f})")
                lines.append(f"         path: {r['path']}")
                for s in r["snippets"]:
                    lines.append(f"         > {s}")
                lines.append("")
            return {"content": [{"type": "text", "text": "\n".join(lines)}]}, None
  • Schema/definition of the 'search' tool. Declares the tool's name, description, and input schema requiring a 'query' string parameter.
    {
        "name": "search",
        "description": "Search across all memory files by keyword. Returns matching file names, titles, strengths, and context snippets.",
        "inputSchema": {
            "type": "object",
            "properties": {"query": {"type": "string", "description": "Keyword or phrase to search for"}},
            "required": ["query"],
        },
    },
  • nexus_mcp.py:120-130 (registration)
    The 'search' tool is registered as part of the TOOL_DEFS list, which is returned by handle_tools_list() in response to a 'tools/list' MCP request.
    TOOL_DEFS = [
        {
            "name": "search",
            "description": "Search across all memory files by keyword. Returns matching file names, titles, strengths, and context snippets.",
            "inputSchema": {
                "type": "object",
                "properties": {"query": {"type": "string", "description": "Keyword or phrase to search for"}},
                "required": ["query"],
            },
        },
        {
  • nexus_mcp.py:365-375 (registration)
    Dispatcher routing in the main loop: 'tools/list' calls handle_tools_list() which returns TOOL_DEFS (including 'search'), and 'tools/call' dispatches to handle_tools_call() where the 'search' case is handled.
    elif method == "tools/list":
        result = handle_tools_list(req_id)
        respond(req_id, result)
    elif method == "tools/call":
        name = params.get("name", "")
        args = params.get("arguments", {})
        result, err = handle_tools_call(req_id, name, args)
        if err:
            respond(req_id, error=err)
        else:
            respond(req_id, result)
  • Helper function used by the search handler to enumerate all memory files across tiers with their metadata (name, title, tier, strength, path).
    def list_memory_files():
        """Return list of {tier, name, path, title, strength, type} for all memories."""
        results = []
        for tier in TIERS:
            tier_dir = os.path.join(MEMORY_DIR, tier)
            if not os.path.isdir(tier_dir):
                continue
            for f in sorted(glob.glob(os.path.join(tier_dir, "*.md"))):
                name = os.path.splitext(os.path.basename(f))[0]
                with open(f, encoding="utf-8") as fh:
                    content = fh.read()
                title = ""
                for line in content.splitlines():
                    if line.startswith("# "):
                        title = line[2:]
                        break
                strength = parse_frontmatter(content, "strength") or "1.0"
                type_ = parse_frontmatter(content, "type") or tier
                results.append({
                    "uri": f"nexus://{tier}/{name}",
                    "name": name,
                    "title": title,
                    "tier": tier,
                    "strength": float(strength),
                    "type": type_,
                    "path": os.path.relpath(f, MEMORY_DIR),
                })
        return results
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description discloses the return components (file names, titles, strengths, context snippets), giving insight into expected output. As there are no annotations, the description adequately conveys that this is a read/search operation without side effects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two concise sentences front-load the action and output. No wasted words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the simple tool with one parameter and no output schema, the description is complete—it explains the search scope, input, and output format.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 100% schema description coverage, the description adds marginal value by framing 'query' as a keyword, but the schema already describes it. Baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states that the tool searches across all memory files by keyword and lists the returned fields (file names, titles, strengths, context snippets). It is distinct from siblings like 'save' or 'decay' which have different purposes.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for searching memory files but does not provide explicit when-to-use or when-not-to-use guidance, nor does it mention alternatives among the sibling tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Y-Sky-bro/nexus-memory'

If you have feedback or need assistance with the MCP directory API, please join our Discord server