Skip to content

Direct API vs MCP Tools

The AutoMem system is accessible through two interfaces: the HTTP API (direct REST calls to the AutoMem server) and the MCP tools (JSON-RPC calls through the mcp-automem bridge). Both interfaces reach the same backend but differ in transport, parameter style, and what they expose to callers.

For the HTTP API reference, see Memory Operations, Recall Operations, and related pages. For MCP setup, see MCP Integration.


graph LR
    subgraph mcp["MCP JSON-RPC Tools"]
        StoreMemory["store_memory"]
        RecallMemory["recall_memory"]
        AssociateMemories["associate_memories"]
        UpdateMemory["update_memory"]
        DeleteMemory["delete_memory"]
        CheckHealth["check_database_health"]
    end

    subgraph client["AutoMemClient Methods"]
        StoreMethod["storeMemory(args)"]
        RecallMethod["recallMemory(args)"]
        AssociateMethod["associateMemories(args)"]
        UpdateMethod["updateMemory(args)"]
        DeleteMethod["deleteMemory(args)"]
        HealthMethod["checkHealth()"]
    end

    subgraph api["AutoMem HTTP API"]
        PostMemory["POST /memory"]
        GetRecall["GET /recall"]
        PostAssociate["POST /associate"]
        PatchMemory["PATCH /memory/:id"]
        DeleteMemoryEndpoint["DELETE /memory/:id"]
        GetHealth["GET /health"]
    end

    StoreMemory --> StoreMethod
    RecallMemory --> RecallMethod
    AssociateMemories --> AssociateMethod
    UpdateMemory --> UpdateMethod
    DeleteMemory --> DeleteMethod
    CheckHealth --> HealthMethod

    StoreMethod -->|"JSON body"| PostMemory
    RecallMethod -->|"Query params"| GetRecall
    AssociateMethod -->|"JSON body"| PostAssociate
    UpdateMethod -->|"JSON body"| PatchMemory
    DeleteMethod -->|"URL param"| DeleteMemoryEndpoint
    HealthMethod -->|"No params"| GetHealth

The MCP bridge (mcp-automem) operates as a thin translation layer. Each MCP tool call is mapped to an AutoMemClient method, which in turn makes an HTTP request to the AutoMem server. The bridge keeps no storage or ranking logic of its own — it handles parameter mapping, argument validation, the client-side supersede flow, and response formatting.


The mcp-automem package (src/index.ts) serves two purposes from a single entry point:

  1. Server Mode: When launched without arguments, it becomes an MCP server communicating over stdio
  2. CLI Mode: When launched with commands (setup, cursor, recall, etc.), it executes utility functions and exits

Mode detection occurs immediately at startup:

// src/index.ts lines 30-31
const command = (process.argv[2] || '').toLowerCase();
const isServerMode = command.length === 0;

In server mode the entry point goes on to rebind the console and start the stdio server. In CLI mode it runs the matching command handler and exits; an unrecognized command prints an error and exits with code 1 (src/index.ts lines 407-411).

This allows a single npm package to serve as both an interactive MCP server for AI platforms and a command-line toolkit for configuration management.

In server mode, all MCP communication occurs over stdin/stdout using the StdioServerTransport from @modelcontextprotocol/sdk. console.log, console.info, console.debug, and console.warn are rebound to console.error, which writes to stderr, to keep logging off the JSON-RPC channel:

// src/index.ts lines 78-84 (server mode only)
if (isServerMode) {
const logToStderr = (...args: unknown[]) => console.error(...args);
console.log = logToStderr;
console.info = logToStderr;
console.debug = logToStderr;
console.warn = logToStderr;
}
StageLinesDescription
Entry1–28Shebang, imports, isInteractiveTerminal() helper
Mode Detection30–84Determine server vs CLI mode, decide whether to silence the dotenv banner, and redirect logging in server mode
Startup Helpers86–125Load .env, set the optional process title, define installStdioErrorGuards(), read the package version
CLI Routing127–411Print help, execute CLI commands and exit, reject unknown commands
Configuration413–433Resolve the API URL and key, create AutoMemClient
Server Setup435–439Build the server with createAutoMemMcpServer() (tools and handlers live in src/mcp-surface.ts)
Main Loop441–496main(): install stdio guards, create StdioServerTransport, register shutdown triggers, connect

The server guards against two classes of failures:

Broken pipe errors — When the AI platform terminates the connection unexpectedly:

