Skip to content

HTTPMCPClient

🛈 DocStrings

High-level MCP protocol client for connecting to external servers via HTTP.

Source code in src/mcp_server_llmling/http_client.py
class HTTPMCPClient:
    """High-level MCP protocol client for connecting to external servers via HTTP."""

    def __init__(self, config: HTTPClientConfig) -> None:
        """Initialize client with configuration.

        Args:
            config: Client configuration including server URL
        """
        self.config = config
        self._session: ClientSession | None = None
        self._context_manager = streamablehttp_client(
            url=self.config.server_url,
            headers=self.config.headers,
            timeout=self.config.timeout,
        )

    async def start(self) -> None:
        """Connect to server and perform handshake."""
        try:
            # Connect via streamablehttp_client and get streams

            streams_and_callback = await self._context_manager.__aenter__()
            read_stream, write_stream, _get_session_id = streams_and_callback

            info = Implementation(name=self.config.client_name, version=self.config.client_version)
            self._session = ClientSession(read_stream, write_stream, client_info=info)
            await self._session.__aenter__()
            result = await self._session.initialize()
            msg = "Connected to MCP server at %s (protocol version %s)"
            logger.info(msg, self.config.server_url, result.protocolVersion)
            if result.protocolVersion != self.config.protocol_version:
                msg = "Server negotiated MCP protocol version %s (expected %s)"
                logger.warning(msg, result.protocolVersion, self.config.protocol_version)
        except Exception as exc:
            # Clean up on failure
            try:
                await self._context_manager.__aexit__(type(exc), exc, exc.__traceback__)
            except Exception:
                logger.exception("Error during cleanup after connection failure")
            msg = "Failed to connect to server"
            raise McpConnectionError(msg) from exc

    async def close(self) -> None:
        """Close connection to server."""
        if self._session:
            try:
                await self._session.__aexit__(None, None, None)
            except Exception:
                logger.exception("Error closing session")
            finally:
                self._session = None

        try:
            await self._context_manager.__aexit__(None, None, None)
        except Exception:
            logger.exception("Error closing context manager")

    @property
    def session(self) -> ClientSession:
        """Get active session."""
        if not self._session:
            msg = "Not connected to server"
            raise RuntimeError(msg)
        return self._session

    async def list_tools(self) -> Sequence[Tool]:
        """List available tools."""
        try:
            result = await self.session.list_tools()
        except Exception as exc:
            msg = "Failed to list tools"
            raise ToolError(msg) from exc
        else:
            return result.tools

    async def call_tool(
        self,
        name: str,
        arguments: dict[str, Any] | None = None,
        *,
        timeout: float | None = None,
    ) -> Any:
        """Call a tool with given arguments."""
        timeout = timeout or self.config.timeout
        try:
            async with asyncio.timeout(timeout):
                result = await self.session.call_tool(name, arguments)
                return result.content
        except TimeoutError as exc:
            msg = f"Tool execution timed out after {timeout}s"
            raise ToolError(msg) from exc
        except Exception as exc:
            msg = f"Tool execution failed: {exc}"
            raise ToolError(msg) from exc

    async def list_resources(self) -> Sequence[Resource]:
        """List available resources."""
        try:
            result = await self.session.list_resources()
        except Exception as exc:
            msg = "Failed to list resources"
            raise MCPClientError(msg) from exc
        else:
            return result.resources

    async def list_prompts(self) -> Sequence[Prompt]:
        """List available prompts."""
        try:
            result = await self.session.list_prompts()
        except Exception as exc:
            msg = "Failed to list prompts"
            raise MCPClientError(msg) from exc
        else:
            return result.prompts

    async def subscribe_resource(self, uri: str | AnyUrl) -> None:
        """Subscribe to resource updates."""
        try:
            if isinstance(uri, str):
                uri = AnyUrl(uri)
            await self.session.subscribe_resource(uri)
        except Exception as exc:
            msg = "Failed to subscribe to resource"
            raise MCPClientError(msg) from exc

    async def unsubscribe_resource(self, uri: str | AnyUrl) -> None:
        """Unsubscribe from resource updates."""
        try:
            if isinstance(uri, str):
                uri = AnyUrl(uri)
            await self.session.unsubscribe_resource(uri)
        except Exception as exc:
            msg = "Failed to unsubscribe from resource"
            raise MCPClientError(msg) from exc

    async def __aenter__(self) -> Self:
        """Async context manager entry."""
        await self.start()
        return self

    async def __aexit__(self, *exc: object) -> None:
        """Async context manager exit."""
        await self.close()

session property

session: ClientSession

Get active session.

__aenter__ async

__aenter__() -> Self

Async context manager entry.

Source code in src/mcp_server_llmling/http_client.py
async def __aenter__(self) -> Self:
    """Async context manager entry."""
    await self.start()
    return self

__aexit__ async

__aexit__(*exc: object) -> None

Async context manager exit.

Source code in src/mcp_server_llmling/http_client.py
async def __aexit__(self, *exc: object) -> None:
    """Async context manager exit."""
    await self.close()

__init__

__init__(config: HTTPClientConfig) -> None

Initialize client with configuration.

Parameters:

Name Type Description Default
config HTTPClientConfig

Client configuration including server URL

required
Source code in src/mcp_server_llmling/http_client.py
def __init__(self, config: HTTPClientConfig) -> None:
    """Initialize client with configuration.

    Args:
        config: Client configuration including server URL
    """
    self.config = config
    self._session: ClientSession | None = None
    self._context_manager = streamablehttp_client(
        url=self.config.server_url,
        headers=self.config.headers,
        timeout=self.config.timeout,
    )

call_tool async

call_tool(
    name: str, arguments: dict[str, Any] | None = None, *, timeout: float | None = None
) -> Any

Call a tool with given arguments.

Source code in src/mcp_server_llmling/http_client.py
async def call_tool(
    self,
    name: str,
    arguments: dict[str, Any] | None = None,
    *,
    timeout: float | None = None,
) -> Any:
    """Call a tool with given arguments."""
    timeout = timeout or self.config.timeout
    try:
        async with asyncio.timeout(timeout):
            result = await self.session.call_tool(name, arguments)
            return result.content
    except TimeoutError as exc:
        msg = f"Tool execution timed out after {timeout}s"
        raise ToolError(msg) from exc
    except Exception as exc:
        msg = f"Tool execution failed: {exc}"
        raise ToolError(msg) from exc

close async

close() -> None

Close connection to server.

Source code in src/mcp_server_llmling/http_client.py
async def close(self) -> None:
    """Close connection to server."""
    if self._session:
        try:
            await self._session.__aexit__(None, None, None)
        except Exception:
            logger.exception("Error closing session")
        finally:
            self._session = None

    try:
        await self._context_manager.__aexit__(None, None, None)
    except Exception:
        logger.exception("Error closing context manager")

list_prompts async

list_prompts() -> Sequence[Prompt]

List available prompts.

Source code in src/mcp_server_llmling/http_client.py
async def list_prompts(self) -> Sequence[Prompt]:
    """List available prompts."""
    try:
        result = await self.session.list_prompts()
    except Exception as exc:
        msg = "Failed to list prompts"
        raise MCPClientError(msg) from exc
    else:
        return result.prompts

list_resources async

list_resources() -> Sequence[Resource]

List available resources.

Source code in src/mcp_server_llmling/http_client.py
async def list_resources(self) -> Sequence[Resource]:
    """List available resources."""
    try:
        result = await self.session.list_resources()
    except Exception as exc:
        msg = "Failed to list resources"
        raise MCPClientError(msg) from exc
    else:
        return result.resources

list_tools async

list_tools() -> Sequence[Tool]

List available tools.

Source code in src/mcp_server_llmling/http_client.py
async def list_tools(self) -> Sequence[Tool]:
    """List available tools."""
    try:
        result = await self.session.list_tools()
    except Exception as exc:
        msg = "Failed to list tools"
        raise ToolError(msg) from exc
    else:
        return result.tools

start async

start() -> None

Connect to server and perform handshake.

Source code in src/mcp_server_llmling/http_client.py
async def start(self) -> None:
    """Connect to server and perform handshake."""
    try:
        # Connect via streamablehttp_client and get streams

        streams_and_callback = await self._context_manager.__aenter__()
        read_stream, write_stream, _get_session_id = streams_and_callback

        info = Implementation(name=self.config.client_name, version=self.config.client_version)
        self._session = ClientSession(read_stream, write_stream, client_info=info)
        await self._session.__aenter__()
        result = await self._session.initialize()
        msg = "Connected to MCP server at %s (protocol version %s)"
        logger.info(msg, self.config.server_url, result.protocolVersion)
        if result.protocolVersion != self.config.protocol_version:
            msg = "Server negotiated MCP protocol version %s (expected %s)"
            logger.warning(msg, result.protocolVersion, self.config.protocol_version)
    except Exception as exc:
        # Clean up on failure
        try:
            await self._context_manager.__aexit__(type(exc), exc, exc.__traceback__)
        except Exception:
            logger.exception("Error during cleanup after connection failure")
        msg = "Failed to connect to server"
        raise McpConnectionError(msg) from exc

subscribe_resource async

subscribe_resource(uri: str | AnyUrl) -> None

Subscribe to resource updates.

Source code in src/mcp_server_llmling/http_client.py
async def subscribe_resource(self, uri: str | AnyUrl) -> None:
    """Subscribe to resource updates."""
    try:
        if isinstance(uri, str):
            uri = AnyUrl(uri)
        await self.session.subscribe_resource(uri)
    except Exception as exc:
        msg = "Failed to subscribe to resource"
        raise MCPClientError(msg) from exc

unsubscribe_resource async

unsubscribe_resource(uri: str | AnyUrl) -> None

Unsubscribe from resource updates.

Source code in src/mcp_server_llmling/http_client.py
async def unsubscribe_resource(self, uri: str | AnyUrl) -> None:
    """Unsubscribe from resource updates."""
    try:
        if isinstance(uri, str):
            uri = AnyUrl(uri)
        await self.session.unsubscribe_resource(uri)
    except Exception as exc:
        msg = "Failed to unsubscribe from resource"
        raise MCPClientError(msg) from exc

:fa-brands-github: Show source on GitHub