Skip to content

[codex] fix mcp helper stability and session loading regressions#26

Merged
Hmbown merged 2 commits intomainfrom
codex/fix-mcp-session-helper-regressions
Feb 10, 2026
Merged

[codex] fix mcp helper stability and session loading regressions#26
Hmbown merged 2 commits intomainfrom
codex/fix-mcp-session-helper-regressions

Conversation

@Hmbown
Copy link
Owner

@Hmbown Hmbown commented Feb 10, 2026

Summary

This PR fixes three MCP robustness regressions discovered while exercising Aleph end-to-end, and publishes a patch version bump to 0.8.3.

User-facing impact

Users could hit confusing or broken behavior in real workflows:

  • load_session could silently report success but restore zero sessions from valid memory packs generated by save_session.
  • After exec_python, rebinding helper names like lines, search, or semantic_search could break core MCP tools (peek_context, search_context, semantic_search) for that session.
  • search_context line numbers and peek_context(unit="lines") indexing were not aligned, making search hits harder to navigate directly.

Root cause

  1. save_session emitted per-session identifiers as session_id/context_id, while load_session only looked for id.
  2. Query tools resolved helpers from the mutable REPL namespace (repl.get_variable(...)), which user code can overwrite.
  3. Line slicing used helper-native 0-based indices, while search output advertises line numbers according to line_number_base.

Fixes

  • Added payload compatibility resolution for session IDs:
    • load_session now accepts id, context_id, or session_id.
    • Added structured skipped reporting instead of silently swallowing invalid entries.
  • Added stable helper references in the sandbox:
    • REPLEnvironment now stores immutable helper references and exposes get_helper(name).
    • Query tools now prefer stable helpers via _get_repl_helper(...).
  • Normalized line indexing for peek_context(unit="lines"):
    • Added _to_internal_line_index(...) conversion from external base to internal 0-based helper indices.
    • Preserved backward compatibility for legacy 0-based callers when start=0 on 1-based sessions.
  • Bumped package version from 0.8.2 to 0.8.3 in:
    • pyproject.toml
    • aleph/__init__.py

Tests and validation

  • Added targeted regression coverage:
    • tests/test_mcp_local_server_regressions.py
      • search/peek line-number alignment
      • helper-name rebinding does not break MCP tools
      • save/load session compatibility + skipped-session reporting
    • tests/test_sandbox.py
      • stable helper retrieval after name rebinding
    • tests/test_mcp_local_server.py
      • helper-level tests for payload ID resolution and line index normalization
  • Validation run:
    • ruff check aleph/ tests/
    • pytest tests/ -q ✅ (307 passed)

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @Hmbown, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses critical stability and regression issues within the MCP (Multi-Context Programming) server, specifically focusing on session management and the robustness of core helper tools. The changes ensure that sessions can be reliably loaded from various memory pack formats, prevent user code from inadvertently breaking essential MCP functionalities, and standardize line number reporting for improved user experience. These fixes enhance the overall reliability and predictability of the Aleph system.

Highlights

  • Session Loading Robustness: The load_session functionality now correctly identifies sessions from memory packs using multiple ID fields (id, context_id, session_id) and provides detailed reporting for skipped, invalid sessions instead of silent failures.
  • Stable MCP Tools: MCP tools like peek_context, search_context, and semantic_search are now robust against user-initiated helper name rebindings in the REPL environment by using stable, immutable references.
  • Consistent Line Numbering: Line number indexing for peek_context(unit="lines") has been aligned with search_context output, ensuring consistent 1-based indexing for external display while handling internal 0-based helper indices and maintaining backward compatibility.
  • Version Bump: The package version has been updated from 0.8.2 to 0.8.3.
  • New Regression Tests: Comprehensive regression tests have been added to validate the fixes for session loading, helper stability, and line number alignment.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • aleph/init.py
    • Updated the __version__ string to "0.8.3".
  • aleph/mcp/local_server.py
    • Added _to_internal_line_index to convert external line numbers to internal 0-based indices, with backward compatibility for 0-based callers.
    • Introduced _resolve_session_payload_id to robustly extract session identifiers from memory pack payloads, supporting id, context_id, and session_id keys.
    • Implemented _get_repl_helper to retrieve stable helper references from the REPL environment.
    • Modified load_session to use _resolve_session_payload_id and to report skipped invalid sessions in its output.
    • Updated peek_context, search_context, and semantic_search to utilize _get_repl_helper for stable helper access and _to_internal_line_index for consistent line indexing in peek_context.
  • aleph/repl/sandbox.py
    • Stored initial helper references in a new _helpers dictionary within REPLEnvironment to maintain stable access.
    • Added a get_helper method to REPLEnvironment to retrieve these stable helper references.
  • pyproject.toml
    • Updated the project version to "0.8.3".
  • tests/test_mcp_local_server.py
    • Imported new helper functions _resolve_session_payload_id and _to_internal_line_index.
    • Added TestSessionPayloadHelpers class to test session ID resolution logic.
    • Added TestLineIndexHelpers class to test line index conversion.
  • tests/test_mcp_local_server_regressions.py
    • Added a new test file to cover specific regression scenarios.
    • Included tests for peek_context line number alignment with search_context.
    • Added tests to verify that rebinding helper names in exec_python does not break MCP tools.
    • Included tests for load_session's ability to accept context_id format and correctly report skipped sessions.
  • tests/test_sandbox.py
    • Added test_get_helper_stable_after_name_rebind to confirm that get_helper returns stable references even after REPL variables are reassigned.
