Skip to content

[BUG] MCPClient.__exit__ type annotations don't match context-manager protocol #2247

@cogwirrel

Description

@cogwirrel

Checks

  • I have updated to the latest minor and patch version of Strands
  • I have checked the documentation and this is not expected behavior
  • I have searched issues and there are no duplicates of my issue

Strands Version

1.38.0

Python Version

3.12

Operating System

Any

Installation Method

pip

Steps to Reproduce

from strands.tools.mcp.mcp_client import MCPClient

client = MCPClient(lambda: streamablehttp_client("http://localhost:8080/mcp"))
with client:
    pass

Run ty check (or any strict type checker).

Expected Behavior

No type errors — MCPClient should be a valid context manager per the typing protocol.

Actual Behavior

error[invalid-context-manager]: Object of type `MCPClient` cannot be used with `with` because it does not correctly implement `__exit__`

Additional Context

Runtime behavior is correct. The issue is only in the type annotations on __exit__ and stop() in mcp_client.py.

Possible Solution

Fix the parameter types to match the context-manager protocol:

-    def __exit__(self, exc_type: BaseException, exc_val: BaseException, exc_tb: TracebackType) -> None:
+    def __exit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) -> None:

Apply the same type[BaseException] | None fix to exc_type in stop().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions