How ai-memory Implements Per-Session Auto-Scope Routing with the Session-Aware Bridge

ai-memory achieves per-session isolation by having a session-aware stdio bridge inject a unique session identifier into every MCP request, which the server uses to automatically resolve the correct workspace and project scope from the session's recorded working directory.

The ai-memory project provides an intelligent memory system for AI assistants that must route requests to the correct project context without manual configuration. The per-session auto-scope routing mechanism ensures that each assistant session operates in its own isolated environment, preventing data leakage between concurrent sessions.


Architecture Overview

The routing system consists of two primary components working in tandem:

  1. The Session-Aware Bridge — a client-side stdio-to-HTTP proxy that captures session context
  2. The Auto-Scope Resolver — server-side logic that maps session IDs to project scopes

This design allows Claude Code and compatible clients to launch isolated sessions where each request automatically targets the correct project based on where the session was started.


Step 1: Bridge Injection of Session ID

The session-aware bridge is installed via the CLI and becomes the entry point for all MCP communication.

Installation Command

ai-memory install-mcp --client claude-code --session-aware --apply

Bridge Implementation Details

In crates/ai-memory-cli/src/commands/mcp_bridge.rs, the bridge performs three critical functions:

  • Reads the session id from the lifecycle hook environment
  • Creates an HTTP client for forwarding stdio traffic
  • Appends session_id as a query parameter to every outgoing MCP request

This transformation happens transparently — the underlying AI assistant (Claude Code) writes JSON-RPC messages to stdout as normal, but the bridge intercepts and enriches each request with session context before forwarding to the ai-memory HTTP server.


Step 2: Server-Side Session Resolution

When the MCP server receives a request bearing a session_id parameter, it activates session-aware routing mode.

Core Resolution Logic

In crates/ai-memory-mcp/src/server.rs (line 172), the server handles incoming requests:

// Simplified representation of the server's routing decision
let scope = if let Some(session_id) = req.query("session_id") {
    // Session-aware path: resolve scope from session's recorded state
    ScopeResolver::resolve_by_session(&session_id)?
} else {
    // Explicit scope path: require workspace + project parameters
    ScopeResolver::resolve_explicit(&req)?
};

The ScopeResolver::resolve_by_session function performs a lookup to find the workspace and project associated with that session's original working directory. This lookup is what enables auto-scoping — the caller needs no knowledge of ai-memory's internal project structure.


Step 3: Auto-Scope Selection from Session CWD

The auto-scope mechanism defaults to the project resolved from the session's working directory at startup time.

Routing Snippet Implementation

In crates/ai-memory-core/src/routing_snippet.rs (line 36), the core logic determines:

  • If workspace or project parameters are explicitly provided → use those
  • If absent but session_id is present → auto-scope to the session's recorded project
  • If neither explicit scope nor session id → trigger error handling

This three-tier fallback ensures maximum flexibility while maintaining safety boundaries.


Step 4: Isolation Enforcement via Scope Triple

Once resolved, the server tags every request with a (workspace_id, project_id, session_id) tuple. This triple propagates through all downstream operations:

Component Enforcement Behavior
Store Read/write operations filtered by scope triple
Wiki Entries created with session-attributed metadata
Retrieval Search results scoped to authorized projects

The session_id component provides an additional audit trail and enables future features like session replay or temporary workspace branching.


Step 5: Error Handling for Scope Bleed Prevention

If the bridge omits the session identifier or the resolver cannot locate the session record, the server returns a protective error.

In crates/ai-memory-mcp/src/server.rs (line 5297), the explicit error message states:

"auto-scoped error must hint at scope-bleed"

This error design serves two purposes:

  • Prevents silent misrouting — requests fail loudly rather than defaulting to an incorrect scope
  • Aids debugging — the "scope-bleed" terminology alerts developers to potential cross-session contamination

Example error response:

{
  "error": "auto-scoped error must hint at scope-bleed; got missing session_id"
}

Practical Code Examples

Starting a Session-Aware Client Session


# The bridge handles all session context automatically

ai-memory install-mcp --client claude-code --session-aware

# Subsequent Claude Code runs use the bridged MCP server

# Each independent Claude Code window receives a unique session id

HTTP Request Flow

// Bridge transforms stdio message to HTTP request
POST /mcp/v1/call?session_id=4a7b9c23-e1f5-4d3a-9c2b-5e7a6d8f9c0e
Content-Type: application/json

{
  "method": "notes/search",
  "params": {
    "query": "authentication patterns",
    // No workspace or project needed — auto-resolved from session
  }
}

Server-Side Scope Resolution (Conceptual)

// From crates/ai-memory-core/src/routing_snippet.rs
pub struct ScopeResolver;

impl ScopeResolver {
    pub fn resolve_by_session(session_id: &str) -> Result<Scope, Error> {
        let session = SessionStore::get(session_id)
            .ok_or(Error::SessionNotFound)?;
        
        // Auto-scope to project derived from session's original cwd
        let project = ProjectIndex::find_by_path(&session.cwd)?;
        
        Ok(Scope {
            workspace_id: project.workspace_id,
            project_id: project.id,
            session_id: session_id.to_string(),
        })
    }
}

Key Source Files

File Path Responsibility
crates/ai-memory-cli/src/commands/mcp_bridge.rs Implements stdio-to-HTTP bridge with session ID injection
crates/ai-memory-mcp/src/server.rs MCP server entry point; session-aware routing logic at lines 172 and 5297
crates/ai-memory-core/src/routing_snippet.rs Core auto-scope resolution from session working directory
docs/auto-scope.md Human-readable documentation of per-session auto-scope modes
docs/users.md User guide explaining session ID forwarding across requests

Summary

  • The session-aware bridge (mcp_bridge.rs) transparently adds session_id to every MCP request based on the client lifecycle hook environment.

  • Auto-scope resolution (routing_snippet.rs) eliminates the need for manual workspace/project parameters by deriving scope from each session's recorded working directory.

  • Triple-tag isolation ((workspace_id, project_id, session_id)) enforces boundaries across all data operations, preventing cross-session leakage.

  • Explicit error design ("scope-bleed" errors) ensures misconfigurations fail visibly rather than silently routing requests to wrong projects.

  • The architecture supports multiple concurrent sessions with zero configuration per session beyond the initial --session-aware bridge installation.


Frequently Asked Questions

What happens if I use the session-aware bridge without a session ID?

The server detects the missing identifier and returns an explicit error: "auto-scoped error must hint at scope-bleed; got missing session_id". This prevents the request from defaulting to an arbitrary scope and potentially exposing or modifying the wrong project's data.

Can I override auto-scope with explicit workspace and project parameters?

Yes. The resolution logic checks for explicit workspace and project parameters first. If present, these take precedence over the auto-scoped value from the session. This allows intentional cross-scope operations when needed while maintaining safe defaults.

Does the session-aware bridge work with clients other than Claude Code?

The bridge is client-agnostic in implementation, but requires a client that provides a stable session identifier through environment variables or similar lifecycle hooks. Claude Code has built-in support; other MCP clients would need equivalent hook mechanisms to populate the session context that the bridge reads.

How does ai-memory handle sessions that change their working directory mid-session?

The session's scope is fixed at initialization time based on the original working directory. Changing directories within a session does not alter the auto-scoped project, which prevents confusing scope shifts during long-running assistant conversations. Users needing to work across multiple projects should start separate sessions.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →