Skip to content

fix(api): sort memory_sessions by recency, expose limit param#961

Open
shgew wants to merge 2 commits into
rohitg00:mainfrom
shgew:fix/api-sessions-cap-and-sort
Open

fix(api): sort memory_sessions by recency, expose limit param#961
shgew wants to merge 2 commits into
rohitg00:mainfrom
shgew:fix/api-sessions-cap-and-sort

Conversation

@shgew

@shgew shgew commented Jun 20, 2026

Copy link
Copy Markdown

What

api::sessions now sorts sessions by most-recent activity and accepts a numeric ?limit. When ?limit is absent, all sessions are returned (preserves the viewer dashboard, which consumes the same endpoint). When provided, the value is honored verbatim with a non-negative floor; no upper cap. The MCP memory_sessions path self-defaults to 20 and exposes limit in its tool schema.

Why

Pre-fix: REST returned every session in KV order with an N+1 summary fetch on the full set, which bloated MCP client context on large stores. The fix lets the caller choose how many sessions they want without imposing an arbitrary ceiling.

How

Both MCP paths (in-process handler and standalone proxy shim) self-default to 20, so neither relies on the REST default.

Tests

test/api-sessions-limit.test.ts (4 cases). Targeted suite: 4/4 pass.

Compatibility

REST default-all matches pre-existing behavior. MCP self-default is opaque to REST consumers. No upper bound clamp; callers passing very large limits get exactly what they ask for.

Summary by CodeRabbit

  • New Features

    • Memory sessions now support a limit parameter to control the number of results returned (defaults to 20).
    • Sessions are now sorted by recency, displaying most recently updated sessions first.
  • Tests

    • Added comprehensive test suite validating limit and recency-based session ordering behavior.

api::sessions returns sessions sorted by most-recent activity and
accepts a numeric ?limit. When ?limit is absent, all sessions are
returned (preserves the viewer dashboard, which consumes the same
endpoint). When provided, the value is honored verbatim with a
non-negative floor; no upper cap. The MCP memory_sessions path
self-defaults to 20 and exposes the same limit field in its tool
schema.

Pre-fix: REST returned every session in KV order with an N+1
summary fetch on the full set, bloating MCP client context on
large stores. The fix lets the caller choose how many sessions
they want without imposing an arbitrary ceiling.

Both MCP paths (in-process handler and standalone proxy shim)
self-default to 20, so neither relies on the REST default.

Tests: test/api-sessions-limit.test.ts (4 cases).

Signed-off-by: Hleb Shauchenka <me@marleb.org>
@vercel

vercel Bot commented Jun 20, 2026

Copy link
Copy Markdown

@shgew is attempting to deploy a commit to the rohitg00's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2b89b20a-a7f5-418e-8145-2861400a4beb

📥 Commits

Reviewing files that changed from the base of the PR and between 7ece022 and 09f345c.

📒 Files selected for processing (2)
  • src/types.ts
  • test/api-sessions-limit.test.ts
✅ Files skipped from review due to trivial changes (1)
  • src/types.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/api-sessions-limit.test.ts

📝 Walkthrough

Walkthrough

Session listing is updated in two surfaces: the api::sessions REST handler and the memory_sessions MCP tool. Both now derive a recency key from the newest available timestamp field across sessions, sort by that key descending, and slice to a configurable limit. The Session type gains optional timestamp fields supporting this calculation. A new Vitest suite validates the API's ordering and limit edge cases.

Changes

Session Listing: Recency Sort and Limit

Layer / File(s) Summary
Session type extension
src/types.ts
Session type gains optional updatedAt and lastCheckpointAt timestamp fields to support recency key computation.
REST API recency sort and limit
src/triggers/api.ts
Handler parses a limit query parameter, computes a per-session recencyKey from multiple timestamp fields, sorts filtered sessions by that key descending, slices to the limit, and restricts summary hydration to the resulting subset.
MCP tool recency sort and limit
src/mcp/tools-registry.ts, src/mcp/server.ts
memory_sessions tool schema adds a limit numeric input (default 20); handler derives a bounded limit from args.limit, computes recency keys, sorts sessions descending, and slices instead of returning the raw KV list.
API sessions limit and recency test suite
test/api-sessions-limit.test.ts
Tests cover default ordering (most-recent first with all sessions), explicit limits (e.g., 5 sessions), oversize limits (no truncation), and non-positive limits (empty result).

Sequence Diagram

sequenceDiagram
  participant Client
  participant api_sessions as api::sessions handler
  participant KV

  Client->>api_sessions: GET /sessions?limit=N
  api_sessions->>KV: list sessions (all)
  KV-->>api_sessions: raw session list
  api_sessions->>api_sessions: compute recencyKey per session
  api_sessions->>api_sessions: sort by recencyKey desc
  api_sessions->>api_sessions: slice to limit (or all if undefined)
  api_sessions->>KV: lookup summaries for recent subset only
  KV-->>api_sessions: summaries
  api_sessions-->>Client: sorted, limited session list
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐇 Hippity-hoppity, sessions in line,
Sorted by recency, fresh and fine!
A limit of twenty (or more, or less),
Keeps the KV tidy — no clutter, no mess.
The newest timestamps lead the parade,
While old sessions wait in the shade. 🌿

🚥 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 directly and specifically summarizes the main changes: sorting memory_sessions by recency and exposing the limit parameter, which are the primary objectives of this pull request.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@shgew shgew changed the title fix(api): cap and sort memory_sessions, expose limit param fix(api): sort memory_sessions by recency, expose limit param Jun 20, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/triggers/api.ts`:
- Around line 827-830: The recencyKey function in src/triggers/api.ts references
properties updatedAt and lastCheckpointAt on the Session object, but the Session
interface in src/types.ts does not declare these properties, causing TypeScript
type errors. Add updatedAt and lastCheckpointAt as string properties (or
optional string properties if they're conditionally present) to the Session
interface definition in src/types.ts to match what the recencyKey function
expects when comparing session timestamps.

In `@test/api-sessions-limit.test.ts`:
- Around line 126-132: The test "treats non-positive limit as zero" currently
only validates the behavior when limit is "0", but the test name implies it
should cover all non-positive values including negative numbers. Add an
additional assertion or test case within this test that also checks the behavior
when passing a negative limit value like "-1" to the reqWithLimit function to
ensure both zero and negative limits are handled consistently and treated as
zero in the sessions response.
🪄 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: 80bc192e-fd51-45dc-a0aa-61c53782b18f

📥 Commits

Reviewing files that changed from the base of the PR and between f6f9e3c and 7ece022.

📒 Files selected for processing (4)
  • src/mcp/server.ts
  • src/mcp/tools-registry.ts
  • src/triggers/api.ts
  • test/api-sessions-limit.test.ts

Comment thread src/triggers/api.ts
Comment thread test/api-sessions-limit.test.ts
…negative limit

recencyKey() in src/triggers/api.ts and src/mcp/server.ts reads these
fields, so the Session interface needs to declare them or strict mode
emits TS2339. Both are optional in practice (persisted sessions backfill
them via checkpoint runs), so they are typed as optional strings.

Also extend the 'treats non-positive limit as zero' case to assert -1
in addition to 0, matching the contract the endpoint promises.
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.

1 participant