Skip to content

Fix MCP client double initialize in config flow#171636

Draft
cskujawa wants to merge 1 commit into
home-assistant:devfrom
cskujawa:mcp-fix-double-initialize
Draft

Fix MCP client double initialize in config flow#171636
cskujawa wants to merge 1 commit into
home-assistant:devfrom
cskujawa:mcp-fix-double-initialize

Conversation

@cskujawa
Copy link
Copy Markdown

Proposed change

mcp_client is an @asynccontextmanager that opens the MCP transport and calls session.initialize() before yielding the session. validate_input in config_flow.py then called session.initialize() a second time on the already-initialized session in order to obtain the InitializeResult (needed for response.capabilities.tools and response.serverInfo.name).

MCP servers that correctly implement the spec reject the second initialize POST which carries the existing mcp-session-id header, with 400 -32600 "Invalid Request: Server already initialized". This surfaces to the user as "Cannot connect to MCP server".

Minimal curl reproduction (against any compliant MCP server):

# Step 1 — fresh initialize: succeeds, server returns a session-id
curl -si -X POST http://<server>/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","method":"initialize","id":1,"params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}'
# → 200 OK, mcp-session-id: <uuid>

# Step 2 — second initialize on the same session: rejected
curl -si -X POST http://<server>/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "mcp-session-id: <uuid>" \
  -d '{"jsonrpc":"2.0","method":"initialize","id":2,"params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}'
# → 400, {"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid Request: Server
already initialized"},"id":null}

Fix: Make mcp_client capture the InitializeResult and yield (session, result) instead of session alone. Update the two non-config-flow callers (ModelContextProtocolTool.async_call and _async_update_data) to unpack (session, _). Update validate_input to unpack (_session, response) from the context manager and drop the second initialize() call. The response object is unchanged - response.capabilities.tools and response.serverInfo.name are still used on the lines that follow.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Deprecation (breaking change to happen in the future)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

  • No manifest.json, dependency, or requirements_all.txt change is needed.
  • No documentation PR needed - no user-facing behavior change.

Checklist

  • I understand the code I am submitting and can explain how it works.
  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • I have followed the perfect PR recommendations
  • The code has been formatted using Ruff (ruff format homeassistant tests)
  • Tests have been added to verify that the new code works. (regression test test_initialize_called_once_in_config_flow asserts initialize() is called exactly once during the config flow)
  • Any generated code has been carefully reviewed for correctness and compliance with project standards.

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • For the updated dependencies a diff between library versions and ideally a link to the changelog/release notes is added to the PR description.

To help with the load of incoming pull requests:

@cskujawa cskujawa requested a review from allenporter as a code owner May 20, 2026 20:53
Copilot AI review requested due to automatic review settings May 20, 2026 20:53
Copy link
Copy Markdown
Contributor

@home-assistant home-assistant Bot left a comment

Choose a reason for hiding this comment

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

Hi @cskujawa

It seems you haven't yet signed a CLA. Please do so here.

Once you do that we will be able to review and accept this pull request.

Thanks!

@home-assistant home-assistant Bot marked this pull request as draft May 20, 2026 20:53
@home-assistant
Copy link
Copy Markdown
Contributor

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@home-assistant
Copy link
Copy Markdown
Contributor

Hey there @allenporter, mind taking a look at this pull request as it has been labeled with an integration (mcp) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of mcp can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant mark-draft Mark the pull request as draft.
  • @home-assistant ready-for-review Remove the draft status from the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign mcp Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant update-branch Update the pull request branch with the base branch.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component, problem in config, problem in device, feature-request) on the pull request.

Copy link
Copy Markdown
Contributor

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

Note

Copilot was unable to run its full agentic suite in this review.

Fixes a regression where MCP servers reject a second initialize() call during config flow by ensuring initialization happens exactly once inside the mcp_client context manager.

Changes:

  • Update mcp_client to call session.initialize() internally and yield both the session and InitializeResult.
  • Refactor coordinator and config flow call sites to unpack (session, initialize_result) and avoid re-initializing.
  • Add a regression test asserting initialize() is only called once during config flow.

Reviewed changes

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

File Description
tests/components/mcp/test_config_flow.py Adds regression coverage for the double-initialize() config flow bug.
homeassistant/components/mcp/coordinator.py Changes mcp_client to yield (ClientSession, InitializeResult) and updates existing call sites.
homeassistant/components/mcp/config_flow.py Stops calling initialize() directly and uses the initialization result from mcp_client.

Comment on lines +42 to 45
) -> AsyncGenerator[tuple[ClientSession, InitializeResult]]:
"""Create an MCP client.

This is an asynccontext manager that exists to wrap other async context managers
url: str,
token_manager: TokenManager | None = None,
) -> AsyncGenerator[ClientSession]:
) -> AsyncGenerator[tuple[ClientSession, InitializeResult]]:
Comment on lines +61 to +62
result = await session.initialize()
yield session, result
Comment on lines +154 to +158
async with mcp_client(hass, url, token_manager=token_manager) as (
_session,
response,
):
pass
Comment on lines +133 to +135
response = Mock()
response.serverInfo.name = TEST_API_NAME
mock_mcp_client.return_value.initialize.return_value = response
@allenporter
Copy link
Copy Markdown
Contributor

Thank you for the contribution. Please address or respond to the co-pilot feedback and mark as Ready for review when ready. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants