
    9i.                         S r SSKJrJrJr  SSKrSSKJr  SSKJ	r	  SSK
Jr  \" 5       rSr " S S	\5      r " S
 S\5      r " S S\5      r " S S\5      rg)z
MCP (Model Context Protocol) API interface for ModelScope Hub.

This module provides a simple interface to interact with
ModelScope MCP plaza (https://www.modelscope.cn/mcp).
    )AnyDictOptionalN)HubApi)raise_for_http_status)
get_loggerz/openapi/v1/mcp/serversc                       \ rS rSrSrSrg)MCPApiError   z"Base exception for MCP API errors. N__name__
__module____qualname____firstlineno____doc____static_attributes__r       V/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/hub/mcp_api.pyr
   r
      s    ,r   r
   c                       \ rS rSrSrSrg)MCPApiRequestError   z,Exception raised when MCP API request fails.r   Nr   r   r   r   r   r      s    6r   r   c                       \ rS rSrSrSrg)MCPApiResponseError!   z2Exception raised when MCP API response is invalid.r   Nr   r   r   r   r   r   !   s    <r   r   c                   <  ^  \ rS rSrSrSS\\   SS4U 4S jjjr\S\	R                  S\\\4   4S j5       r\S	\S\4S
 j5       r    SS\\   S\\\\4      S\\   S\\   S\\\4   4
S jjr SS\S\\\4   4S jjr SS	\S\\   S\\\4   4S jjrSrU =r$ )MCPApi&   a=  
MCP (Model Context Protocol) API interface class.

This class provides interfaces to interact with ModelScope MCP servers,
such as to list, deploy and manage MCP servers.

Note: MCPApi inherits login() from HubApi for authentication.
Different methods have different token requirements - see individual method docs.
Nendpointreturnc                 P   > [         TU ]  US9  U R                  [        -   U l        g)zs
Initialize MCP API.

Args:
    endpoint: The modelscope server address. Defaults to None (uses default endpoint).
)r   N)super__init__r   MCP_API_PATHmcp_base_url)selfr   	__class__s     r   r#   MCPApi.__init__1   s&     	(+ MML8r   rc                 &    U R                  5       nUR                  S0 5      $ ! [        R                  R                   aN  n[        R                  SU 35        [        R                  SU R                   35        [        SU 35      UeSnAff = f)z
Handle HTTP response with unified error handling and JSON parsing.

Args:
    r: requests Response object

Returns:
    Parsed response data dict

Raises:
    MCPApiResponseError: If JSON parsing fails
zJSON parsing failed: zResponse content: zInvalid JSON response: Ndata)	jsonrequests
exceptionsJSONDecodeErrorloggererrortextr   get)r)   respes      r   _handle_responseMCPApi._handle_response<   s    	L668D xx## ""22 	LLL045LL-affX67%(?s&CD!K	Ls   $ BA	BB	server_idc                 <    SU ;   a  U R                  SS5      S   $ U $ )z#Extract server name from server ID./   )split)r8   s    r   _get_server_name_from_idMCPApi._get_server_name_from_idS   s(     )??3*1--r   tokenfiltertotal_countsearchc           	         Ub  US:  d  US:  a  [        S5      eU=(       d    0 SUUS.n U R                  U5      nU R                  R                  U R                  U R                  U R                  5      UUS9n[        U5        U R                  U5      n	U	R                  S	/ 5      n
U
 Vs/ s H9  nUR                  S
