Skip to content

fix: Add session settings#42

Open
jasonjgardner wants to merge 1 commit into
mainfrom
fix/sessions
Open

fix: Add session settings#42
jasonjgardner wants to merge 1 commit into
mainfrom
fix/sessions

Conversation

@jasonjgardner

@jasonjgardner jasonjgardner commented Jun 12, 2026

Copy link
Copy Markdown
Owner

Closes #41

Summary by CodeRabbit

  • Documentation

    • Updated configuration examples in README with improved formatting and guidance.
  • Improvements

    • Increased default session timeout from 5 to 30 minutes for longer-lasting sessions.
    • Enhanced session management and error handling for improved reliability.
  • Chores

    • Version updated to 1.6.1.
    • Added plugin metadata including contributors and project links.

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Session management improved with extended 30-minute inactivity timeout and ping-failure handling removed in favor of timeout-based cleanup. HTTP session initialization refactored to validate initialize requests separately and return proper error codes for missing sessions. Keep-alive ping now uses explicit JSON-RPC request. Documentation and metadata updated to align with version 1.6.1 release.

Changes

Session Management and HTTP Handling

Layer / File(s) Summary
Session timeout configuration
lib/sessions.ts, index.ts, ui/settings.ts
Default session inactivity timeout constant and fallback values increased from 5 minutes to 30 minutes across all configuration entry points.
Ping failure handling refactor
lib/sessions.ts
recordPingFailed signature changed from returning boolean to void; ping failures now cap the counter, log informational messages, and do not terminate sessions; session expiry delegated entirely to inactivity timeout.
HTTP session handling and initialization
server/net.ts
Session gating logic refactored: invalid session headers return 404 JSON-RPC error; non-initialize requests without session return 400 error; keep-alive ping uses explicit server.request with EmptyResultSchema; session initialization uses newSession closure instead of temporary map entry; client version capture wired from initialized sessionServer.server.
Documentation and metadata
README.md, index.ts, package.json, prompts/manifest.json
Claude Desktop config examples add -y flag and multi-line formatting; plugin registration gains contributors, website, repository, and bug_tracker metadata; version bumped to 1.6.1; manifest timestamp updated.

Sequence Diagram

sequenceDiagram
  participant Client
  participant HTTPHandler as HTTP Handler
  participant SessionGate as Session Gating
  participant NewSession as newSession Closure
  participant SessionServer as SessionServer
  participant SessionMgr as SessionManager
  Client->>HTTPHandler: POST with/without Mcp-Session-Id
  HTTPHandler->>SessionGate: check if session exists
  alt Session Header Valid
    SessionGate->>SessionGate: session found
    SessionGate->>Client: 200 (existing session)
  else Session Header Missing/Invalid
    SessionGate->>SessionGate: no active session
    alt Request is initialize
      SessionGate->>NewSession: create newSession closure
      NewSession->>SessionServer: initialize server
      SessionServer->>NewSession: return sessionServer
      NewSession->>SessionMgr: getClientVersion from<br/>sessionServer.server
      SessionServer->>SessionServer: connect transport
      NewSession->>NewSession: assign transport
      Client->>Client: session initialized
    else Non-initialize Request
      SessionGate->>Client: 400 error<br/>(session required)
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • jasonjgardner/blockbench-mcp-plugin#32: Both PRs modify the session/ping lifecycle code—main PR changes lib/sessions.ts session inactivity and recordPingFailed behavior plus server/net.ts keep-alive ping + session handling—so they overlap at the same session management entry points.

Suggested labels

enhancement

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Several changes appear out of scope: plugin metadata additions (contributors, website, repository, bug_tracker fields), version bumping, timestamp updates, and significant session handling refactors beyond simple configuration fixes. Separate out-of-scope changes into dedicated PRs: documentation enhancements, metadata updates, and session management refactors should each have their own focused PR with clear objectives.
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'fix: Add session settings' is vague and generic, using non-descriptive terms that don't convey the specific nature of the changes related to session configuration. Clarify the title to describe the actual changes made, such as 'fix: Increase default session timeout and update session handling' or similar.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed The PR addresses the reported Claude Desktop configuration issue through multiple improvements: enhanced README documentation, updated session timeout defaults, refactored session management logic, and improved HTTP error handling.

✏️ 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/sessions

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.

@github-actions

Copy link
Copy Markdown
Contributor

