Skip to content

feat(api): add GET /agentmemory/memories/:id (#196)#208

Merged
rohitg00 merged 1 commit intomainfrom
fix/196-memory-by-id
Apr 26, 2026
Merged

feat(api): add GET /agentmemory/memories/:id (#196)#208
rohitg00 merged 1 commit intomainfrom
fix/196-memory-by-id

Conversation

@rohitg00
Copy link
Copy Markdown
Owner

@rohitg00 rohitg00 commented Apr 26, 2026

Summary

The route was simply not registered. `POST /remember` writes to `KV.memories` keyed by the generated id; `GET /memories` lists from the same scope. There was no by-id retrieval handler at all, so any "save then fetch-by-ID" round-trip returned 404 even though the data was in storage and visible in list responses.

Adds `api::memory-by-id` with path-param `:id`:

  • 200 `{ memory }` on hit (matches the POST response shape)
  • 404 `{ error }` on miss
  • 400 if id is empty
  • Auth gate matches the rest of the protected endpoints

Thanks @Axialon for the precise repro and root-cause guess (correct: it was a missing handler, not a scope mismatch).

Closes #196

Test plan

  • `POST /agentmemory/remember` then `GET /agentmemory/memories/` — must 200 with the same memory object
  • `GET /agentmemory/memories/does-not-exist` — must 404
  • Existing `GET /agentmemory/memories` list endpoint still works

Summary by CodeRabbit

  • New Features
    • Added a new authenticated API endpoint to retrieve individual memories by ID, with appropriate error handling for invalid or missing requests.

The route was simply not registered. POST /remember writes to
\`KV.memories\` keyed by the generated id; GET /memories lists from
the same scope. There was no by-id retrieval handler at all, so any
\`save then fetch-by-ID\` round-trip (including the MCP tool chain's
memory verification step) returned 404 even though the data was in
storage.

Adds \`api::memory-by-id\` with path-param \`:id\`. Returns 200
\`{ memory }\` on hit, 404 \`{ error }\` on miss, 400 if id is empty.
Auth gate matches the rest of the protected endpoints.

Thanks @Axialon for the precise repro and root-cause guess (which
was correct: it was a missing handler, not a scope mismatch).

Closes #196
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 26, 2026

📝 Walkthrough

Walkthrough

A new authenticated GET endpoint is added to retrieve individual memories by ID (GET /agentmemory/memories/:id), including parameter validation and KV lookup logic. A formatting adjustment is also applied to an existing function registration.

Changes

Cohort / File(s) Summary
New Memory Lookup Endpoint
src/triggers/api.ts
Added authenticated GET handler for /agentmemory/memories/:id with ID parameter type validation, KV store lookup, and proper error responses (400 for invalid/missing ID, 404 for not found, 200 with memory object on success). Minor formatting change to existing api::memories registration.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A memory lost, now found once more,
The ID lookup opens every door,
From storage deep, the rabbit hops with cheer,
GET by ID—the missing piece is here!
hop hop 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding a new GET endpoint for retrieving memories by ID, matching the primary objective and the linked issue reference.
Linked Issues check ✅ Passed The PR implements all coding requirements from issue #196: adds the missing GET /agentmemory/memories/:id handler with correct authorization, returns appropriate status codes (200, 404, 400), and matches POST response shape.
Out of Scope Changes check ✅ Passed All changes are scoped to implementing the missing handler and fixing the root cause identified in issue #196; the minor formatting change to the existing api::memories registration is a trivial incidental adjustment within scope.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/196-memory-by-id

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/triggers/api.ts (1)

1346-1349: Optional: tighten and trim the id validation.

req.path_params?.["id"] typed as string already implies string, but a whitespace-only segment would currently pass. Rejecting blank/whitespace ids early (and trimming) avoids a needless KV lookup and gives a clearer 400.

♻️ Suggested refinement
-      const id = req.path_params?.["id"];
-      if (!id || typeof id !== "string") {
-        return { status_code: 400, body: { error: "id path parameter is required" } };
-      }
-      const memory = await kv.get<import("../types.js").Memory>(KV.memories, id);
+      const rawId = req.path_params?.["id"];
+      const id = typeof rawId === "string" ? rawId.trim() : "";
+      if (!id) {
+        return { status_code: 400, body: { error: "id path parameter is required" } };
+      }
+      const memory = await kv.get<import("../types.js").Memory>(KV.memories, id);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/triggers/api.ts` around lines 1346 - 1349, The id extracted from
req.path_params (const id = req.path_params?.["id"]) can be a whitespace-only
string; update the validation to trim and reject empty values to avoid
unnecessary KV lookups: coerce/ensure the value is a string, do const idRaw =
req.path_params?.["id"]; const id = typeof idRaw === "string" ? idRaw.trim() :
""; then if (!id) return 400 with the same error; use the trimmed id for
subsequent operations (e.g., KV lookup) so whitespace-only ids are rejected
early.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/triggers/api.ts`:
- Around line 1342-1361: Update the stale endpoint count from 107 to 104: change
the README text that currently says "107 endpoints" to "104 endpoints" and
update the runtime log string that prints "Endpoints: 107 REST" to "Endpoints:
104 REST" (look for the exact literal "Endpoints: 107 REST" in the index logging
code, e.g., where the app prints endpoint counts via console.log or a logger).

---

Nitpick comments:
In `@src/triggers/api.ts`:
- Around line 1346-1349: The id extracted from req.path_params (const id =
req.path_params?.["id"]) can be a whitespace-only string; update the validation
to trim and reject empty values to avoid unnecessary KV lookups: coerce/ensure
the value is a string, do const idRaw = req.path_params?.["id"]; const id =
typeof idRaw === "string" ? idRaw.trim() : ""; then if (!id) return 400 with the
same error; use the trimmed id for subsequent operations (e.g., KV lookup) so
whitespace-only ids are rejected early.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 930255e1-7627-4cbe-ac8f-0887c7b4afa1

📥 Commits

Reviewing files that changed from the base of the PR and between 18e3257 and cf15036.

📒 Files selected for processing (1)
  • src/triggers/api.ts

Comment thread src/triggers/api.ts
Comment on lines +1342 to +1361
sdk.registerFunction("api::memory-by-id",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const id = req.path_params?.["id"];
if (!id || typeof id !== "string") {
return { status_code: 400, body: { error: "id path parameter is required" } };
}
const memory = await kv.get<import("../types.js").Memory>(KV.memories, id);
if (!memory) {
return { status_code: 404, body: { error: `memory not found: ${id}` } };
}
return { status_code: 200, body: { memory } };
},
);
sdk.registerTrigger({
type: "http",
function_id: "api::memory-by-id",
config: { api_path: "/agentmemory/memories/:id", http_method: "GET" },
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify README and index.ts mention the new endpoint and any endpoint counts are updated.
fd -t f 'README.md' --max-depth 2
rg -nP '/agentmemory/memories(/:id|/\{id\})?' -C2
rg -nP 'memory-by-id|memories/:id' -C2
rg -nPi 'endpoints?\s*[:\-]?\s*\d+|\d+\s+endpoints?' README.md 2>/dev/null

Repository: rohitg00/agentmemory

Length of output: 1562


🏁 Script executed:

#!/bin/bash
# Check index.ts for endpoint count references
find . -name 'index.ts' -type f | head -10

# Count actual endpoints registered in src/triggers/api.ts
echo "=== Total registerTrigger calls in api.ts ==="
rg -c 'registerTrigger' src/triggers/api.ts

echo "=== List all endpoints in api.ts ==="
rg -oP 'api_path:\s*"([^"]+)"' src/triggers/api.ts | sort | uniq -c | sort -rn

# Check if index.ts exists at repo root or src root
echo "=== Checking for index.ts ==="
cat src/index.ts 2>/dev/null | grep -i 'endpoint' -C 2 || echo "No endpoint references in src/index.ts"

Repository: rohitg00/agentmemory

Length of output: 5848


Update endpoint counts in README.md and src/index.ts — they show 107 but should be 104.

The handler implementation itself is correct — it's registered in api.ts (lines 1342–1361) and uses proper auth/validation patterns consistent with other endpoints. However, the endpoint counts in your documentation are stale:

  • README.md text states "107 endpoints" (should be 104 — matches the badge already)
  • src/index.ts logs "Endpoints: 107 REST" (should be 104)

Both need to be corrected to 104 to match the actual unique endpoint count in the codebase.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/triggers/api.ts` around lines 1342 - 1361, Update the stale endpoint
count from 107 to 104: change the README text that currently says "107
endpoints" to "104 endpoints" and update the runtime log string that prints
"Endpoints: 107 REST" to "Endpoints: 104 REST" (look for the exact literal
"Endpoints: 107 REST" in the index logging code, e.g., where the app prints
endpoint counts via console.log or a logger).

@rohitg00 rohitg00 merged commit c4efcd9 into main Apr 26, 2026
3 of 4 checks passed
@rohitg00 rohitg00 deleted the fix/196-memory-by-id branch April 26, 2026 23:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

REST GET /memories/:id returns 404 for IDs confirmed to exist in storage + list endpoint

1 participant