Skip to Content
Mind Palace 0.4.2-alpha is out. Check it out →
Autonomous Agent Guide

Autonomous Agent Guide

Mind Palace is designed for deterministic, autonomous agent workflows. This guide shows AI agents how to use Mind Palace automatically without manual intervention.

Philosophy: Why Mind Palace for Agents?

Modern AI agents work across large codebases without your institutional memory. Mind Palace provides:

  1. Session Management: Coordinate multiple agents, prevent conflicts
  2. Deterministic Context: No embeddings required - schema-validated, queryable knowledge
  3. File Intelligence: Know what breaks, what’s hot, what decisions apply to each file
  4. Failure Memory: Learn from past mistakes automatically
  5. Autonomous Workflows: Agents know WHEN to use tools via priority system

Quick Start: Single-Call Initialization

Every agent task starts with one call:

// 1. Initialize with full context (RECOMMENDED - ONE CALL DOES IT ALL) const init = await session_init({ agent_name: "cursor", task: "Add authentication", }); // Returns: session ID, workspace briefing, project structure, pending handoffs // 2. Get file context before editing const fileContext = await file_context({ file_path: "auth/jwt.ts" }); // fileContext includes: learnings, decisions, failures, hotspots // 3. End session when done await session({ action: "end", outcome: "success", summary: "Added JWT refresh tokens", });

That’s it. session_init combines session start + brief + explore rooms into a single call and shows any pending handoffs waiting for you.

Priority System

Mind Palace provides 21 consolidated MCP tools with action-based dispatching:

  • 🔴 CRITICAL: Must do these (session_init, file_context, session with action=end)
  • 🟡 IMPORTANT: Should do these (store, session with action=log/conflict, handoff)
  • 🟢 RECOMMENDED: Optional but valuable (recall, explore, context, analytics)
  • ADMIN: Human-mode only (govern with action=approve/reject, store with direct=true)

Agents should always execute CRITICAL tools, usually execute IMPORTANT tools, and conditionally use RECOMMENDED tools.

Consolidated Tools Reference

ToolActionsDescription
session_init-🔴 Initialize session with full context (combines start + brief + rooms)
file_context-🔴 Get file context before editing
exploresearch, rooms, context, impact, callers, dependencies, symbols, file, files, preview, room_by_path🟢 Explore codebase structure
store- (use direct: true for bypass)🟡 Store learnings/decisions/ideas
recallquery, outcome, link, unlink, obsolete, archive🟢 Recall knowledge and manage records
briefworkspace, file, stats🟢 Get briefings and analytics
sessionstart, end, log, list, conflict, get, resume🔴🟡 Session lifecycle management
searchsemantic, text, hybrid🟢 Search across knowledge base
embeddinggenerate, refresh⚪ Manage embeddings
contextauto_inject, focus, blur, get_focus, clear🔴🟢 Context management
contradictioncheck, resolve🟢 Detect/resolve contradictions
decaycheck, prune⚪ Manage knowledge decay
postmortemcreate, get, resolve, list, stats, to_learnings🟢 Failure analysis
handoffcreate, get, list, claim, complete🟡 Agent handoffs
conversationpersist🟢 Save conversation history
corridorlearnings🟢 Cross-workspace knowledge
patterndetect, analyze, common🟢 Pattern detection
contractextract🟢 Extract code contracts
analyticshealth, freshness🟢 Workspace analytics
governapprove, reject, list⚪ Proposal governance
route-🟢 Smart context routing

Complete Autonomous Workflow

Here’s a full example for adding a feature:

1. Session Initialize (🔴 CRITICAL - THE FIRST CALL)

const init = await session_init({ agent_name: "cursor", task: "Add JWT refresh token support", });

Returns:

  • Session ID (use for all subsequent calls)
  • Active agents and their current work
  • Workspace learnings and decisions
  • Hotspot files (frequently modified, high failure rate)
  • Recent failures and postmortems
  • Pending handoffs (tasks waiting to be picked up)
  • Project structure (rooms and entry points)

Why: This single call replaces session_start + brief + explore_rooms. It tracks your work, prevents conflicts, and gives you full context immediately.

1b. (Alternative) Resume Previous Session

If continuing previous work:

