Skip to content

Make MCP connections concurrency-safe and extend thinking config#107

Merged
JohnRichard4096 merged 5 commits into
mainfrom
fix
Jul 3, 2026
Merged

Make MCP connections concurrency-safe and extend thinking config#107
JohnRichard4096 merged 5 commits into
mainfrom
fix

Conversation

@JohnRichard4096

@JohnRichard4096 JohnRichard4096 commented Jul 3, 2026

Copy link
Copy Markdown
Member

Summary by Sourcery

Make MCP client connections concurrency-safe and enhance OpenAI adapter thinking configuration while updating docs and versioning.

New Features:

  • Enable local search provider in the VitePress documentation site.

Bug Fixes:

  • Prevent concurrent MCP client connections and closures from causing race conditions by making connect and close idempotent and lock-protected.
  • Align OpenAI adapter thinking parameters with model expectations by routing thinking configuration through extra_body and gating reasoning effort on presence.

Enhancements:

  • Clarify MCP connection semantics as idempotent and safe for concurrent calls.
  • Document X-Powered-By headers describing AmritaCore and AmritaSense.
  • Annotate ThinkingConfig for future model-adapter specific configuration and remove obsolete TODO/commented code in the agent module.

Build:

  • Bump project version from 0.10.2 to 0.10.3.

Tests:

  • Update MCP connection tests to assert that repeated connects are safely suppressed instead of raising errors.

@sourcery-ai

sourcery-ai Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Makes MCP client connection handling idempotent and concurrency-safe, adds structured thinking configuration support to the OpenAI adapter, enables local search in docs, performs minor cleanup of deprecated comments/config, and bumps the project version.

Sequence diagram for concurrent MCPClient connection handling

sequenceDiagram
    actor Caller1
    actor Caller2
    participant MCPClient
    participant Client

    Caller1->>MCPClient: _connect(update_tools)
    activate MCPClient
    MCPClient->>MCPClient: _connect_lock.acquire()
    MCPClient->>MCPClient: _clean_waitter()
    MCPClient->>Client: Client(server_script)
    MCPClient->>Client: __aenter__()
    Client-->>MCPClient: client ready
    MCPClient->>MCPClient: list_tools()
    MCPClient->>MCPClient: _cast_tool_to_amrita()
    MCPClient->>MCPClient: _connect_lock.release()
    deactivate MCPClient

    Caller2->>MCPClient: _connect(update_tools)
    activate MCPClient
    MCPClient->>MCPClient: _connect_lock.acquire()
    alt mcp_client already connected
        MCPClient-->>Caller2: return
    end
    MCPClient->>MCPClient: _connect_lock.release()
    deactivate MCPClient

    Caller1->>MCPClient: _close()
    activate MCPClient
    MCPClient->>MCPClient: _connect_lock.acquire()
    MCPClient->>Client: __aexit__(None, None, None)
    Client-->>MCPClient: closed
    MCPClient->>MCPClient: mcp_client = None
    MCPClient->>MCPClient: _connect_lock.release()
    deactivate MCPClient
Loading

File-Level Changes

Change Details Files
Make MCPClient connection and shutdown idempotent and safe under concurrent use.
  • Introduce an asyncio-compatible lock stored on the MCPClient instance to serialize connect/close operations.
  • Guard the _connect method with the lock and short‑circuit if a connection already exists instead of raising an error.
  • Guard the _close method with the same lock to avoid races with concurrent connects/closes.
  • Adjust the _connect test to expect silent success instead of a RuntimeError when already connected.
src/amrita_core/tools/mcp.py
tests/test_mcp.py
Extend OpenAI adapter to pass structured thinking configuration through extra_body while keeping reasoning_effort handling backwards compatible.
  • Initialize extra_body in OpenAI chat completions call paths when not provided.
  • If preset.thinking_config is set, optionally pass thinking.type and enable_thinking via extra_body while only setting reasoning_effort when a value is present.
  • Apply the same thinking/extra_body behavior to both normal call_api and tool-calling paths.
src/amrita_core/adapters/openai.py
src/amrita_core/types/preset.py
Enable local search in VitePress docs for both English and Chinese sites.
  • Add themeConfig.search.provider = "local" in the main docs configuration.
  • Mirror the same search configuration for the Chinese docs section.
docs/docs/.vitepress/config.mts
Perform minor documentation and configuration polish.
  • Add an X-Powered-By comment block describing AmritaCore and AmritaSense.
  • Remove an obsolete TODO comment from config and another from the agent strategy file.
  • Bump the project version to 0.10.3 and refresh the dependency lockfile.
src/amrita_core/consts.py
src/amrita_core/builtins/agent.py
src/amrita_core/config.py
pyproject.toml
uv.lock

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@JohnRichard4096

Copy link
Copy Markdown
Member Author

@sourcery-ai title

@sourcery-ai sourcery-ai Bot changed the title Fix Make MCP connections concurrency-safe and extend thinking config Jul 3, 2026
@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying amritacore with  Cloudflare Pages  Cloudflare Pages

Latest commit: 86f3af7
Status: ✅  Deploy successful!
Preview URL: https://ea216461.amritacore.pages.dev
Branch Preview URL: https://fix.amritacore.pages.dev

View logs

@sourcery-ai sourcery-ai 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.

Hey - I've found 1 issue, and left some high level feedback:

  • In MCPClient._connect, calling await self._clean_waitter() inside the _connect_lock can deadlock because _clean_waitter awaits a _close task that now also acquires _connect_lock; consider moving _clean_waitter outside the async with _connect_lock or adjusting _close so it doesn't contend for the same lock when awaited via _close_waitter.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `MCPClient._connect`, calling `await self._clean_waitter()` inside the `_connect_lock` can deadlock because `_clean_waitter` awaits a `_close` task that now also acquires `_connect_lock`; consider moving `_clean_waitter` outside the `async with _connect_lock` or adjusting `_close` so it doesn't contend for the same lock when awaited via `_close_waitter`.

## Individual Comments

### Comment 1
<location path="src/amrita_core/tools/mcp.py" line_range="109-113" />
<code_context>
             await self._close()

     async def _connect(self, update_tools: bool = False):
-        """Connect to MCP Server
+        """Connect to MCP Server (idempotent, safe for concurrent calls)
         Args:
             update_tools (bool, optional): whether to update the tool list. Defaults to False.
         """
-        await self._clean_waitter()
-        if self.mcp_client is not None:
-            raise RuntimeError("MCP Server is already connected!")
-
</code_context>
<issue_to_address>
**issue (bug_risk):** Update-tools path is ignored if a connection already exists, which may surprise callers.

Previously, `_connect` raised if already connected, so callers wouldn’t expect tools to remain stale. Now, if another coroutine connects first, a later call with `update_tools=True` returns early and `self.tools` is never refreshed. If reloading tools on an open connection is expected, consider honoring `update_tools` even when `self.mcp_client` is set (e.g., refresh tools under the lock or separate connect vs. tool-refresh logic). If not, clarify (via docs or assertions) that `update_tools` only applies on the initial connection to avoid subtle staleness issues.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/amrita_core/tools/mcp.py
@JohnRichard4096 JohnRichard4096 merged commit f395d51 into main Jul 3, 2026
9 checks passed
@JohnRichard4096 JohnRichard4096 deleted the fix branch July 3, 2026 14:24
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