# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.connection_test_result import ConnectionTestResult
from ..types.mcp_configuration_list_response import McpConfigurationListResponse
from ..types.mcp_configuration_response import McpConfigurationResponse

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawMcpConfigurationsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def list_mcp_configurations(
        self,
        *,
        organization_id: str,
        type: typing.Optional[str] = None,
        is_active: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[McpConfigurationListResponse]:
        """
        List MCP configurations for an organization.

        Returns configurations accessible to the current user within the specified organization.

        Parameters
        ----------
        organization_id : str
            Organization ID

        type : typing.Optional[str]
            Filter by type: custom, streamline, personal_connector

        is_active : typing.Optional[bool]
            Filter by active status

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[McpConfigurationListResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/mcp-configurations",
            method="GET",
            params={
                "organization_id": organization_id,
                "type": type,
                "is_active": is_active,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    McpConfigurationListResponse,
                    parse_obj_as(
                        type_=McpConfigurationListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def create_mcp_configuration(
        self,
        *,
        name: str,
        organization_id: str,
        server_url: str,
        transport_type: str,
        auth_type: str,
        credentials: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        tool_configuration: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[McpConfigurationResponse]:
        """
        Create a new custom MCP configuration.

        Allows users to configure custom MCP servers with encrypted credentials.

        Parameters
        ----------
        name : str
            Display name

        organization_id : str
            Organization ID

        server_url : str
            HTTPS URL to MCP server

        transport_type : str
            Transport type: 'sse' or 'streamable_http'

        auth_type : str
            Authentication type: 'none', 'api_key', 'bearer_token', 'oauth'

        credentials : typing.Optional[typing.Dict[str, typing.Any]]
            Authentication credentials (will be encrypted)

        tool_configuration : typing.Optional[typing.Dict[str, typing.Any]]
            Tool enablement configuration

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[McpConfigurationResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/mcp-configurations",
            method="POST",
            json={
                "name": name,
                "organization_id": organization_id,
                "server_url": server_url,
                "transport_type": transport_type,
                "auth_type": auth_type,
                "credentials": credentials,
                "tool_configuration": tool_configuration,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    McpConfigurationResponse,
                    parse_obj_as(
                        type_=McpConfigurationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_mcp_configuration(
        self, config_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[McpConfigurationResponse]:
        """
        Get a specific MCP configuration by ID.

        Returns the configuration if the user has access to it.

        Parameters
        ----------
        config_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[McpConfigurationResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/mcp-configurations/{jsonable_encoder(config_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    McpConfigurationResponse,
                    parse_obj_as(
                        type_=McpConfigurationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def update_mcp_configuration(
        self,
        config_id: str,
        *,
        name: typing.Optional[str] = OMIT,
        server_url: typing.Optional[str] = OMIT,
        is_active: typing.Optional[bool] = OMIT,
        credentials: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        tool_configuration: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[McpConfigurationResponse]:
        """
        Update an existing MCP configuration.

        Only the configuration owner can update it.

        Parameters
        ----------
        config_id : str

        name : typing.Optional[str]
            Display name

        server_url : typing.Optional[str]
            HTTPS URL to MCP server

        is_active : typing.Optional[bool]
            Enable/disable configuration

        credentials : typing.Optional[typing.Dict[str, typing.Any]]
            Updated credentials (will be encrypted)

        tool_configuration : typing.Optional[typing.Dict[str, typing.Any]]
            Tool enablement configuration

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[McpConfigurationResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/mcp-configurations/{jsonable_encoder(config_id)}",
            method="PUT",
            json={
                "name": name,
                "server_url": server_url,
                "is_active": is_active,
                "credentials": credentials,
                "tool_configuration": tool_configuration,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    McpConfigurationResponse,
                    parse_obj_as(
                        type_=McpConfigurationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete_mcp_configuration(
        self, config_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[None]:
        """
        Delete an MCP configuration (soft delete).

        Only the configuration owner can delete it.

        Parameters
        ----------
        config_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/mcp-configurations/{jsonable_encoder(config_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def test_mcp_connection(
        self, config_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ConnectionTestResult]:
        """
        Test connection to an MCP server.

        Verifies that the MCP server is reachable and returns available tools.

        Parameters
        ----------
        config_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ConnectionTestResult]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/mcp-configurations/{jsonable_encoder(config_id)}/test",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ConnectionTestResult,
                    parse_obj_as(
                        type_=ConnectionTestResult,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawMcpConfigurationsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list_mcp_configurations(
        self,
        *,
        organization_id: str,
        type: typing.Optional[str] = None,
        is_active: typing.Optional[bool] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[McpConfigurationListResponse]:
        """
        List MCP configurations for an organization.

        Returns configurations accessible to the current user within the specified organization.

        Parameters
        ----------
        organization_id : str
            Organization ID

        type : typing.Optional[str]
            Filter by type: custom, streamline, personal_connector

        is_active : typing.Optional[bool]
            Filter by active status

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[McpConfigurationListResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/mcp-configurations",
            method="GET",
            params={
                "organization_id": organization_id,
                "type": type,
                "is_active": is_active,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    McpConfigurationListResponse,
                    parse_obj_as(
                        type_=McpConfigurationListResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def create_mcp_configuration(
        self,
        *,
        name: str,
        organization_id: str,
        server_url: str,
        transport_type: str,
        auth_type: str,
        credentials: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        tool_configuration: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[McpConfigurationResponse]:
        """
        Create a new custom MCP configuration.

        Allows users to configure custom MCP servers with encrypted credentials.

        Parameters
        ----------
        name : str
            Display name

        organization_id : str
            Organization ID

        server_url : str
            HTTPS URL to MCP server

        transport_type : str
            Transport type: 'sse' or 'streamable_http'

        auth_type : str
            Authentication type: 'none', 'api_key', 'bearer_token', 'oauth'

        credentials : typing.Optional[typing.Dict[str, typing.Any]]
            Authentication credentials (will be encrypted)

        tool_configuration : typing.Optional[typing.Dict[str, typing.Any]]
            Tool enablement configuration

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[McpConfigurationResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/mcp-configurations",
            method="POST",
            json={
                "name": name,
                "organization_id": organization_id,
                "server_url": server_url,
                "transport_type": transport_type,
                "auth_type": auth_type,
                "credentials": credentials,
                "tool_configuration": tool_configuration,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    McpConfigurationResponse,
                    parse_obj_as(
                        type_=McpConfigurationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_mcp_configuration(
        self, config_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[McpConfigurationResponse]:
        """
        Get a specific MCP configuration by ID.

        Returns the configuration if the user has access to it.

        Parameters
        ----------
        config_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[McpConfigurationResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/mcp-configurations/{jsonable_encoder(config_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    McpConfigurationResponse,
                    parse_obj_as(
                        type_=McpConfigurationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def update_mcp_configuration(
        self,
        config_id: str,
        *,
        name: typing.Optional[str] = OMIT,
        server_url: typing.Optional[str] = OMIT,
        is_active: typing.Optional[bool] = OMIT,
        credentials: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        tool_configuration: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[McpConfigurationResponse]:
        """
        Update an existing MCP configuration.

        Only the configuration owner can update it.

        Parameters
        ----------
        config_id : str

        name : typing.Optional[str]
            Display name

        server_url : typing.Optional[str]
            HTTPS URL to MCP server

        is_active : typing.Optional[bool]
            Enable/disable configuration

        credentials : typing.Optional[typing.Dict[str, typing.Any]]
            Updated credentials (will be encrypted)

        tool_configuration : typing.Optional[typing.Dict[str, typing.Any]]
            Tool enablement configuration

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[McpConfigurationResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/mcp-configurations/{jsonable_encoder(config_id)}",
            method="PUT",
            json={
                "name": name,
                "server_url": server_url,
                "is_active": is_active,
                "credentials": credentials,
                "tool_configuration": tool_configuration,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    McpConfigurationResponse,
                    parse_obj_as(
                        type_=McpConfigurationResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete_mcp_configuration(
        self, config_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[None]:
        """
        Delete an MCP configuration (soft delete).

        Only the configuration owner can delete it.

        Parameters
        ----------
        config_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/mcp-configurations/{jsonable_encoder(config_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def test_mcp_connection(
        self, config_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ConnectionTestResult]:
        """
        Test connection to an MCP server.

        Verifies that the MCP server is reachable and returns available tools.

        Parameters
        ----------
        config_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ConnectionTestResult]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/mcp-configurations/{jsonable_encoder(config_id)}/test",
            method="POST",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ConnectionTestResult,
                    parse_obj_as(
                        type_=ConnectionTestResult,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
