# Connecting to AkiMCP over HTTP
> Guide rev 3 · AkiMCP 4.4+

Connect an HTTP chat client to the owner's AkiMCP server with a temporary token.

## 0. Kickoff block
````text
I own this AkiMCP server. Connect to MCP_URL using TOKEN by following GUIDE, then wait for my task. When I say the work is done, revoke the token and remove any saved state/helper files as section 4 describes (DELETE MCP_URL, or aki__temp_token op="revoke_self" for POST-only clients).
GUIDE: https://akimcp.top/guide/mcp-http.md
MCP_URL: https://<owner-host>/mcp
TOKEN: <temporary token>
NAME: <optional token name — omitted when unnamed>
````
`TOKEN` defaults to 4h (owner may extend in panel); ends on revoke, expiry, or restart.

## 1. Token & state storage (security lock)
- Never print `TOKEN` in chat, commits, URLs, logs, CLI `argv`, or public output, and **never write `TOKEN` or `token.json` inside an app or repo workspace** (dev servers serve workspace files; Export/Share/Deploy bundles them).
- Pick the first matching tier:
  1. **Persistent shell / shared host / GUI client:** shell memory or client secret vars only.
  2. **VM with shell (preferred):** save `{url, token, name, sid, receipt, ss}` in one `0600` JSON file **outside** workspace (`$HOME/.akimcp/token.json` if `$HOME` persists across turns, else `/tmp/akimcp/token.json`, atomic write, no symlink) beside helper `akimcp.py`.
  3. **No writable outside-workspace path, or missing/`401` after compaction:** fail closed — memory only, or stop and ask for a new kickoff; never scan other `/tmp/*` files, logs, or caches.

## 2. Handshake & reusable helper
One JSON-RPC 2.0 object per `POST` to `MCP_URL` (plain JSON; CORS exposes `MCP-Session-Id`, allows `DELETE`). Headers: `Authorization: Bearer <TOKEN>`, `Content-Type: application/json`, `Accept: application/json, text/event-stream`, `MCP-Protocol-Version: 2025-06-18`, `User-Agent: akimcp-client/1.0`, plus `MCP-Session-Id` after `initialize`.
1. **`initialize`** → save `MCP-Session-Id` (`notifications/initialized` optional, `202`).
2. **`tools/list`** → read exact tool names and schemas (`aki__` by default).
3. **`tools/call` `aki__akidevrule_context`** → `{}` on cold kickoff, or `{"workingPath":"/abs/path/to/repo"}` once a repo is named (`ss` on later calls). Save `receipt` (`sha256:<64 hex>`) and `ss`; acting tools refuse without `receipt`.

### 2a. Reusable Python 3 helper (write once outside workspace, call in 1 line)
Run `mkdir -p -m 700 /tmp/akimcp` (or `$HOME/.akimcp`), save `akimcp.py`, then run `MCP_URL=... TOKEN=... NAME=... python3 /tmp/akimcp/akimcp.py init [workingPath]` (secrets via env, never `argv`):
````python
#!/usr/bin/env python3
import json, os, re, sys, tempfile, urllib.error as ue, urllib.request as ur
D = os.path.dirname(os.path.abspath(__file__)); F = os.path.join(D, "token.json")
PV, UA = "2025-06-18", "akimcp-client/1.0"
def save(s):
  os.umask(0o077)
  with tempfile.NamedTemporaryFile("w", dir=D, delete=False, encoding="utf-8") as f: json.dump(s, f); t = f.name
  os.chmod(t, 0o600); os.replace(t, F)
def load(): return json.load(open(F, encoding="utf-8"))
def hd(x): return {k.lower(): v for k, v in x.items()}
def req(u, tok, b=None, sid=None, m="POST"):
  h = {"Authorization": f"Bearer {tok}", "Accept": "application/json, text/event-stream", "MCP-Protocol-Version": PV, "User-Agent": UA}
  if b is not None: h["Content-Type"] = "application/json"
  if sid: h["MCP-Session-Id"] = sid
  r = ur.Request(u, data=(json.dumps(b).encode() if b is not None else None), headers=h, method=m)
  try:
    with ur.urlopen(r, timeout=60) as p: return p.status, hd(p.headers), p.read().decode("utf-8", "replace")
  except ue.HTTPError as e: return e.code, hd(e.headers), e.read().decode("utf-8", "replace")
