Skip to main content
Glama

search_events

Search through logged events using keywords to retrieve matching summaries with type and timestamp. A token-efficient alternative to generating full summaries.

Instructions

Plain-text search across all logged events.

Token-efficient alternative to get_summary when you only need events
matching a keyword. Returns matching event summaries with type and
timestamp.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
limitNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool handler for 'search_events'. Registered via @mcp.tool() decorator. Reads all events, performs case-insensitive substring match on summary/notes, returns last N matching events formatted as text.
    @mcp.tool()
    @safe_tool
    def search_events(query: str, limit: int = 10) -> str:
        """Plain-text search across all logged events.
    
        Token-efficient alternative to get_summary when you only need events
        matching a keyword. Returns matching event summaries with type and
        timestamp."""
        events = read_events()
        q = query.lower()
        matches = []
        for e in events:
            if q in e.summary.lower() or (e.notes and q in e.notes.lower()):
                matches.append(e)
        matches = matches[-limit:]
        if not matches:
            return f"No events match '{query}'."
        lines = [f"Found {len(matches)} match(es) for '{query}':"]
        for e in matches:
            outcome = f" ({e.outcome})" if e.outcome else ""
            loc = f" @ {e.location}" if e.location else ""
            lines.append(f"  [{e.type}{outcome}] {e.summary}{loc}")
        return "\n".join(lines)
  • Event dataclass used by search_events — defines the structure of events being searched (type, summary, notes, files, location, etc.)
    @dataclass
    class Event:
        type: str
        summary: str
        id: str = field(default_factory=lambda: f"evt_{uuid4().hex[:20]}")
        timestamp: str = field(default_factory=utc_now_iso)
        issue_id: str | None = None
        outcome: str | None = None
        files: list[str] = field(default_factory=list)
        command: str | None = None
        notes: str | None = None
        git_commit: str | None = None
        location: str | None = None
        # Auto-capture fields (P0)
        auto_captured: bool = False
        capture_source: str | None = None
        capture_confidence: str | None = None
        git_message: str | None = None
    
        def __post_init__(self) -> None:
            if self.type not in VALID_EVENT_TYPES:
                raise ValueError(f"Unsupported event type: {self.type}")
            if self.outcome is not None and self.outcome not in VALID_OUTCOMES:
                raise ValueError(f"Unsupported outcome: {self.outcome}")
            if self.capture_source is not None and self.capture_source not in VALID_CAPTURE_SOURCES:
                raise ValueError(f"Unsupported capture source: {self.capture_source}")
            if self.capture_confidence is not None and self.capture_confidence not in VALID_CONFIDENCE_LEVELS:
                raise ValueError(f"Unsupported confidence level: {self.capture_confidence}")
            self.summary = self.summary.strip()
            if not self.summary:
                raise ValueError("Event summary cannot be empty")
    
        def to_dict(self) -> dict[str, Any]:
            data = asdict(self)
            return {key: value for key, value in data.items() if value not in (None, [], False)}
    
        @classmethod
        def from_dict(cls, data: dict[str, Any]) -> "Event":
            return cls(
                id=data.get("id") or f"evt_{uuid4().hex[:20]}",
                timestamp=normalize_timestamp(data.get("timestamp")) if data.get("timestamp") else utc_now_iso(),
                type=data["type"],
                issue_id=data.get("issue_id"),
                summary=data["summary"],
                outcome=data.get("outcome"),
                files=list(data.get("files") or []),
                command=data.get("command"),
                notes=data.get("notes"),
                git_commit=data.get("git_commit"),
                location=data.get("location"),
                auto_captured=bool(data.get("auto_captured", False)),
                capture_source=data.get("capture_source"),
                capture_confidence=data.get("capture_confidence"),
                git_message=data.get("git_message"),
            )
  • Tool registered as MCP tool via @mcp.tool() decorator on the search_events function in mcp_server.py
    @mcp.tool()
    @safe_tool
    def search_events(query: str, limit: int = 10) -> str:
  • Core search logic: case-insensitive substring or regex matching across event summaries, notes, and files. Used by the CLI command and could be imported elsewhere.
    def search_events(query: str, regex: bool = False) -> list[Event]:
        """Search the event log.
    
        Default mode is case-insensitive substring match against the summary,
        notes, and `files` array. With ``regex=True`` the query is treated as
        a Python regex (case-insensitive) — useful for OR-patterns like
        ``"carousel|favicon"`` that previously returned `No matches.` because
        the literal pipe character isn't in any event (L-027c).
        """
        events = read_events()
        if regex:
            try:
                pattern = re.compile(query, re.IGNORECASE)
            except re.error:
                # Bad regex → fall back to literal substring rather than crash.
                return search_events(query, regex=False)
            return [
                event
                for event in events
                if pattern.search(event.summary)
                or (event.notes and pattern.search(event.notes))
                or any(pattern.search(f) for f in event.files)
            ]
        needle = query.casefold()
        return [
            event
            for event in events
            if needle in event.summary.casefold()
            or (event.notes and needle in event.notes.casefold())
            or any(needle in file_path.casefold() for file_path in event.files)
        ]
  • Helper function that reads events from events.jsonl file, used by the MCP tool handler to load events before searching.
    def read_events(root: Path | None = None) -> list[Event]:
        path = events_path(root)
        events: list[Event] = []
        for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
            if not line.strip():
                continue
            try:
                events.append(Event.from_dict(json.loads(line)))
            except (json.JSONDecodeError, KeyError, ValueError) as exc:
                raise ProjectMemError(f"Invalid event at {path}:{line_number}: {exc}") from exc
        return events
Behavior2/5

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

No annotations are provided, so the description bears full responsibility for behavioral disclosure. It only states it returns matching summaries, but does not disclose whether the search is read-only, any access restrictions, rate limiting, or edge case behavior (e.g., empty results). The lack of detail means the agent cannot fully anticipate the tool's side effects or constraints.

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?

The description is two sentences with no filler. The first sentence states the core functionality; the second provides an alternative and output details. It is appropriately front-loaded and efficient.

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

Completeness3/5

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

Given that an output schema exists, the description provides a basic idea of the return content (event summaries with type and timestamp). However, it lacks details on search semantics (e.g., case sensitivity, partial matching), pagination, and error handling. For a simple search tool with only two parameters, it is minimally complete but leaves gaps that could confuse an agent.

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

Parameters2/5

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

The input schema has zero description coverage, and the tool description does not add any details about the 'query' or 'limit' parameters. It mentions 'keyword' loosely but does not clarify the expected format or behavior of the query parameter. The 'limit' parameter is not mentioned at all, leaving its function implicit.

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 the action ('plain-text search'), the resource ('all logged events'), and distinguishes itself from sibling tool 'get_summary' by specifying it is a token-efficient alternative for keyword matching. It also specifies the return type: event summaries with type and timestamp.

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

Usage Guidelines4/5

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

It explicitly positions itself as an alternative to 'get_summary' when only keyword matching is needed, providing clear guidance on when to use it. However, it does not describe scenarios where it should not be used (e.g., when a full summary is needed) beyond implying that 'get_summary' would be better in those cases.

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/riponcm/projectmem'

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