Activity
  • No specific activity (comments, reviews, or progress updates) has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request effectively addresses several robustness and stability regressions related to session loading, helper function stability, and line number indexing. The fixes are well-implemented and accompanied by a comprehensive suite of regression tests, which is excellent for long-term maintainability. The overall code quality is high. I have one suggestion to further improve the atomicity of the session loading logic, ensuring that partially configured sessions are not added to the active session map in case of an error during configuration.

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@Hmbown Hmbown marked this pull request as ready for review February 10, 2026 01:19
Copilot AI review requested due to automatic review settings February 10, 2026 01:19
@Hmbown Hmbown merged commit 9423dfb into main Feb 10, 2026
1 check passed
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR addresses MCP local-server robustness regressions around session pack loading compatibility, REPL helper stability (when user code rebinds helper names), and consistent line-index semantics between search_context and peek_context(unit="lines"), and bumps the package version to 0.8.3.

Changes:

  • Add stable helper resolution via REPLEnvironment.get_helper() and use it in MCP query tools to avoid breakage after helper-name rebinding.
  • Make load_session accept id/context_id/session_id payload identifiers and report skipped/invalid entries.
  • Normalize peek_context(unit="lines") indices to align with line_number_base, with backward compatibility for legacy 0-based callers, and add regression tests + version bumps.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
aleph/mcp/local_server.py Adds helper-resolution + session-id compatibility helpers, improves load_session reporting, and normalizes line indexing for peek_context.
aleph/repl/sandbox.py Preserves stable helper references and exposes get_helper() for tool-side resolution.
tests/test_mcp_local_server_regressions.py New end-to-end regression tests covering the reported regressions.
tests/test_mcp_local_server.py Adds unit tests for new helper functions used by the local server.
tests/test_sandbox.py Adds REPL-level test ensuring get_helper() remains stable after name rebinding.
pyproject.toml Bumps project version to 0.8.3.
aleph/__init__.py Bumps __version__ to 0.8.3.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 2416 to 2418
loaded = []
skipped: list[dict[str, str]] = []
for sp in payload.get("sessions", []):
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

load_session() iterates over payload.get("sessions", []) without validating that sessions is a list. If a malformed pack has sessions as a dict/string, this will iterate keys/characters and produce a misleading “success + many skipped” result instead of a clear schema error. Consider validating sessions is a list (and each entry is a dict) and returning an explicit "Invalid memory pack" error when it isn’t.

Suggested change
loaded = []
skipped: list[dict[str, str]] = []
for sp in payload.get("sessions", []):
sessions = payload.get("sessions")
if sessions is None:
sessions = []
if not isinstance(sessions, list) or any(not isinstance(sp, dict) for sp in sessions):
return _format_error("Invalid memory pack", output=output)
loaded = []
skipped: list[dict[str, str]] = []
for sp in sessions:

Copilot uses AI. Check for mistakes.
Comment on lines +2423 to +2426
try:
session = _session_from_payload(sp, sid, self.sandbox_config, asyncio.get_running_loop())
self._configure_session(session, sid, loop=asyncio.get_running_loop())
self._sessions[sid] = session
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

Inside the load_session() loop, asyncio.get_running_loop() is called twice per session payload. Since the loop is constant within this coroutine, it would be clearer and slightly more efficient to grab it once before iterating and reuse the same variable for _session_from_payload(...) and _configure_session(...).

Copilot uses AI. Check for mistakes.
self._namespace.update(helpers_ns)
# Preserve stable helper references so MCP tools can resolve helpers
# even if user code rebinds names in the REPL namespace.
self._helpers: dict[str, object] = dict(helpers_ns)
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

REPLEnvironment already imports the helpers module as _helpers, and this change adds an instance attribute named self._helpers. The name collision is easy to misread/typo (module vs dict) and can lead to maintenance bugs later. Consider renaming the attribute to something unambiguous like self._stable_helpers (and updating get_helper() accordingly).

Suggested change
self._helpers: dict[str, object] = dict(helpers_ns)
self._stable_helpers: dict[str, object] = dict(helpers_ns)

Copilot uses AI. Check for mistakes.
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.

2 participants