// src/index.ts lines 102-112
function installStdioErrorGuards() {
const handler = (error: unknown) => {
const err = error as { code?: string } | undefined;
if (err?.code === 'EPIPE' || err?.code === 'ECONNRESET') {
process.exit(0);
}
};
process.stdout.on('error', handler);
process.stderr.on('error', handler);
}

Tool execution errors — All tool handlers are wrapped in try-catch (src/mcp-surface.ts lines 1041-1320), returning MCP error responses rather than crashing the server.


graph TB
    subgraph tools["MCP Tools (createAutoMemMcpServer)"]
        direction TB

        T1["store_memory<br/>One of: content (single)<br/>or memories[] (batch)<br/>Optional: tags, importance,<br/>embedding, metadata, timestamps,<br/>supersede fields"]
        T2["recall_memory<br/>Modes: memory_id (fetch),<br/>tags + exhaustive (enumerate),<br/>or ranked retrieval<br/>Optional: query, queries,<br/>embedding, limit, sort,<br/>time filters, tags,<br/>expand options, context hints"]
        T3["associate_memories<br/>Pair: memory1_id, memory2_id,<br/>type, strength<br/>or associations[] (batch)"]
        T4["update_memory<br/>Required: memory_id<br/>Optional: content, tags,<br/>importance, metadata, timestamps"]
        T5["delete_memory<br/>One of: memory_id or tags"]
        T6["check_database_health<br/>No parameters"]
    end

    subgraph schemas["Input Schemas"]
        S1["type: object<br/>properties: {content, memories[],<br/>tags[], importance, embedding[], ...}<br/>no top-level required"]
        S2["type: object<br/>properties: {memory_id, exhaustive,<br/>query, queries[], embedding[],<br/>limit, offset, sort, format,<br/>expand_relations, expand_entities,<br/>context, language, ...}<br/>no top-level required"]
        S3["type: object<br/>properties: {memory1_id,<br/>memory2_id, type, strength,<br/>associations[], edge props}<br/>no top-level required"]
        S4["type: object<br/>properties: {memory_id,<br/>content, tags[], importance, ...}<br/>required: ['memory_id']"]
        S5["type: object<br/>properties: {memory_id, tags[]}<br/>no top-level required"]
        S6["type: object<br/>properties: {}"]
    end

    T1 --- S1
    T2 --- S2
    T3 --- S3
    T4 --- S4
    T5 --- S5
    T6 --- S6
Tool NameHTTP EquivalentRead-OnlyDestructiveIdempotent
store_memoryPOST /memory (batch mode: POST /memory/batch)NoNoNo
recall_memoryGET /recall (ID fetch: GET /memory/:id; tag enumeration: GET /memory/by-tag)YesNoYes
associate_memoriesPOST /associate (pair and batch modes)NoNoYes
update_memoryPATCH /memory/:idNoNoYes
delete_memoryDELETE /memory/:id (bulk by tag: DELETE /memory/by-tag)NoYesNo
check_database_healthGET /healthYesNoYes

MCP tool annotations provide semantic hints to AI platforms about tool behavior:

AnnotationTypeMeaningApplied To
readOnlyHintbooleanTool only reads datarecall_memory, check_database_health
destructiveHintbooleanTool may perform destructive updates (only meaningful when readOnlyHint is false)delete_memory only
idempotentHintbooleanRepeated calls with the same arguments have no additional effect on the environment (only meaningful when readOnlyHint is false)All except store_memory and delete_memory
openWorldHintbooleanTool may interact with an open world of external entities, such as web search (a memory tool’s domain is closed)false for all tools

MCP Tool Input Schema:

store_memory is mode-multiplexed: pass top-level content for a single memory (add supersedes_memory_id to replace an existing one), or memories: [...] for a batch. The input schema has no top-level required array, but the MCP client throws if you send neither content nor memories.

ParameterTypeRequiredConstraintsDescription
contentstringSingle mode (XOR memories)Runtime: ≤2000 charsMemory content to store
memoriesarray[object]Batch mode (XOR content)1–500 items; each item requires non-empty contentMemories to store in one request. Per-item fields: tags, importance, timestamp, type, confidence, metadata
tagsarray[string]No—Categorization tags
importancenumberNo0–1Significance score
embeddingarray[number]NoSingle mode onlyOptional pre-computed vector
metadataobjectNo—Structured additional data
timestampstringNoISO formatCreation timestamp
typestringNoenum: Decision, Pattern, Preference, Style, Habit, Insight, ContextMemory type classification
confidencenumberNo0–1Classification confidence (defaults to 0.9 when type is set)
t_valid, t_invalidstringNoISO 8601, single mode onlyValidity window
updated_at, last_accessedstringNoISO 8601, single mode onlyExplicit timestamps
supersedes_memory_idstringNoSingle mode onlyExisting memory this one replaces or corrects
supersede_relationstringNoINVALIDATED_BY (default) | EVOLVED_INTORelation created from the old memory to the new one
supersede_reasonstringNo—Reason stored on the old memory’s metadata

