Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions INSTALL_FOR_AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Default keyless mode needs no API key or cloud account and disables vector embed

- Node.js >= 20 with npm and npx. Check with `node -v`, `npm -v`, and `npx -v`.
- macOS/Linux automatic iii installation also requires `curl`, a POSIX `sh`, and `tar`. Check with `command -v curl sh tar`. Minimal images such as `node:20-slim` may not include them.
- Windows: WSL2 follows the Linux path. Native Windows installs the pinned iii-engine v0.25.1 ZIP automatically. Native automated `connect` supports only `copilot-cli`; configure other Windows agents manually. WSL `connect` applies only to agents installed in that same WSL environment.
- Windows: WSL2 follows the Linux path. Native Windows installs the pinned iii-engine v0.25.1 ZIP automatically. Native `connect` works for every adapter. WSL `connect` applies only to agents installed in that same WSL environment.
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
- Default ports 3111 (REST), 3113 (viewer), and 49134 (engine) must be free. Viewer events are carried over REST.

## Running non-interactively
Expand Down Expand Up @@ -100,7 +100,7 @@ The first embedding request downloads `Xenova/all-MiniLM-L6-v2`; wait for that d

## 5. Wire MCP into the calling agent

Detect which agent is running this runbook, then wire its MCP config. On native Windows, run this automated step only for `copilot-cli`:
Detect which agent is running this runbook, then wire its MCP config:

```bash
npx -y @agentmemory/agentmemory@latest connect <agent>
Expand All @@ -110,7 +110,7 @@ Supported agent names:

`claude-code`, `copilot-cli`, `codex`, `cursor`, `gemini-cli`, `opencode`, `cline`, `continue`, `droid`, `hermes`, `openclaw`, `openhuman`, `pi`, `omp`, `qwen`, `warp`, `zed`, `antigravity`, `kiro`.

If you cannot tell which agent you are, default to `claude-code` on macOS/Linux. On native Windows, `copilot-cli` is the only automated adapter; configure all other agents with the manual MCP block in the README. Run `connect` inside WSL only when the target agent is installed inside the same WSL environment. After wiring, restart the agent or run its MCP reload command (for example `/mcp` in Claude Code) so it picks up the server.
If you cannot tell which agent you are, default to `claude-code` on macOS/Linux. Run `connect` inside WSL only when the target agent is installed inside the same WSL environment. After wiring, restart the agent or run its MCP reload command (for example `/mcp` in Claude Code) so it picks up the server.

Expect: the agent now lists agentmemory's tools. With the server running you should see the full set of 54 tools (for example `memory_save`, `memory_smart_search`, `memory_sessions`). If you see only 7 tools, the MCP shim could not reach the server; see Troubleshooting.

Expand Down Expand Up @@ -216,7 +216,7 @@ The MCP server exposes 54 tools by default (`--tools all`). Use `--tools core` (
- `The engine process started but the REST API never responded.`: inspect the REST, viewer, and engine ports, confirm the pinned iii process stayed alive, and use `--verbose` for captured engine stderr.
- Engine version conflict / another iii engine already running: if an unmanaged engine is already listening on the engine port, agentmemory will not adopt it. Stop that engine or choose another `--instance` or `--port`. The CLI keeps its private pinned binary separate from a user-managed `iii` on `PATH`.
- Only 7 tools visible in the agent: the MCP shim is in local fallback because it could not reach a server. Start `npx -y @agentmemory/agentmemory@latest`, ensure `AGENTMEMORY_URL` points at it (default `http://localhost:3111`), then reload MCP.
- Native Windows: if the automatic engine install fails, install the pinned v0.25.1 `iii.exe` manually or use WSL2. Automated `connect` supports only `copilot-cli`; configure other native agents manually.
- Native Windows: if the automatic engine install fails, install the pinned v0.25.1 `iii.exe` manually or use WSL2.
- Semantic demo query returns zero hits: this is expected with vectors disabled in default keyless mode. Set `EMBEDDING_PROVIDER=local`, restart, allow the first model download to complete, and rerun the demo.