const resumed = await session_resume({ sessionId: "sess_abc123", // Or use agentType to find latest });

Why: Picks up where you left off with full context restoration.

// Find relevant code const results = await explore({ action: "search", query: "jwt authentication", }); // Get room context const rooms = await explore({ action: "rooms" }); // ["api", "auth", "database"] const authContext = await explore({ action: "context", room: "auth" }); // Understand dependencies const impact = await explore({ action: "impact", path: "auth/jwt.ts" }); const callers = await explore({ action: "callers", symbol: "validateToken", file: "auth/jwt.ts", });

Why: Understand codebase structure before making changes.

// Check for related learnings const learnings = await recall({ action: "query", query: "jwt authentication", }); // Check for active decisions const decisions = await recall({ action: "query", type: "decisions", query: "token validation", status: "active", }); // Learn from past failures const postmortems = await postmortem({ action: "list", severity: "high" });

Why: Avoid repeating past mistakes. Leverage existing knowledge.

5. Get File Context (🔴 CRITICAL - BEFORE EVERY EDIT)

const context = await context({ action: "auto_inject", file_path: "auth/jwt.ts", });

Returns prioritized context:

  • File-scoped learnings (“never use X in this file”)
  • File-scoped decisions (“this file must use Y pattern”)
  • Failure warnings (“this breaks 40% of the time”)
  • Edit history (who changed it, when, why)
  • Related learnings from room/palace scopes

Why: This is non-negotiable. Editing without file context is like performing surgery without reading the patient’s chart.

6. Check for Conflicts (🟡 IMPORTANT)

const conflict = await session({ action: "conflict", path: "auth/jwt.ts" }); if (conflict.has_conflict) { console.log(`${conflict.agent_name} is already editing this file`); // Coordinate or wait }

Why: Prevents merge conflicts and wasted work.

7. Make Changes

Now you have full context. Edit the file safely.

8. Log Activity (🟡 IMPORTANT)

await session({ action: "log", activity: "file_edit", path: "auth/jwt.ts", description: "Added refresh token validation logic", });

Why: Creates audit trail. Enables session analysis.

9. Store Knowledge (🟡 IMPORTANT)

// Store learnings await store({ content: "JWT refresh tokens should expire in 7 days, access tokens in 1 hour", as: "decision", scope: "room", scopePath: "auth", rationale: "Balance security (short access tokens) with UX (longer refresh)", }); // Store learnings from solving problems await store({ content: "JWT signature validation must happen before expiration check to prevent timing attacks", as: "learning", scope: "file", scopePath: "auth/jwt.ts", });

Why: Builds institutional knowledge. Future agents (or you) can recall this.

10. End Session (🔴 CRITICAL)

await session({ action: "end", outcome: "success", summary: "Added JWT refresh token support with proper validation and expiration handling", });

Why: Releases locks, marks task complete, enables session analysis.

Failure Handling: Postmortems

When things go wrong, create a postmortem:

await store_postmortem({ title: "JWT signature bypass vulnerability", what_happened: "Expired tokens were accepted due to wrong validation order", root_cause: "Checked expiration before signature, allowing signature replay attacks", lessons_learned: [ "Always validate signature first", "Add integration tests for expired tokens", "Review security checklist before auth changes", ], prevention_steps: [ "Reorder validation: signature → expiration → claims", "Add test: test_expired_token_rejection()", "Add pre-commit hook for auth file changes", ], severity: "critical", affected_files: ["auth/jwt.ts", "middleware/authenticate.ts"], related_decision: "d_abc123", }); // Extract learnings from postmortem await postmortem_to_learnings({ postmortemId: "pm_xyz789" });

This prevents repeating the same mistake.

Scope Hierarchy

Knowledge has four scope levels (most specific wins):

  1. File: scope: "file", scopePath: "auth/jwt.ts"

    • “This specific file should never import from parent directories”
  2. Room: scope: "room", scopePath: "auth"

    • “All auth files must use bcrypt for password hashing”
  3. Palace (workspace): scope: "palace"

    • “Use TypeScript strict mode across entire project”
  4. Corridor (personal/global): Requires explicit promotion

    • “Always validate input at API boundaries” (applies to all your projects)

When storing knowledge, choose the narrowest applicable scope.

Context Management

Set Task Focus

Focus context retrieval on your current task:

await context_focus({ task: "Implement rate limiting for API endpoints", pin: ["l_ratelimit123", "d_api456"], // Pin specific records });

Now all context retrievals will prioritize rate-limiting related knowledge.

Get Focused Context

const context = await context_get({ file: "api/middleware.ts", // Optional: file-specific maxTokens: 2000, });

Returns prioritized learnings, pinned records, active decisions, and warnings.

Pin Important Records

// Pin a crucial learning for this session await context_pin({ id: "l_important123" }); // Unpin when no longer needed await context_pin({ id: "l_important123", unpin: true });

Multi-Agent Handoffs

Create a Handoff

When you can’t complete a task, hand it off:

await handoff_create({ task: "Complete API rate limiting implementation", to: "claude-code", // Or "any" for any agent context: "Started implementing token bucket algorithm. Redis backend configured.", pending: [ "Add rate limit headers to responses", "Implement per-user limits", "Add monitoring dashboard", ], pin: ["l_ratelimit123"], // Include relevant learnings priority: "high", });

Check for Pending Handoffs

const handoffs = await handoff_list({ status: "pending" });

Note: session_init automatically shows pending handoffs at session start.

Accept a Handoff

const handoff = await handoff_accept({ id: "hoff_12345678" }); // Automatically sets your context focus to the handoff task // Pins the handoff's records to your context

Complete a Handoff

await handoff_complete({ id: "hoff_12345678", summary: "Implemented all rate limiting features with Redis backend", });

Analytics & Health

Check Workspace Health

const health = await analytics_health(); // Returns: health score (0-100), knowledge health, contradictions, // session success rates, failure tracking, handoff status

Session Analytics

const stats = await analytics_sessions({ days: 30 }); // Returns: session counts, completion rates, average duration, // activity outcomes, agent breakdown

Learning Effectiveness

const effectiveness = await analytics({ type: "learnings", limit: 20, sort: "use_count", // or "confidence" or "combined" }); // Shows which learnings are most used and effective

Advanced Features

Semantic Search (if embeddings configured)

// Conceptual search - finds related concepts even without keyword match await search({ mode: "semantic", query: "retry logic with exponential backoff", }); // Hybrid: keyword + semantic (best of both) await search({ mode: "hybrid", query: "error handling" }); // Find similar records await search({ mode: "similar", recordId: "l_abc123" });

Contradiction Detection

// Check for contradicting records await contradiction({ action: "check", record1Id: "l_abc123", record2Id: "d_xyz789", }); // Resolve contradiction await contradiction({ action: "resolve", conflictId: "conflict_123" });

Decay Management

// Preview what would decay await decay({ action: "check" }); // Apply decay (reduces confidence of unused learnings) // NEVER do this without preview + user approval await decay({ action: "prune" });

Learning Lifecycle

// Link learning to decision for automatic feedback await recall({ action: "link", decisionId: "d_abc123", learningId: "l_xyz789", }); // Now when decision outcome is recorded, learning confidence auto-updates // Record decision outcome await recall({ action: "outcome", decisionId: "d_abc123", outcome: "success", note: "Reduced DB queries by 60%, no issues in production", }); // Mark learning as obsolete await recall({ action: "obsolete", learningId: "l_old123", reason: "Superseded by new approach using Redis caching", });

Corridor (Cross-Workspace Knowledge)

// Get personal learnings from all your projects await corridor({ action: "learnings", query: "error handling" }); // Promote workspace learning to personal corridor await corridor_promote({ learningId: "l_abc123" }); // Now this learning follows you to every project // Reinforce corridor learning when it helps await corridor_reinforce({ learningId: "l_corridor456" });

Anti-Patterns (Don’t Do This)

❌ Start work without session_start
❌ Edit files without context_auto_inject
❌ Forget to call session_end
❌ Work without calling brief first
❌ Ignore session_conflict warnings
❌ Store vague learnings (“this is good” - too generic)
❌ Never log activities (breaks audit trail)
❌ Apply decay without preview + approval

Best Practices

✅ Start with session_start, brief
✅ Get context before every file edit
✅ Check conflicts before editing
✅ Store specific, actionable learnings
✅ Log major activities
✅ End session when done
✅ Learn from postmortems
✅ Use explore tools to understand codebase
✅ Check decisions before implementing
✅ Choose appropriate scope for knowledge

Configuration for Agents

Mind Palace provides preset rules files for all major AI coding tools. When you install MCP configuration, the appropriate rules file is automatically copied to your workspace.

Supported Tools

ToolRule FileCommand
Claude CodeCLAUDE.mdpalace mcp-config --for claude-code --install
Cursor.cursorrulespalace mcp-config --for cursor --install
Windsurf.windsurfrulespalace mcp-config --for windsurf --install
VS Code Copilot.github/copilot-instructions.mdpalace mcp-config --for vscode --install
Gemini CLIGEMINI.mdpalace mcp-config --for gemini-cli --install
Claude DesktopglobalRules in configpalace mcp-config --for claude-desktop --install

Example: Setting Up Claude Code

# Initialize Mind Palace in your project palace init palace scan # Install MCP config and agent rules palace mcp-config --for claude-code --install

This creates:

  • .mcp.json - MCP server configuration
  • CLAUDE.md - Agent rules file with autonomous workflow instructions

Example: Setting Up Cursor

palace mcp-config --for cursor --install

This creates:

  • ~/.cursor/mcp.json - MCP server configuration
  • .cursorrules - Agent rules file in your workspace

See the Agent Rules Reference for complete documentation on customizing rules for your team.

Tool Categories

Mind Palace has 77+ tools across 13 categories:

The 21 consolidated tools are organized into categories:

  1. Composite (2 tools): session_init, file_context - single-call workflows
  2. Core (5 tools): explore, store, recall, brief, session - primary operations
  3. Search (2 tools): search, embedding - search and embeddings
  4. Intelligence (3 tools): context, contradiction, decay - smart context management
  5. Workflow (3 tools): postmortem, handoff, conversation - collaboration
  6. Cross-workspace (1 tool): corridor - personal knowledge across projects
  7. Analysis (3 tools): pattern, contract, analytics - code analysis
  8. Governance (2 tools): govern, route - approval and routing

Each tool uses an action parameter to select specific functionality.

Example: Complete Feature Implementation

// 1. Initialize (single call) const init = await session_init({ agent_name: "claude", task: "Add rate limiting to API", }); // Check init.pendingHandoffs for any waiting tasks // 2. Explore const apiFiles = await explore({ action: "context", room: "api" }); const rateLimitCode = await explore({ action: "search", query: "rate limiting middleware", }); // 3. Recall Knowledge const learnings = await recall({ action: "query", query: "rate limiting" }); const decisions = await recall({ action: "query", type: "decisions", query: "api security", status: "active", }); const failures = await postmortem({ action: "list", severity: "high" }); // 4. Get File Context const ctx = await file_context({ file_path: "api/middleware/rateLimit.ts" }); // 5. Check Conflicts await session({ action: "conflict", path: "api/middleware/rateLimit.ts" }); // 6. Make Changes // [Edit file with full context] // 7. Log Activity await session({ action: "log", activity: "file_edit", path: "api/middleware/rateLimit.ts", description: "Implemented token bucket rate limiting", }); // 8. Store Knowledge await store({ content: "Use token bucket algorithm for API rate limiting - allows bursts while maintaining average rate", as: "decision", scope: "room", scopePath: "api", rationale: "More flexible than fixed window, prevents thundering herd", }); await store({ content: "Rate limit counters should use Redis with TTL, not in-memory - enables multi-instance deployment", as: "learning", scope: "file", scopePath: "api/middleware/rateLimit.ts", }); // 9. End Session await session({ action: "end", outcome: "success", summary: "Implemented token bucket rate limiting with Redis backend", });

FAQ

Q: Should I use session_init or session with action=start? A: Use session_init - it’s a single call that combines start + brief + explore rooms and shows pending handoffs.

Q: Can I skip file_context if I’m making a small change? A: No. Small changes can have big impacts. Always get file context.

Q: When should I store knowledge? A: After solving problems, making decisions, or discovering patterns. Be specific and actionable.

Q: What’s the difference between learning and decision? A: Decisions are choices with rationale. Learnings are observations or patterns. Ideas are proposals.

Q: Should I use semantic search or keyword search? A: Use explore({action: "search"}) (keyword) first. Use search({mode: "semantic"}) or search({mode: "hybrid"}) for conceptual queries if embeddings are configured.

Q: How do I handle multi-agent scenarios? A: session_init shows active agents. Use session({action: "conflict"}) before editing. Use handoffs to pass work between agents.

Q: What if I can’t complete a task? A: Create a handoff with handoff({action: "create"}) including context, pending items, and relevant learnings. Another agent can pick it up.

Q: How do I continue work from a previous session? A: Use session({action: "resume", sessionId: "..."}) to find and resume the latest session.

Q: What if I forget to end the session? A: Session persists as “active”, potentially blocking other agents. Always end sessions.

Q: How do I check workspace health? A: Call analytics({type: "health"}) for an overall health score and issue list. Good practice at session start.

Q: Can I use Mind Palace without autonomous features? A: Yes, but you miss the point. Mind Palace is designed for autonomous agent workflows.

Next Steps

  1. Run palace mcp-config --for <your-agent> --install
  2. Read the .cursorrules or globalRules in your config
  3. Start using the 3-step workflow: session → brief → context → work → end
  4. Store knowledge as you work
  5. Learn from postmortems

See API Reference for complete tool documentation.

Last updated on