S5      UR                  SS5      UR                  SS5      S.PM;     nnU	R                  SS5      US.$ ! [        R                  R                   a*  n[        R                  SU5        [        SU 35      UeSnAff = fs  snf )a  
List available MCP servers, if (optional) token is presented, this would return private MCP servers as well.

Args:
    token: Optional access token for authentication
    filter: Optional filters to apply to the search
        - 'category': str, server category, e.g. 'communication'
        - 'tag': str, server tag, e.g. 'social-media'
        - 'is_hosted': bool, server is hosted
        When all three are passed in, the intersection is taken.
    total_count: Number of servers to return, max 100, default 20
    search: Optional search query string,e.g. Chinese service name, English service name, author/owner username
    You can combine `filter` and `search` to retrieve desired MCP servers.

Returns:
    Dict containing:
        - total_count: Total number of servers
        - servers: List of server dictionaries with name, id, description

Raises:
    MCPApiRequestError: If API request fails (network, server errors)
    MCPApiResponseError: If response format is invalid or JSON parsing fails

Authentication:
    Optional, only required if you wish to retrieve private MCP servers.
    You may leverage the token parameter for one-time authentication, or use api.login()

Returns:
    {
        'total_count': 20,
        'servers': [
            {'name': 'ServerA', 'id': '@demo/ServerA', 'description': 'This is a demo server for xxx.'},
            {'name': 'ServerB', 'id': '@demo/ServerB', 'description': 'This is another demo server.'},
            ...
        ]
    }
Nr;   d   z%total_count must be between 1 and 100)r@   page_number	page_sizerB   )urlheadersr,   cookieszFailed to get MCP servers: %szFailed to get MCP servers: mcp_server_listname iddescription)rK   rM   rN   rA   r   rA   servers)
ValueErrorget_cookiessessionputr%   builder_headersrH   r   r-   r.   RequestExceptionr0   r1   r   r6   r3   )r&   r?   r@   rA   rB   bodyrI   r)   r5   r+   rJ   itemmcp_config_lists                r   list_mcp_serversMCPApi.list_mcp_serversZ   sq   V +/[35FDEE l$	

	O&&u-G  %%,,T\\:	 ! !A
 "!$
 $$Q'((#4b9
 &	' &d HHVR(((4$88M26
 &	 	 '  88M15&
 	
 ""33 	OLL8!<$'B1#%FGQN	O's   AD .A EE#%EEc           	         U R                    S3nU R                  U R                  5      n U R                  USS9nU R                  R                  X#US9n[        U5        [        R                  SUR                   35        U R                  U5      nUR                  S/ 5      n/ n	U H  n
0 nU
R                  S	S
5      US	'   U
R                  SS
5      US'   U
R                  SS
5      US'   / US'   U
R                  S/ 5       HK  nUS   R!                  UR                  S5      R#                  S5      S   UR                  SS
5      S.5        MM     U	R!                  U5        M     UR                  SS5      U	S.$ ! [        R                  R                   a,  n[        R                  SU 35        [        SU 35      UeSnAff = f)aQ  
Get list of operational MCP servers that have been triggered hosting service by the user.

Returns:
    Dict containing:
        - total_counts: Total number of operational servers
        - servers: List of server info with name, id, description

Raises:
    MCPApiRequestError: If authentication fails or API request fails
    MCPApiResponseError: If response format is invalid or JSON parsing fails

Returns:
    {
        'total_count': 10,
        'servers': [
            {
                'name': 'ServerA',
                "id": "@Group1/ServerA",
                'description': 'This is a demo server for xxx.'
                'mcp_servers': [
                    {
                        'type': 'sse',
                        'url': 'https://mcp.api-inference.modelscope.net/{uuid}/sse'
                    },
                    {
                        'type': 'streamable_http',
                        'url': 'https://mcp.api-inference.modelscope.net/{uuid}/streamable_http'
                    },
                    ...
                ]
            },
            ...
        ]
    }
z/operationalT)access_tokencookies_required)rH   rI   z'Failed to get operational MCP servers: NzResponse status code: rJ   rK   rL   rM   rN   mcp_serversoperational_urlsrG   r:   typerG   rA   r   rO   )r%   rU   rH   rR   rS   r3   r   r-   r.   rV   r0   r1   r   debugstatus_coder6   appendr<   )r&   r?   rG   rH   rI   r)   r5   r+   rJ   rY   rX   
mcp_configoperational_urls                r   list_operational_mcp_servers#MCPApi.list_operational_mcp_servers   s   L ""#<0&&t||4	F&&"T ' ;G  w GA!!$ 	-amm_=>$$Q'((#4b9#DJ!%&"!5Jv#xxb1Jt(,(CJ}%(*J}%#'88,>#C=)00#''.44S9"=#''r2	2  $D "":. $  88M15&
 	
3 ""33 	FLLB1#FG$9!=?DEF	Fs   5E> >G'GGc                 f   U(       d  [        S5      eU R                   SU 3nU R                  U R                  5      n U R	                  U5      nU R
                  R                  UUSS0US9n[        U5        U R                  U5      nUR                  S	S
5      UR                  SS
5      UR                  SS
5      S.n	UR                  SS
5      n[        R!                  U5      n
UR                  S/ 5      n/ nU
(       aW  U(       aP  U HJ  nUR                  S5      R#                  S5      S   UR                  SS
5      S.nUR%                  U5        ML     XS'   U	$ ! [        R                  R                   a2  n[        R                  SU SU 35        [        SU SU 35      UeSnAff = f)aM  
Get detailed information for a specific MCP Server,
a valid token shall be provided if the MCP server is private.

Args:
    server_id: MCP server ID (e.g., "@amap/amap-maps")
    token: Optional access token for authentication

Returns:
    Dict containing:
        - name: Server name
        - description: Server description
        - id: Server ID
        - service_config: Connection configuration with type and url

Raises:
    ValueError: If server_id is empty or None
    MCPApiRequestError: If API request fails or server not found
    MCPApiResponseError: If response format is invalid or JSON parsing fails

Returns:
    {
        'name': 'ServerA',
        'description': 'This is a demo server for xxx.',
        'id': '@demo/serverA',
        'servers': [
            {
                'type': 'sse',
                'url': 'https://mcp.api-inference.modelscope.net/{uuid}/sse'
            },
            {
                'type': 'streamable_http',
                'url': 'https://mcp.api-inference.modelscope.net/{uuid}/streamable_http'
            }
            ...
        ]
    }
zserver_id cannot be emptyr:   get_operational_urlT)rH   paramsrI   zFailed to get MCP server z: NrK   rL   rN   rM   )rK   rN   rM   r`   rG   ra   rb   rP   )rQ   r%   rU   rH   rR   rS   r3   r   r-   r.   rV   r0   r1   r   r6   r   r=   r<   rf   )r&   r8   r?   rG   rH   rI   r)   r5   r+   resultserver_namer`   rY   rh   rg   s                  r   get_mcp_serverMCPApi.get_mcp_server   s   R 899""#1YK0&&t||4	E&&u-G  - ! !A "!$ $$Q' HHVR(88M26((4$
 HHT2&	55i@88$6;+#3+//6<<SA"E*..ub9
  &&z2 $4 ,y7 ""33 	ELL4YKr!EF$+I;b<>CDE	Es    :E   F0>-F++F0)r%   )N)NN   rL   )r   r   r   r   r   r   strr#   staticmethodr-   Responser   r   r6   r=   intrZ   ri   rp   r   __classcell__)r'   s   @r   r   r   &   s=   	9# 	9$ 	9 	9 $H-- $$sCx. $ $, C C   15<@6813	L
 (L
!)$sCx.!9L
 '/smL
 "*#	L
 9=S#X	L
^ 37J
,/J
;?S>J
\ /3S"%S&smS7;CH~S Sr   r   )r   typingr   r   r   r-   modelscope.hub.apir   modelscope.hub.errorsr   modelscope.utils.loggerr   r0   r$   	Exceptionr
   r   r   r   r   r   r   <module>r}      s`    ' &  % 7 . 
 )	) 	
	 	
	+ 	
aV ar   