## Report success
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ agentmemory connect copilot-cli
copilot plugin install rohitg00/agentmemory:plugin
```

`agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` (or `$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set) and preserves existing servers. On native Windows this is the only automated `connect` adapter; configure every other native Windows agent manually. WSL `connect` is supported only when the target agent is installed in that same WSL environment. Copilot picks up the MCP server on next launch or after `/mcp`. Install the plugin as well when you want the full hook/skill experience.
`agentmemory connect copilot-cli` merges `mcpServers.agentmemory` into `~/.copilot/mcp-config.json` (or `$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set) and preserves existing servers. WSL `connect` is supported only when the target agent is installed in that same WSL environment. Copilot picks up the MCP server on next launch or after `/mcp`. Install the plugin as well when you want the full hook/skill experience.

### Cursor

Expand Down Expand Up @@ -690,7 +690,7 @@ npm install && npm run build && npm start

agentmemory runs on Windows 10/11. WSL2 follows the Linux path and can install the pinned engine automatically. Native Windows also installs the pinned iii-engine v0.25.1 automatically: the CLI downloads the Windows ZIP, verifies its SHA-256 and extracts `iii.exe` into `%USERPROFILE%\.agentmemory\bin`. If that fails, download the matching archive from the [iii v0.25.1 release page](https://github.com/iii-hq/iii/releases/tag/iii%2Fv0.25.1), verify its checksum, and extract `iii.exe` into the same directory.

Native Windows automated MCP wiring supports only `agentmemory connect copilot-cli`. For other native Windows agents, use the manual MCP block from [Other agents](#other-agents). Run `connect` inside WSL only when the target agent is installed in that same WSL environment.
`agentmemory connect <agent>` works on native Windows. It writes the MCP server as `cmd /c npx -y @agentmemory/mcp`, because Windows cannot start `npx` without a shell, and it writes hook script paths as absolute paths with forward slashes, either quoted or passed as a separate argument, so a home folder with spaces is safe. Antigravity hooks cannot use quoted paths. When the install path has spaces, `connect antigravity --with-hooks` uses the Windows short (8.3) path. If the short path is not available, it prints the hook JSON to paste by hand, and the MCP wiring still applies. Run `connect` inside WSL only when the target agent is installed in that same WSL environment.

**Standalone MCP only (no engine).** If you only need MCP tools and do not need the REST API, viewer, or runtime services:

Expand Down
65 changes: 59 additions & 6 deletions src/cli/connect/antigravity-cli.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
Expand Down Expand Up @@ -44,7 +45,59 @@ export const adapter = createJsonMcpAdapter({
* Merge the bundled `plugin/hooks/hooks.antigravity.json` into
* `~/.gemini/config/hooks.json`, replacing only the bundle agentmemory owns.
*/
export function installAntigravityCliHooks(opts: ConnectOptions): ConnectResult {
export function windowsShortPath(path: string): string | null {
try {
const out = execFileSync(
"powershell.exe",
[
"-NoProfile",
"-NonInteractive",
"-Command",
"(New-Object -ComObject Scripting.FileSystemObject).GetFolder($env:AGENTMEMORY_LONG_PATH__).ShortPath",
],
{
env: { ...process.env, AGENTMEMORY_LONG_PATH__: path },
encoding: "utf-8",
stdio: ["ignore", "pipe", "ignore"],
timeout: 15_000,
windowsHide: true,
},
).trim();
return out || null;
} catch {
return null;
}
}

export function resolveHookCommandRoot(
pluginRoot: string,
shortPath: (path: string) => string | null = windowsShortPath,
): string | null {
if (!containsSpaces(pluginRoot)) return pluginRoot;
if (process.platform !== "win32") return null;
const short = shortPath(pluginRoot);
return short && !containsSpaces(short) ? short : null;
}

function printManualHooks(pluginRoot: string): void {
const target =
process.platform === "win32" ? "C:/agentmemory/plugin" : "/opt/agentmemory/plugin";
const manual = buildMergedAntigravityHooks(null, pluginRoot, undefined, target);
p.log.message(
[
"Manual hook setup for Antigravity:",
` 1. Copy ${pluginRoot} to ${target} (any path without spaces works).`,
` 2. Merge this into ${ANTIGRAVITY_CLI_HOOKS}:`,
"",
JSON.stringify(manual, null, 2),
].join("\n"),
);
}

export function installAntigravityCliHooks(
opts: ConnectOptions,
shortPath: (path: string) => string | null = windowsShortPath,
): ConnectResult {
let pluginRoot: string;
try {
pluginRoot = findPluginRoot();
Expand All @@ -55,17 +108,17 @@ export function installAntigravityCliHooks(opts: ConnectOptions): ConnectResult
};
}

// agy honours no quoting, so a space in the path yields hooks that load
// but never run. Refuse rather than install something that can only fail.
if (containsSpaces(pluginRoot)) {
const commandRoot = resolveHookCommandRoot(pluginRoot, shortPath);
if (commandRoot === null) {
printManualHooks(pluginRoot);
return {
kind: "skipped",
reason: `Antigravity CLI cannot run hook commands whose path contains spaces, and agentmemory is installed at ${pluginRoot}. Reinstall it under a space-free path to use --with-hooks; MCP works either way.`,
reason: `Antigravity cannot run hook commands whose path contains spaces, and agentmemory is installed at ${pluginRoot}. Follow the manual hook steps above; MCP works either way`,
};
}

const existing = readJsonSafe<AntigravityHookManifest>(ANTIGRAVITY_CLI_HOOKS);
const merged = buildMergedAntigravityHooks(existing, pluginRoot);
const merged = buildMergedAntigravityHooks(existing, pluginRoot, undefined, commandRoot);

if (opts.dryRun) {
p.log.info(
Expand Down
6 changes: 4 additions & 2 deletions src/cli/connect/antigravity-hooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { toCommandPath } from "./util.js";

/**
* Merge engine for Antigravity CLI's `hooks.json`.
Expand Down Expand Up @@ -62,11 +63,12 @@ export function buildMergedAntigravityHooks(
existing: AntigravityHookManifest | null,
pluginRoot: string,
manifestFile = "hooks.antigravity.json",
commandRoot = pluginRoot,
): AntigravityHookManifest {
const ours = JSON.parse(
readFileSync(join(pluginRoot, "hooks", manifestFile), "utf-8"),
) as AntigravityHookManifest;
const scriptsDir = join(pluginRoot, "scripts");
const scriptsDir = join(commandRoot, "scripts");

const out: AntigravityHookManifest = {};

Expand All @@ -76,7 +78,7 @@ export function buildMergedAntigravityHooks(
}

for (const [name, bundle] of Object.entries(ours)) {
out[name] = resolveBundle(bundle, pluginRoot);
out[name] = resolveBundle(bundle, toCommandPath(commandRoot));
}

return out;
Expand Down
15 changes: 11 additions & 4 deletions src/cli/connect/antigravity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@ import { join } from "node:path";
import { createJsonMcpAdapter } from "./json-mcp-adapter.js";
import { installAntigravityCliHooks } from "./antigravity-cli.js";

const LEGACY_USER_DIR =
platform() === "darwin"
? join(homedir(), "Library", "Application Support", "Antigravity", "User")
: join(homedir(), ".config", "Antigravity", "User");
function legacyUserDir(): string {
if (platform() === "darwin") {
return join(homedir(), "Library", "Application Support", "Antigravity", "User");
}
if (platform() === "win32") {
return join(process.env["APPDATA"] || join(homedir(), "AppData", "Roaming"), "Antigravity", "User");
}
return join(homedir(), ".config", "Antigravity", "User");
}

const LEGACY_USER_DIR = legacyUserDir();

const CUSTOMIZATION_DIR = join(homedir(), ".gemini", "config");
const mcpAdapter = createJsonMcpAdapter({
Expand Down
9 changes: 2 additions & 7 deletions src/cli/connect/claude-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js";
import {
AGENTMEMORY_MCP_BLOCK,
backupFile,
isAgentmemoryMcpEntry,
logAlreadyWired,
logBackup,
logInstalled,
Expand Down Expand Up @@ -38,13 +39,7 @@ type ClaudeConfig = {
[key: string]: unknown;
};

function entryMatches(entry: unknown): boolean {
if (!entry || typeof entry !== "object") return false;
const e = entry as Record<string, unknown>;
if (e["command"] !== "npx") return false;
const args = Array.isArray(e["args"]) ? (e["args"] as string[]) : [];
return args.includes("@agentmemory/mcp");
}
const entryMatches = isAgentmemoryMcpEntry;

export const adapter: ConnectAdapter = {
name: "claude-code",
Expand Down
3 changes: 2 additions & 1 deletion src/cli/connect/codex-hooks.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { toCommandPath } from "./util.js";

type HookHandler = { type: string; command?: string; args?: string[]; [key: string]: unknown };
type HookEntry = { matcher?: string; hooks: HookHandler[] };
Expand Down Expand Up @@ -86,7 +87,7 @@ export function buildMergedHooks(
}

function withPluginRoot(value: string | undefined, pluginRoot: string): string | undefined {
return value?.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => pluginRoot);
return value?.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, () => toCommandPath(pluginRoot));
}

function isAgentmemoryHandler(handler: HookHandler, scriptsDir: string): boolean {
Expand Down
111 changes: 104 additions & 7 deletions src/cli/connect/codex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { join, dirname } from "node:path";
import * as p from "@clack/prompts";
import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js";
import {
AGENTMEMORY_MCP_BLOCK,
backupFile,
isLegacyMcpCommand,
logAlreadyWired,
logBackup,
logInstalled,
Expand All @@ -22,8 +24,8 @@ const CODEX_TOML = join(CODEX_DIR, "config.toml");
const CODEX_HOOKS = join(CODEX_DIR, "hooks.json");

const TOML_BLOCK = `[mcp_servers.agentmemory]
command = "npx"
args = ["-y", "@agentmemory/mcp"]
command = ${JSON.stringify(AGENTMEMORY_MCP_BLOCK.command)}
args = [${AGENTMEMORY_MCP_BLOCK.args.map((arg) => JSON.stringify(arg)).join(", ")}]

[mcp_servers.agentmemory.env]
AGENTMEMORY_URL = "http://localhost:3111"
Expand All @@ -35,6 +37,90 @@ function isWiredText(toml: string): boolean {
return toml.includes(SECTION_HEADER);
}

const COMMAND_LINE = /^([ \t]*command[ \t]*=[ \t]*)(["'])(.*?)\2(?=[ \t]*(?:#.*)?$)/m;
const ARGS_KEY = /^[ \t]*args[ \t]*=[ \t]*(?=\[)/m;

function sectionBounds(toml: string): { start: number; end: number } | null {
const header = toml.indexOf(SECTION_HEADER);
if (header < 0) return null;
const start = header + SECTION_HEADER.length;
const end = toml.slice(start).search(/^\s*\[/m);
return { start, end: end < 0 ? toml.length : start + end };
}

function decodeBasicString(literal: string): string {
try {
return JSON.parse(literal) as string;
} catch {
return literal.slice(1, -1);
}
}

function findArgs(section: string): { open: number; end: number; items: string[] } | null {
const key = section.match(ARGS_KEY);
if (!key || key.index === undefined) return null;
const open = key.index + key[0].length;
const items: string[] = [];
let depth = 0;
for (let i = open; i < section.length; i++) {
const ch = section[i];
if (ch === "#") {
const newline = section.indexOf("\n", i);
if (newline < 0) return null;
i = newline;
} else if (ch === '"' || ch === "'") {
let j = i + 1;
while (j < section.length && section[j] !== ch && section[j] !== "\n") {
j += ch === '"' && section[j] === "\\" ? 2 : 1;
}
if (section[j] !== ch) return null;
const literal = section.slice(i, j + 1);
if (depth === 1) items.push(ch === '"' ? decodeBasicString(literal) : literal.slice(1, -1));
i = j;
} else if (ch === "[") {
depth++;
} else if (ch === "]" && --depth === 0) {
return { open, end: i + 1, items };
}
}
return null;
}

function agentmemorySection(toml: string): string | null {
const bounds = sectionBounds(toml);
return bounds ? toml.slice(bounds.start, bounds.end) : null;
}

function hasLegacyCommand(toml: string): boolean {
const section = agentmemorySection(toml);
if (section === null) return false;
return isLegacyMcpCommand(section.match(COMMAND_LINE)?.[3], findArgs(section)?.items);
}

function hasCurrentCommand(toml: string): boolean {
const section = agentmemorySection(toml);
if (section === null) return false;
const args = findArgs(section)?.items;
return (
section.match(COMMAND_LINE)?.[3] === AGENTMEMORY_MCP_BLOCK.command &&
JSON.stringify(args) === JSON.stringify(AGENTMEMORY_MCP_BLOCK.args)
);
}

function migrateLegacyCommand(toml: string): string | null {
const bounds = sectionBounds(toml)!;
const section = toml.slice(bounds.start, bounds.end);
const args = findArgs(section);
if (!args) return null;
const nextArgs = `[${AGENTMEMORY_MCP_BLOCK.args.map((arg) => JSON.stringify(arg)).join(", ")}]`;
const migrated = (section.slice(0, args.open) + nextArgs + section.slice(args.end)).replace(
COMMAND_LINE,
(_, prefix: string) => `${prefix}${JSON.stringify(AGENTMEMORY_MCP_BLOCK.command)}`,
);
const next = toml.slice(0, bounds.start) + migrated + toml.slice(bounds.end);
return hasCurrentCommand(next) ? next : null;
}

function stripExistingBlock(toml: string): string {
const lines = toml.split(/\r?\n/);
const out: string[] = [];
Expand Down Expand Up @@ -76,8 +162,9 @@ export const adapter: ConnectAdapter = {
const exists = existsSync(CODEX_TOML);
const current = exists ? readFileSync(CODEX_TOML, "utf-8") : "";
const wired = isWiredText(current);
const legacy = wired && hasLegacyCommand(current);

if (wired && !opts.force) {
if (wired && !legacy && !opts.force) {
logAlreadyWired("Codex CLI", CODEX_TOML);
return { kind: "already-wired", mutatedPath: CODEX_TOML };
}
Expand All @@ -98,10 +185,20 @@ export const adapter: ConnectAdapter = {
mkdirSync(dirname(CODEX_TOML), { recursive: true });
}

const cleaned = wired ? stripExistingBlock(current) : current;
const joiner = cleaned.length === 0 || cleaned.endsWith("\n") ? "" : "\n";
const next = `${cleaned}${joiner}${cleaned.length > 0 ? "\n" : ""}${TOML_BLOCK}`;
writeFileSync(CODEX_TOML, next, "utf-8");
if (legacy && !opts.force) {
const migrated = migrateLegacyCommand(current);
if (migrated === null) {
p.log.error(
`Could not migrate the agentmemory launcher in ${CODEX_TOML}. Run again with --force to rewrite the block.`,
);
return { kind: "skipped", reason: "verification-failed" };
}
writeFileSync(CODEX_TOML, migrated, "utf-8");
} else {
const cleaned = wired ? stripExistingBlock(current) : current;
const joiner = cleaned.length === 0 || cleaned.endsWith("\n") ? "" : "\n";
writeFileSync(CODEX_TOML, `${cleaned}${joiner}${cleaned.length > 0 ? "\n" : ""}${TOML_BLOCK}`, "utf-8");
}

const verify = readFileSync(CODEX_TOML, "utf-8");
if (!isWiredText(verify)) {
Expand Down
Loading
Loading