In batch mode, put tags, importance, and the other per-item fields inside each memories entry. The client rejects any top-level single-mode field sent alongside memories, and it rejects per-item id, embedding, t_valid, and t_invalid.

MCP Tool Output:

Only message is a required output field. The rest depend on which mode ran.

FieldTypeRequiredDescription
messagestringYesConfirmation message
memory_idstringNoSingle and supersede modes: ID of the stored memory
memory_idsarray[string]NoBatch mode: IDs of the stored memories
storedintegerNoBatch mode: number of memories stored
qdrant, enrichmentstringNoBatch mode: indexing and enrichment status reported by the server
query_time_msnumberNoBatch mode: server-reported execution time
superseded_memory_idstringNoSupersede mode: ID of the memory marked invalid
association_createdbooleanNoSupersede mode: whether the old → new association was created

HTTP API equivalent:

Terminal window
curl -X POST https://your-automem-instance/memory \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"content": "User prefers TypeScript for new projects",
"tags": ["preference", "language:typescript"],
"importance": 0.85
}'

Content Size Governance (single mode; the MCP layer adds two-tier validation):

LimitValueBehavior
Target150–300 charsOptimal embedding quality
Soft limit500 charsWarning; backend may auto-summarize
Hard limit2000 charsMCP layer rejects before sending to API

In batch mode the client only checks that each item’s content is non-empty. The AutoMem service enforces its own content limits.


MCP Tool Input Schema:

recall_memory picks one of three modes from the arguments you pass: memory_id fetches a single record, tags with exhaustive: true enumerates a tag exactly, and anything else is ranked hybrid retrieval. The input schema has no top-level required array.

ParameterTypeRequiredConstraintsDescription
memory_idstringNo—ID-fetch mode: returns that one memory. No other parameter is sent to the server, but format still shapes the response. An ID that does not exist returns count: 0 with empty results
exhaustivebooleanNoRequires non-empty tags; rejects tag_match: "prefix", tag_mode: "all", and ranked-only options such as query or sortTag-enumeration mode: paginated exact-match listing, not ranked retrieval
querystringNo—Semantic search query
queriesarray[string]No—Multiple queries for broader recall
embeddingarray[number]No—Optional embedding vector for direct similarity search
limitintegerNo1–200 (schema default 5)Max results to return. Ranked mode defaults to 5; enumeration without limit uses the server default of 20. Enumeration mode honors up to 200; in ranked mode the server enforces its own cap (default 100 via RECALL_MAX_LIMIT)
offsetintegerNo≥ 0Pagination offset (enumeration mode only; rejected with a validation error in ranked mode — raise limit instead)
tagsarray[string]No—Filter by tags
tag_modestringNo"any" | "all"Tag matching mode
tag_matchstringNo"exact" | "prefix"Tag matching strategy
time_querystringNo—Natural language time filter
startstringNoISO timestampTime range start
endstringNoISO timestampTime range end
expand_entitiesbooleanNo—Enable multi-hop entity expansion
expand_relationsbooleanNo—Follow graph relationships
expansion_limitintegerNo1–500, default 25Max expanded results
relation_limitintegerNo1–200, default 5Relations per seed memory
expand_min_importancenumberNo0–1Filter expanded results by importance
expand_min_strengthnumberNo0–1Min relation strength to traverse
expand_respect_tagsbooleanNo—Restrict graph expansion to the active tag scope
contextstringNo—Context label for boosting
languagestringNo—Programming language hint

MCP Tool Output:

FieldTypeRequiredDescription
countintegerYesNumber of memories returned
resultsarray[object]YesArray of memory objects with scores
dedup_removedintegerNoDuplicates removed in multi-query mode
modestringNoMode that produced the result: "ranked", "enumeration", or "id_fetch"
has_morebooleanNoEnumeration mode: whether more pages exist past offset + limit
limit, offsetintegerNoEnumeration mode: page size and offset used for this response

Response shaping and backend-owned recall:

The MCP bridge forwards recall arguments to the AutoMem backend and then formats the response for MCP clients. Hybrid scoring, tag filtering, deduplication, entity expansion, and priority_ids guarantees all live in AutoMem itself, so HTTP and MCP produce the same recall behavior when you pass the same arguments.