def hs(s):
  st, h, b = req(s["url"], s["token"], {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": PV, "capabilities": {}, "clientInfo": {"name": "web-chat-agent", "version": "1.0.0"}}})
  if st != 200 or not h.get("mcp-session-id"): sys.exit(f"init HTTP {st}: {b[:200]}")
  s["sid"] = h["mcp-session-id"]; save(s); return s
def rpc(s, m, p):
  pl = {"jsonrpc": "2.0", "id": 2, "method": m, "params": p}
  st, _, b = req(s["url"], s["token"], pl, s.get("sid"))
  if st == 404: s = hs(s); st, _, b = req(s["url"], s["token"], pl, s["sid"])
  if st != 200: sys.exit(f"HTTP {st}: {b[:240]}")
  return json.loads(b)
def tc(s, n, a):
  res = rpc(s, "tools/call", {"name": n, "arguments": a}).get("result", {})
  return res, (res.get("content") or [{}])[0].get("text", "")
def ctx(s, wp=None):
  wp = wp or s.get("wp")
  if wp: s["wp"] = wp
  res, txt = tc(s, "aki__akidevrule_context", {k: v for k, v in (("workingPath", wp), ("ss", s.get("ss"))) if v})
  m = re.search(r"sha256:[0-9a-f]{64}", txt)
  if m: s["receipt"] = m.group(0)
  ss = ((res.get("structuredContent") or {}).get("ss") or {}).get("path")
  if ss: s["ss"] = ss
  save(s); return txt
cmd = sys.argv[1] if len(sys.argv) > 1 else ""
if cmd == "init":
  s = hs({"url": os.environ["MCP_URL"], "token": os.environ["TOKEN"], "name": os.environ.get("NAME") or None})
  print(ctx(s, sys.argv[2] if len(sys.argv) > 2 else None)[:1200])
elif cmd == "ctx": print(ctx(load(), sys.argv[2] if len(sys.argv) > 2 else None)[:1200])
elif cmd == "list":
  for t in rpc(load(), "tools/list", {})["result"]["tools"]: print(t["name"], list((t.get("inputSchema") or {}).get("properties", {}).keys()))
elif cmd == "call":
  s, n, a = load(), sys.argv[2], json.loads(sys.argv[3]) if len(sys.argv) > 3 else {}
  res, txt = tc(s, n, a)
  if res.get("isError") and "RULE_RECEIPT_" in txt:
    if "UNKNOWN" in txt or not s.get("receipt"): ctx(s)
    res, txt = tc(s, n, {**a, "receipt": s["receipt"], **({"ss": s["ss"]} if s.get("ss") else {})})
  print(txt)
elif cmd == "revoke":
  s = load(); st, _, b = req(s["url"], s["token"], None, s.get("sid"), "DELETE")
  if st in (200, 204, 401):
    for p in (F, os.path.abspath(__file__)): os.path.exists(p) and os.remove(p)
    print(f"revoked (HTTP {st}); state removed")
  else: sys.exit(f"revoke HTTP {st}: {b[:160]}")
````
1-line calls: `python3 /tmp/akimcp/akimcp.py call aki__git '{"op":"status","repoPath":"/path"}'` (auto-renews `sid` on `404`, auto-attaches `receipt`/`ss`; `ctx /path` binds a repo later).

### 2b. Non-Python clients
- **Node 18+:** mirror `akimcp.py` with `fetch()` + `0600` `token.json` outside workspace.
- **POSIX sh / curl (no Bash arrays):** pass `-A 'akimcp-client/1.0' -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -H 'MCP-Protocol-Version: 2025-06-18'`; check HTTP `200`, extract `MCP-Session-Id` (`awk -F':' 'tolower($1)=="mcp-session-id"{sub(/^[[:space:]]+/,"",$2); print $2; exit}'`).
- **Postman:** collection vars `mcp_url`, `token` (secret), `session_id`; on `initialize`: `const sid = pm.response.headers.get("MCP-Session-Id"); if (sid) pm.collectionVariables.set("session_id", sid);`.

## 3. Errors
| Code | Meaning | Action |
|---|---|---|
| `401 Unauthorized` | wrong/expired/revoked | after revoke: done; else fail closed, ask for new kickoff |
| `403 Forbidden` | WAF blocked default UA | send `User-Agent: akimcp-client/1.0` on every request |
| `404 Session not found` | missing/stale `MCP-Session-Id` | re-run `initialize`, update `sid`, retry |
| `-32602` / receipt error | bad arg or rotated receipt | fix arg or re-call `aki__akidevrule_context`, retry |
| connection error | server/tunnel down | tell owner; no retry loop |

## 4. Revoke
Only when the owner says the work is done (never on compaction or transient errors):
- **`DELETE`:** `python3 /tmp/akimcp/akimcp.py revoke` (or `curl -sS -f -A 'akimcp-client/1.0' -X DELETE "$MCP_URL" -H "Authorization: Bearer $TOKEN" && rm -rf /tmp/akimcp`). `2xx`/`401` → delete `token.json` and helper; on network error ask owner to click **Revoke** in panel first.
- **POST-only (4.3.0+):** `aki__temp_token` `{"op":"revoke_self","receipt":"sha256:<64 hex>"}`, then delete `token.json` and helper.
