Metadata-Version: 2.4
Name: smartmemory-mcp
Version: 2.0.2
Summary: Unified SmartMemory MCP server — tiered tools, local + remote backends
License: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: fastmcp<5,>=4.0
Requires-Dist: httpx>=0.27
Provides-Extra: hosted
Requires-Dist: py-key-value-aio[redis]>=0.2; extra == "hosted"
Provides-Extra: keyring
Requires-Dist: keyring>=24.0; extra == "keyring"

# smart-memory-mcp

Unified SmartMemory MCP (Model Context Protocol) server — tiered tools, local + remote backends.

mcp-name: ai.smartmemory/smartmemory-mcp

## Overview

MCP server exposing SmartMemory operations to MCP-compatible clients (Claude Desktop, Cursor, etc.). Implements the full memory toolset (add, search, recall, decisions, plans, anchors, code-index) and routes to either a local SmartMemory instance or a remote `smart-memory-service` API endpoint.

## Status

**Version:** 0.2.1

## Quick start

Use the hosted server. Nothing to install:

```bash
claude mcp add --transport http smartmemory https://mcp.smartmemory.ai/mcp
```

The first tool call opens a browser for consent. Other clients (Claude.ai, Grok, xAI API) are under [Client configuration](#client-configuration).

Run it yourself instead (pip install, stdio):

```bash
pip install smartmemory-mcp   # or, from a checkout: pip install -e .

# Run the server
smartmemory-mcp        # or python -m smartmemory_mcp
```

Tests:

```bash
pytest tests/ -v
```

## Backend: REST by default, in-process only on opt-in

The stdio and `--http` servers talk to a SmartMemory service over REST
(`SMARTMEMORY_API_URL`, `SMARTMEMORY_API_KEY`, `SMARTMEMORY_WORKSPACE_ID`; the older
`SMARTMEMORY_TEAM_ID` still works). A new session starts on the first of these that
is set: `SMARTMEMORY_WORKSPACE_ID`, then `SMARTMEMORY_TEAM_ID`, then the workspace
saved in the smartmemory config (`switch_workspace(..., save_as_default=True)`), then
your account's default workspace. The order is the same with or without the
`smartmemory` package installed, and one WARNING names both variables when they are
set to different workspaces. A live `switch_workspace` overrides all of them for the
rest of the session. Having the
`smartmemory` package importable does **not** switch them to an in-process store
any more (MCP-PERF-1): that loaded the embedding model, spaCy and the reranker into
every MCP process, 1.6-4 GB per Claude Code session.

| `SMARTMEMORY_MCP_MODE` | Backend |
|------|---------|
| unset or `remote` | REST. A service that does not answer is logged once at WARNING with its URL, and tools return a clear error; nothing falls back to an in-process store. |
| `local` | In-process store (`pip install smartmemory`), models load on first use. Also warms the transcript-search models at boot. |
| `hosted` | the multi-tenant server below |
| anything else | one WARNING, then REST |

The `smartmemory` CLI config's `mode = "local"` is not an opt-in for the MCP; it is
logged once. The transcript tools (`transcript_search` and friends) read a local
store, so they still open it in-process on first use, with a WARNING.

## Local session rule checks

`memory_get_violation_patterns(memory_dir=..., rule_type="feedback")` compiles
local `feedback_*.md` Detection patterns with core's adherence compiler. It
returns the existing record list and logs each unusable rule by name. Invalid
regexes and discarded entries produce coverage warnings. Files must be regular
files in the selected directory. `rule_type` is a literal filename prefix.
The tool is unavailable in hosted mode.

For the orient hook, set `SMARTMEMORY_RULES_DIR` to the session's local rule
directory. The hook loads the catalog once and asks the session to check each
draft. A deterministic advisory check is available with
`python -m smartmemory.adherence.session --check`, reading JSON with `response`
and `recent_user_turns` from stdin. It does not call a service or write a store.
The checker ships in core's `smartmemory.adherence.session` module.

## Hosted mode

`--hosted` serves the multi-tenant, OAuth-protected endpoint that runs at
`mcp.smartmemory.ai`. It is a different server from the stdio and `--http` modes:
every request carries its own credential, and the tool call is executed as that
caller against `smart-memory-service`. The process holds no shared API key and no
core SmartMemory instance.

Hosted search and recall ask the service to exclude speculative-derived memories
server-side, while retaining client-side tier filtering as defence in depth.

Hosted mode serves an explicit tool allowlist (`smartmemory_mcp/hosted/tools.py`).
The adherence pattern tools are not on it: `pattern_seed` reads a MEMORY.md
directory on the client's own disk, which a hosted server does not have, and
`pattern_query/get/list` and `pattern_create/update/retire` are not yet audited
for hosted. In stdio and `--http` modes all seven work, locally against your own
store or remotely through `/memory/patterns` (the seed sends file text, never a path).

```bash
SMARTMEMORY_MCP_MODE=hosted smartmemory-mcp
# or
smartmemory-mcp --hosted
```

Install with the extra, which adds the Redis-backed OAuth state store:

```bash
pip install "smartmemory-mcp[hosted]"
```

### Modes

| Mode | Command | Authentication | Tenancy |
|------|---------|----------------|---------|
| stdio | `smartmemory-mcp` | none, local process | single identity |
| http | `smartmemory-mcp --http` | none | single identity, loopback by default |
| hosted | `smartmemory-mcp --hosted` | Clerk OAuth or a SmartMemory API key | per request |

`--http` has no per-request authentication, so every caller of it acts as
whoever the process's API key belongs to. It therefore binds `127.0.0.1` and
logs a warning if asked for anything else. Set
`SMARTMEMORY_MCP_ALLOW_UNAUTH_HTTP=true` to override that deliberately. Use
`--hosted` if what you want is a server on the network.

### Environment

All of these are required in hosted mode. A missing one raises at startup,
naming the variable.

| Variable | Meaning |
|----------|---------|
| `SMARTMEMORY_API_URL` | Base URL of `smart-memory-service` |
| `MCP_PUBLIC_BASE_URL` | Public URL of this server, e.g. `https://mcp.smartmemory.ai` |
| `CLERK_DOMAIN` | Clerk instance domain |
| `CLERK_OAUTH_CLIENT_ID` | Clerk OAuth application client id |
| `CLERK_OAUTH_CLIENT_SECRET` | Clerk OAuth application client secret |
| `MCP_JWT_SIGNING_KEY` | Signs the reference tokens issued to MCP clients |
| `MCP_STATE_ENCRYPTION_KEY` | Fernet key encrypting all stored OAuth state |
| `MCP_REDIS_URL` | Redis holding OAuth state, ideally its own instance |

Optional:

| Variable | Default | Meaning |
|----------|---------|---------|
| `MCP_ALLOWED_CLIENT_REDIRECTS` | the six built-in patterns | Comma-separated client callback allowlist |
| `SMARTMEMORY_WEB_URL` | `https://www.smartmemory.ai` | Web app URL shown when an invited beta user must accept the agreement |
| `MCP_HOSTED_PORT` | `8012` | Port to bind |
| `MCP_TRUST_PROXY` | `false` | Honour `X-Forwarded-For` for rate limiting. Only true behind our own reverse proxy |

Set `MCP_JWT_SIGNING_KEY` explicitly. Left unset, the signing key is derived
from the Clerk client secret, which ties rotating that secret to invalidating
every token already issued.

### Tools

Local `code_index` indexes Python, JavaScript, TypeScript, JSX and TSX through core CodeIndexer. Standalone remote installations without core use the bundled Python parser and report a warning that TS/JS/TSX/JSX indexing and shared cross-file resolution require `pip install smartmemory-core`. A hard parse error refuses replacement and retains the prior index. Recoverable grammar partials travel with visible diagnostics. Hosted `code_upload` publishes a client-parsed bundle containing `repo`, `entities`, `relations` and optional `commit_hash` and `parse_summary`. It accepts up to 10,000 source files and 64 MiB per bundle. Destination workspace comes from the authenticated session. The hosted tool accepts no checkout path.

Code indexing reports clean, partial and failed file counts plus acceptance, staging and publication outcomes. Every hosted response derives counts from uploaded file evidence. Uncomputable evidence and missing server counts are displayed as `unknown`. Localized grammar partials with usable extraction can publish with visible spans and byte coverage. Hard collection or parse failures retain the prior index. Partial 1.x acceptance does not prove G16 complete-generation publication. Successful file extraction checkpoints are stored under `SMARTMEMORY_CODE_CHECKPOINT_DIR` (default `~/.cache/smartmemory/code-parse`) and reused when source, configuration and parser versions match. Remote code indexing preserves the server diagnostic counts and publication outcome on HTTP failures. Transport loss reports an unconfirmed server outcome.

Local `code_effects(directory, repo_name=None)` scans Python effects through the shared engine without opening a memory store. Hosted `code_effects(repo, source_snapshot, limit=20, offset=0)` reads uploaded `fa_snapshot` records in the selected workspace. It accepts no filesystem path. Upload the engine's `snapshot_record` payload through existing declared-record ingestion first. Repository rules belong in the scanned checkout's `.smartmemory-effects.json`.

Stdio advertises 41 tools in FREE, 81 in PRO and 120 in PRO+ (counts pinned by `tests/test_tier_registration.py`). PRO+ includes the conflict review queue (`review_queue_list`, `review_queue_settle`), the supersession policy (`supersession_policy_get`, `supersession_policy_set`) and who may approve reviews (`review_approval_get`, `review_approval_set`). On a local store the policy and approval tools read and set the store's own settings, and may only tighten them. By default only a person approves a review, so the assistant's settle call is refused until a person sets approval to anyone. `list_workspaces` is available in every tier.

Hosted mode advertises 35 tools, an explicit allowlist rather than a tier:

`memory_save` `memory_search` `memory_recall` `read_around` `memory_get`
`memory_explain` `memory_ask` `memory_recall_pack` `memory_policy_bundle`
`memory_update` `memory_supersede` `memory_delete` `memory_list` `memory_stats`
`memory_save_conversation` `memory_search_by_metadata` `memory_feedback`
`code_search` `code_dead_code` `code_dependencies` `code_upload` `code_effects`
`agent_set_recall_profile` `agent_get_recall_profile` `reasoning_query_traces`
`decision_create` `decision_supersede` `decision_get` `decision_list`
`decision_search` `decision_provenance` `review_queue_list` `review_queue_settle`
`whoami` `list_workspaces` `switch_workspace` `switch_team`

When a workspace asks a person first (supersession policy `propose`), `decision_supersede`
answers "held for review" with a review id and the old rule stays in force. The assistant
tells the user the change is waiting for a person and never settles it itself. A person settles it
in the review queue (`review_queue_list` shows what is waiting). `review_queue_settle` records that
person's decision (`keep_b` accepts, `keep_a` rejects); in a person-only workspace an agent's call is refused.
Sending the same change again after it was decided answers "already decided: <outcome> (review <id>)".
`memory_supersede` on a decision in such a workspace shows the refusal ("use `decision_supersede`") and writes nothing.
Hosted, both review tools act on the signed-in workspace and the service records the signed-in
caller as the one who settled. `decision_list(status=...)` reads `superseded` (replaced) and
`retracted` rules as well as the ones in force (`active`, the default).

Hosted search and decision reads accept `business_scope` and `valid_at`.
Omitting both selects the sponsor rule effective now. `scope_go_lives` on
creation or supersession schedules sponsor or exact-site activation dates.

Deprecated: `switch_team` (an alias of `switch_workspace`, removed in the next
release).

Everything else is hidden, and hidden is the default, so a tool added to a
shared module does not appear here until it is added to the allowlist. Three
kinds of tool are excluded on purpose:

- **Anything that reads or writes a filesystem path.** The container's disk is
  shared by every tenant, so `memory_export`, `memory_import`, `code_index`,
  `code_blame` and the rest are out.
- **Anything that needs a local SmartMemory instance.** Tools reaching for
  `backend._mem` or the core graph cannot work against a REST backend.
- **Destructive bulk operations**, such as `memory_clear`.

Two tools have options that cannot work here and refuse them rather than
quietly ignoring the request:

- `memory_search(cite=True)` — citation formatting lives in the `smartmemory`
  core package, which the hosted server does not ship.
- `memory_recall(session_id=…)` and `memory_recall(cite=True)` — the
  alternative recall path builds a working context through the core activation
  scorer.

`switch_workspace(workspace)` changes the workspace by id or name, with no
restart. The pick is saved server-side for you and this MCP client, so it
survives a reconnect and a server restart (SM20-WS-ROUTING-PARITY-1). It
validates membership against the API and never leaks into another user's calls. A refused switch names the workspace
still in use. Listing your workspaces needs an API key with the `read:teams`
scope (a key with only `read:memories` is told so and keeps its workspace).
`whoami` shows the user, tenant and workspace. The tenant comes from
your credential and is never a tool argument.

### Client configuration

Claude Code:

```bash
claude mcp add --transport http smartmemory https://mcp.smartmemory.ai/mcp
```

The first tool call opens a browser for consent. Claude Code registers itself
through client id metadata, so nothing needs to be created in advance.

Claude.ai custom connector: add a connector with the URL
`https://mcp.smartmemory.ai/mcp` and complete the OAuth prompt.

Grok web: add a connector with the same URL. Grok asks for a client id rather
than registering dynamically, so paste the SmartMemory MCP OAuth application
client id when prompted.

xAI API and Grok Build take a static bearer token instead of an OAuth flow, so
give them a SmartMemory API key:

```json
{
  "type": "mcp",
  "server_url": "https://mcp.smartmemory.ai/mcp",
  "authorization": "sm_live_your_key_here"
}
```

An API key skips the OAuth flow entirely and acts as its owner in that owner's
default workspace. Legacy `sk_` keys are accepted.

## Documentation

Full SmartMemory documentation: https://docs.smartmemory.ai

## Part of SmartMemory

This is one component of the SmartMemory ecosystem. See the [main repo](https://github.com/smartmemory/smart-memory) for the broader project.

## Lexical search migration

Search uses `lexical` with default weight 0.8. Replace removed `contains` and `keyword-bm25` channel weights explicitly. A zero weight disables lexical, and omission preserves the existing default/profile behavior. Required lexical unavailability fails the whole search. Service callers receive 400 for query/name validation and 503 for unavailable indexes.

Local tools, hosted search and the remote backend validate the same names. Failed search returns an MCP error result, including connection failure.

Quiesce old writers before first-open indexing. Verify the engine capability pin and use `sm rebuild --lexical` for recovery. [Migration, targets and measured limitations](https://github.com/smartmemory/smart-memory-docs/blob/main/docs/features/CORE-LEXICAL-INDEX-1/migration.md).

### Company project alongside local memory

Keep your existing local `smartmemory` connection. Add `claude mcp add --transport http smartmemory-company https://mcp.smartmemory.ai/mcp` and authenticate with your own company-org login. Check `whoami` for the expected tenant, use `switch_workspace` with the project's paired Workspace ID, then check again. Recheck after reconnect because selection is session-scoped. The owner and Kyle authenticate separately. No local-memory upload or local backend switch is needed. Hosted Team responses use `team_id`. Independent Workspace selection is outside this change. Live OAuth and two-user access acceptance remain required.

`memory_ask(question, limit=5, reasoning=True)` answers through the selected backend. Remote and hosted calls use the authenticated `/memory/ask` route with the active workspace. The published response follows `DIST-LITE-9/ask-contract.json`.

`memory_supersede` accepts `scope_go_lives` or the legacy `valid_from`. A scheduled amendment returns its accepted receipt, including `status`, `scope_go_lives` and `recorded_at`, as defined in `SM-SCOPED-VALIDITY-1/scoped-validity-contract.json`. Undated replacements retain the existing confirmation.

If an add loses its response after submission, `WriteOutcomeUnknown` means the memory may have been saved. Check `memory_search` or `memory_list` before retrying to avoid duplicates. The client does not retry the write. Recall uses the full query budget and returns full evidence content.


### Reader recall presets (SM-RECALL-PROFILES-1)

Use `recall_pack(preset="brief")` in core or `memory_recall_pack(preset="brief")`
over MCP. A reader preset selects ordered sections and a default token budget.
Pass `budget_tokens` to override the default.

| Preset | Default tokens | Sections in priority order |
|---|---:|---|
| `brief` | 2000 | constraints, active_plan, anchors, learned, tier1_user |
| `resume` | 3000 | active_plan, anchors, last_session, snapshot, constraints, learned |
| `review` | 4000 | constraints, learned, tier1_user, notes |
| `pane` | 600 | constraints, active_plan, anchors, last_session |

`preset` and explicit `sections` are mutually exclusive. Calls without a reader
preset, including `wakeup`, still require an explicit budget. The manifest names
the preset, resolved budget and section caps. Budget loss and sections unavailable
for `as_of` reads retain their WARNING logs and manifest accounting. Search agent
recall profiles continue to control memory-type weights independently.

MCP expands the four reader presets into the existing `sections` and `cap_tokens`
request fields for local, remote and hosted calls. Remote and hosted use requires
the SM-LEARNED-TOOLS-1 service dependency for learned and constraint sections.
## Human procedure tools

SM-PROCEDURE-TYPE-1 and SM-PROCEDURE-MCP-1 add six stdio tools in every tier:

- `procedure_create(name, steps, expected_outcome, description="", preconditions=None, candidate=False)`
- `procedure_list(task=None, status="active", limit=20)`
- `procedure_get(procedure_id)`
- `procedure_promote(procedure_id)`
- `procedure_dismiss(procedure_id, reason="")`
- `procedure_record_outcome(procedure_id, success, note="")`

Both local and remote stdio modes need a matching `smartmemory-core` installation containing `smartmemory.procedures.human`. These paired post-cut branches must be used together until released. Hosted exposure awaits its explicit surface audit.

Procedures are structured human runbooks with ordered steps, preconditions and expected outcomes. Create active runbooks or candidates, explicitly promote candidates and dismiss obsolete procedures. Task filtering matches active runbooks by token overlap. Recorded successes reinforce confidence and failures weaken it, with the latest 20 outcomes returned. These candidate IDs name saved human runbooks. Ingestion recipe cluster IDs belong to the existing REST recipe workflow.

The backend supplies workspace authority. The tools accept no workspace, tenant or user override. Remote mode reuses existing scoped REST CRUD with direct add, preserving the procedure body. No steps are executed by these tools.