MCP response budgeting (v0.15+; content previews since v0.16): Budgeted formats (text, items, detailed) trim each memory to stay under MCP client tool-response caps (~25k tokens in Claude Code). Content longer than 400 characters is cut to a 400-character preview and flagged with content_truncated and content_chars (the full length). A server-generated summary is kept as an additional field; it only stands in for the preview in the text channel when content is empty. In detailed, relations collapse to compact stubs (max 3 per memory) and metadata collapses to its key list; text and items structured results leave both out. The default token budget is 18,000 estimated tokens (override with AUTOMEM_RECALL_TOKEN_BUDGET). format: "json" keeps raw per-field passthrough but the global budget still applies. ID fetches via memory_id are never truncated — use that mode to retrieve a full record.

HTTP API equivalent:

Terminal window
curl "https://your-automem-instance/recall?query=typescript+preferences&tags=preference&limit=10" \
-H "Authorization: Bearer YOUR_API_TOKEN"

MCP Tool Input Schema:

Like store_memory, this tool has a single-pair mode and a batch mode. The input schema has no top-level required array, so the pair-mode fields below are required by the MCP client at runtime rather than by the schema.

ParameterTypeRequiredConstraintsDescription
memory1_idstringPair mode—Source memory UUID
memory2_idstringPair mode—Target memory UUID
typestringPair modeenum: 11 authorable typesRelationship type
strengthnumberPair mode0–1Relationship strength. The MCP client throws if it is missing; the HTTP API defaults to 0.5 when you omit it
associationsarray[object]Batch mode1–500 items; each item requires memory1_id, memory2_id, type, and strengthBatch of associations. Do not combine with the pair-mode fields
context, reason, pattern_type, confidence, resolution, observations, timestamp, transformation, role—NoEach applies to specific relationship typesRelation-specific properties. Accepted at the top level in pair mode and inside each batch item

Relationship type enum values (11 authorable):

  1. RELATES_TO — General relationship
  2. LEADS_TO — Causal relationship
  3. OCCURRED_BEFORE — Temporal ordering
  4. PREFERS_OVER — Chosen alternative
  5. EXEMPLIFIES — Concrete example of a pattern
  6. CONTRADICTS — Conflicts with
  7. REINFORCES — Strengthens validity
  8. INVALIDATED_BY — Superseded by
  9. EVOLVED_INTO — Updated version
  10. DERIVED_FROM — Implementation of a decision
  11. PART_OF — Component of a larger effort

System-generated relations may still appear in recall results, but they are not valid inputs to associate_memories: SIMILAR_TO, PRECEDED_BY, and DISCOVERED. The tool description also lists EXPLAINS, SHARES_THEME, and PARALLEL_CONTEXT as non-inputs; the server normalizes those three legacy names to DISCOVERED with a matching kind when it returns relations.

MCP Tool Output:

FieldTypeRequiredDescription
successbooleanYesWhether every requested association was created; false for partial batch results
messagestringYesConfirmation message (batch mode: the service summary)
created_count, failed_countintegerNoBatch mode: number of associations created and failed
succeeded, failedarray[object]NoBatch mode: per-association records
summarystringNoBatch mode: service summary

HTTP API equivalent:

Terminal window
curl -X POST https://your-automem-instance/associate \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"memory1_id": "a1b2c3d4-...",
"memory2_id": "b2c3d4e5-...",
"type": "INVALIDATED_BY",
"strength": 0.95
}'

Batch mode sends {"associations": [...]} to the same POST /associate endpoint.


MCP Tool Input Schema:

ParameterTypeRequiredConstraintsDescription
memory_idstringYes—ID of memory to update
contentstringNo—New content (replaces existing)
tagsarray[string]No—New tags (replaces existing)
importancenumberNo0–1New importance score
metadataobjectNo—Metadata (replaces existing)
timestampstringNoISO formatOverride creation timestamp
t_valid, t_invalidstringNoISO 8601Validity window: when the memory becomes valid, and when it expires or was superseded
updated_atstringNoISO formatExplicit update timestamp
last_accessedstringNoISO formatLast access timestamp
typestringNoenum: Decision, Pattern, Preference, Style, Habit, Insight, ContextMemory type classification
confidencenumberNo0–1Confidence score

MCP Tool Output:

FieldTypeRequiredDescription
memory_idstringYesID of updated memory
messagestringYesConfirmation message