Preview Deployment

Your changes have been deployed for preview:

Plugin URL: https://jasonjgardner.github.io/blockbench-mcp-plugin/pr/42/mcp.js

Load in Blockbench via File > Plugins > Load Plugin from URL.

This preview will be automatically cleaned up when the PR is closed.

github-actions Bot added a commit that referenced this pull request Jun 12, 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 `@index.ts`:
- Around line 71-74: Startup must perform a one-time migration to rewrite the
persisted mcp_session_timeout when it still equals the old broken default so
upgrades adopt the new timeout; before you call
toFiniteNumber(Settings.get("mcp_session_timeout"), 30) in index.ts, read the
raw value via Settings.get("mcp_session_timeout"), detect the old-broken default
numeric/string sentinel (the value used previously), and if matched call
Settings.set("mcp_session_timeout", <newDefault>) to overwrite it; then use
toFiniteNumber on the (possibly updated) Settings.get result. Reference the
existing Settings.get/Settings.set calls and the sessionTimeoutMin assignment in
index.ts and the setting declaration in ui/settings.ts when implementing this
migration.

In `@server/net.ts`:
- Around line 72-91: The isInitializeRequestBody helper currently treats any
object with method === 'initialize' as an initialization request; change it to
validate a real JSON-RPC 2.0 request by parsing the body and ensuring the parsed
value is a non-array object with jsonrpc === '2.0', method === 'initialize', and
a present request id (string or number) so notifications/malformed envelopes are
rejected; update isInitializeRequestBody to perform these checks (keep the
try/catch and return false on parse errors) so only a proper JSON-RPC initialize
request triggers session setup.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 695c967f-fe4a-41fa-84c5-66db0cce5a08

📥 Commits

Reviewing files that changed from the base of the PR and between 217fa2c and 278c02c.

📒 Files selected for processing (7)
  • README.md
  • index.ts
  • lib/sessions.ts
  • package.json
  • prompts/manifest.json
  • server/net.ts
  • ui/settings.ts

Comment thread index.ts
Comment thread server/net.ts
Comment on lines +72 to +91
/**
* Whether an HTTP request carries an MCP InitializeRequest. Only initialize
* requests may create a new session — anything else without a session ID is
* a client error, not a new connection. Per spec an InitializeRequest must
* not be part of a JSON-RPC batch, so only a sole non-batched message counts.
*/
function isInitializeRequestBody (method: string, body: string): boolean {
if (method !== 'POST' || !body) return false
try {
const parsed: unknown = JSON.parse(body)
if (Array.isArray(parsed)) return false
return (
typeof parsed === 'object' &&
parsed !== null &&
(parsed as { method?: unknown }).method === 'initialize'
)
} catch {
return false
}
}

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Require a real JSON-RPC request before creating a session.

Line 78 currently accepts any object with method: "initialize", including notifications or malformed envelopes with no request id. That means invalid traffic skips the 400 path and still enters the expensive per-session setup branch. Tighten this helper to require a proper JSON-RPC initialize request.

Suggested diff
 function isInitializeRequestBody (method: string, body: string): boolean {
   if (method !== 'POST' || !body) return false
   try {
     const parsed: unknown = JSON.parse(body)
     if (Array.isArray(parsed)) return false
-    return (
-      typeof parsed === 'object' &&
-      parsed !== null &&
-      (parsed as { method?: unknown }).method === 'initialize'
-    )
+    if (typeof parsed !== 'object' || parsed === null) return false
+    const request = parsed as {
+      jsonrpc?: unknown
+      id?: unknown
+      method?: unknown
+    }
+    return (
+      request.jsonrpc === '2.0' &&
+      request.method === 'initialize' &&
+      request.id !== undefined &&
+      request.id !== null
+    )
   } catch {
     return false
   }
 }
🤖 Prompt for 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.

In `@server/net.ts` around lines 72 - 91, The isInitializeRequestBody helper
currently treats any object with method === 'initialize' as an initialization
request; change it to validate a real JSON-RPC 2.0 request by parsing the body
and ensuring the parsed value is a non-array object with jsonrpc === '2.0',
method === 'initialize', and a present request id (string or number) so
notifications/malformed envelopes are rejected; update isInitializeRequestBody
to perform these checks (keep the try/catch and return false on parse errors) so
only a proper JSON-RPC initialize request triggers session setup.

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.

reddit user error report

1 participant