Skip to main content
Glama

build_context

Retrieve conversation history from memory URLs to maintain context and enable natural follow-ups on previous discussions or related topics.

Instructions

Build context from a memory:// URI to continue conversations naturally.

Use this to follow up on previous discussions or explore related topics.

Memory URL Format:
- Use paths like "folder/note" or "memory://folder/note"
- Pattern matching: "folder/*" matches all notes in folder
- Valid characters: letters, numbers, hyphens, underscores, forward slashes
- Avoid: double slashes (//), angle brackets (<>), quotes, pipes (|)
- Examples: "specs/search", "projects/basic-memory", "notes/*"

Timeframes support natural language like:
- "2 days ago", "last week", "today", "3 months ago"
- Or standard formats like "7d", "24h"

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYes
projectNo
depthNo
timeframeNo7d
pageNo
page_sizeNo
max_relatedNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
pageNo
resultsNoHierarchical results with related items nested
metadataYes
page_sizeNo

Implementation Reference

  • The build_context tool implementation, including @mcp.tool() registration decorator and the full async handler function that builds graph context from memory URLs by calling the backend API.
    @mcp.tool(
        description="""Build context from a memory:// URI to continue conversations naturally.
    
        Use this to follow up on previous discussions or explore related topics.
    
        Memory URL Format:
        - Use paths like "folder/note" or "memory://folder/note"
        - Pattern matching: "folder/*" matches all notes in folder
        - Valid characters: letters, numbers, hyphens, underscores, forward slashes
        - Avoid: double slashes (//), angle brackets (<>), quotes, pipes (|)
        - Examples: "specs/search", "projects/basic-memory", "notes/*"
    
        Timeframes support natural language like:
        - "2 days ago", "last week", "today", "3 months ago"
        - Or standard formats like "7d", "24h"
        """,
    )
    async def build_context(
        url: MemoryUrl,
        project: Optional[str] = None,
        depth: str | int | None = 1,
        timeframe: Optional[TimeFrame] = "7d",
        page: int = 1,
        page_size: int = 10,
        max_related: int = 10,
        context: Context | None = None,
    ) -> GraphContext:
        """Get context needed to continue a discussion within a specific project.
    
        This tool enables natural continuation of discussions by loading relevant context
        from memory:// URIs. It uses pattern matching to find relevant content and builds
        a rich context graph of related information.
    
        Project Resolution:
        Server resolves projects in this order: Single Project Mode → project parameter → default project.
        If project unknown, use list_memory_projects() or recent_activity() first.
    
        Args:
            project: Project name to build context from. Optional - server will resolve using hierarchy.
                    If unknown, use list_memory_projects() to discover available projects.
            url: memory:// URI pointing to discussion content (e.g. memory://specs/search)
            depth: How many relation hops to traverse (1-3 recommended for performance)
            timeframe: How far back to look. Supports natural language like "2 days ago", "last week"
            page: Page number of results to return (default: 1)
            page_size: Number of results to return per page (default: 10)
            max_related: Maximum number of related results to return (default: 10)
            context: Optional FastMCP context for performance caching.
    
        Returns:
            GraphContext containing:
                - primary_results: Content matching the memory:// URI
                - related_results: Connected content via relations
                - metadata: Context building details
    
        Examples:
            # Continue a specific discussion
            build_context("my-project", "memory://specs/search")
    
            # Get deeper context about a component
            build_context("work-docs", "memory://components/memory-service", depth=2)
    
            # Look at recent changes to a specification
            build_context("research", "memory://specs/document-format", timeframe="today")
    
            # Research the history of a feature
            build_context("dev-notes", "memory://features/knowledge-graph", timeframe="3 months ago")
    
        Raises:
            ToolError: If project doesn't exist or depth parameter is invalid
        """
        track_mcp_tool("build_context")
        logger.info(f"Building context from {url} in project {project}")
    
        # Convert string depth to integer if needed
        if isinstance(depth, str):
            try:
                depth = int(depth)
            except ValueError:
                from mcp.server.fastmcp.exceptions import ToolError
    
                raise ToolError(f"Invalid depth parameter: '{depth}' is not a valid integer")
    
        # URL is already validated and normalized by MemoryUrl type annotation
    
        async with get_client() as client:
            # Get the active project using the new stateless approach
            active_project = await get_active_project(client, project, context)
    
            response = await call_get(
                client,
                f"/v2/projects/{active_project.external_id}/memory/{memory_url_path(url)}",
                params={
                    "depth": depth,
                    "timeframe": timeframe,
                    "page": page,
                    "page_size": page_size,
                    "max_related": max_related,
                },
            )
            return GraphContext.model_validate(response.json())
  • Input schema for the 'url' parameter: MemoryUrl type alias with validation, normalization, and constraints for memory:// URLs.
    MemoryUrl = Annotated[
        str,
        BeforeValidator(str.strip),  # Clean whitespace
        BeforeValidator(normalize_memory_url),  # Validate and normalize the URL
        MinLen(1),
        MaxLen(2028),
    ]
  • Output schema for the build_context tool: GraphContext Pydantic model containing hierarchical results, metadata, pagination.
    class GraphContext(BaseModel):
        """Complete context response."""
    
        # hierarchical results
        results: Sequence[ContextResult] = Field(
            description="Hierarchical results with related items nested", default_factory=list
        )
    
        # Context metadata
        metadata: MemoryMetadata
    
        page: Optional[int] = None
        page_size: Optional[int] = None
  • Helper function memory_url_path used in the handler to extract path from MemoryUrl for API call.
    def memory_url_path(url: memory_url) -> str:  # pyright: ignore
        """
        Returns the uri for a url value by removing the prefix "memory://" from a given MemoryUrl.
    
        This function processes a given MemoryUrl by removing the "memory://"
        prefix and returns the resulting string. If the provided url does not
        begin with "memory://", the function will simply return the input url
        unchanged.
    
        :param url: A MemoryUrl object representing the URL with a "memory://" prefix.
        :type url: MemoryUrl
        :return: A string representing the URL with the "memory://" prefix removed.
        :rtype: str
        """
        return url.removeprefix("memory://")
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While it explains the tool builds context for conversations and provides format details, it doesn't disclose critical behavioral traits like whether this is a read-only operation, what permissions are needed, whether it modifies data, rate limits, or what the output contains. For a tool with 7 parameters and no annotations, this is a significant gap.

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

Conciseness4/5

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

The description is well-structured and appropriately sized. It starts with the core purpose, provides usage guidance, then details parameter formats with clear sections. While comprehensive, every sentence serves a purpose - explaining the tool's function, when to use it, and parameter specifics. It could be slightly more concise by integrating some format details more tightly.

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 the tool's complexity (7 parameters, memory system interaction) and the presence of an output schema, the description provides good context about the tool's purpose and key parameters. However, with no annotations and incomplete parameter semantics coverage, it doesn't fully prepare an agent for all aspects of tool invocation. The output schema existence helps, but behavioral aspects remain under-specified.

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?

The description provides extensive information about the 'url' parameter format (memory:// URIs, pattern matching, valid characters, examples) and 'timeframe' parameter (natural language and standard formats). With 0% schema description coverage, this adds substantial value beyond the bare schema. However, it doesn't explain the semantics of 'depth', 'project', 'page', 'page_size', or 'max_related' parameters, leaving half the parameters without semantic explanation.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Build context from a memory:// URI to continue conversations naturally.' This specifies the verb ('build context') and resource ('memory:// URI'), though it doesn't explicitly differentiate from sibling tools like 'read_note' or 'search_notes' that might also access memory content. The purpose is clear but lacks sibling differentiation.

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?

The description provides clear usage context: 'Use this to follow up on previous discussions or explore related topics.' This gives guidance on when to use the tool (for conversation continuity or topic exploration). However, it doesn't specify when NOT to use it or mention alternatives among the many sibling tools, which would be needed for a perfect score.

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/basicmachines-co/basic-memory'

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