HTTP API equivalent:

Terminal window
curl -X PATCH https://your-automem-instance/memory/a1b2c3d4-... \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"importance": 0.95, "tags": ["preference", "language:typescript", "reviewed"]}'

MCP Tool Input Schema:

ParameterTypeRequiredDescription
memory_idstringNoID of memory to delete (XOR with tags)
tagsarray[string]NoBulk-delete all memories matching any tag (XOR with memory_id)

Exactly one of memory_id or tags must be provided.

MCP Tool Output:

Only message is a required output field. memory_id is absent in bulk-by-tag mode.

FieldTypeRequiredDescription
messagestringYesConfirmation message
memory_idstringNoSingle-delete mode: ID of the deleted memory
deleted_countintegerNoBulk-by-tag mode: number of memories deleted
tagsarray[string]NoBulk-by-tag mode: tags used for the bulk delete

HTTP API equivalent:

Terminal window
curl -X DELETE https://your-automem-instance/memory/a1b2c3d4-... \
-H "Authorization: Bearer YOUR_API_TOKEN"

Bulk-by-tag mode calls DELETE /memory/by-tag?tags=... instead.


MCP Tool Input Schema: Empty object — no parameters required.

MCP Tool Output:

FieldTypeRequiredDescription
statusstringYes"healthy", "degraded" (the service is reachable but a backend or sync check needs attention), or "error"
backendstringYesBackend type (always "automem")
statisticsobjectNoDatabase statistics (memory counts, etc.)
errorstringNoError message if status is "error"

Difference from GET /health: check_database_health calls GET /health and repackages the response rather than trimming it. The service fields (falkordb, qdrant, graph, memory_count, vector_count, sync_status, vector_dimensions, enrichment with its queue counters, and timestamp) move under statistics, and backend is added. Any status other than healthy or degraded becomes error, and a failed request returns status: "error" with the error message and an empty statistics object. The text block is a summary that leaves out the enrichment queue counters and vector dimensions. Call /health directly for monitoring dashboards that poll without an MCP client.

HTTP API equivalent:

Terminal window
curl https://your-automem-instance/health

MCP tool handlers return dual-representation responses conforming to the MCP protocol:

  1. content array — Human-readable text (type: "text") for display in chat interfaces
  2. structuredContent object — Machine-readable data matching the tool’s outputSchema

Example from store_memory in single mode (abridged from src/mcp-surface.ts lines 1112-1161):

let responseText = `Memory stored successfully!\n\nMemory ID: ${result.memory_id}`;
// ...supersede, message, auto-summarize, and size-warning lines are appended when present
const output = {
memory_id: result.memory_id,
message: result.message,
// ...supersede, auto-summarize (summarized, original_length, summarized_length),
// and size-warning fields when present
};
return {
content: [{ type: 'text', text: responseText }],
structuredContent: output,
};

This dual format ensures:

  • AI platforms can parse structured data programmatically via structuredContent
  • Users viewing responses in chat see clean, formatted text via content
  • Tools remain compatible with both chat interfaces and API clients

ScenarioUse HTTP APIUse MCP Tools
AI agent integration (Claude, Cursor, etc.)—Preferred — native JSON-RPC
Custom application or scriptPreferred — direct control—
Bulk operations (migration, reprocessing)Preferred — no overhead—
Content size validation before storage—Built-in two-tier limits (single mode)
Structured tool output for chat clientsManual formattingBuilt-in content + structuredContent
Admin operations (reembed, reprocess)Preferred — admin endpointsNot available
Health monitoring dashboardsPreferred — full responseSame fields under statistics; the text block is a summary
Process supervision (stable process title)—Supported via the AUTOMEM_PROCESS_TAG (or MCP_PROCESS_TAG) env var

The mcp-automem server registers tools via the MCP SDK’s schema-based routing. Tool definitions and request handlers live in src/mcp-surface.ts; src/index.ts only builds the server from them through createAutoMemMcpServer().

ListToolsRequestSchema handler (src/mcp-surface.ts line 1034): Returns the complete tools array when AI platforms query available tools via MCP introspection, so platforms can discover what tools are available.

CallToolRequestSchema handler (src/mcp-surface.ts lines 1038-1321): Executes tool logic based on the name parameter using a switch-based dispatcher, then delegates to the corresponding AutoMemClient method.

The tools array (src/mcp-surface.ts lines 85-1007) contains six static tool definitions with extensive inline documentation in the description field. This documentation is directly visible to AI platforms via MCP introspection, informing the model when and how to invoke each tool.