o
    i,                     @  sl  d Z ddlmZ ddlZddlZddlmZ ddlmZm	Z	m
Z
mZmZ ddlmZ ddlZddlmZmZmZmZmZ ddlmZmZ dd	lmZ dd
lmZ erdddlmZmZm Z m!Z! ddl"m#Z# d*ddZ$G dd deZ%G dd deZ&G dd de%e&Z'G dd deZ(G dd de%e(Z)e'e)B Z*e&e(B Z+e*e+B Z,G dd deZ-G dd  d e-Z.d+d(d)Z/dS ),a  Canonical MCP Configuration Format.

This module defines the standard configuration format for Model Context Protocol (MCP) servers.
It provides a client-agnostic, extensible format that can be used across all MCP implementations.

The configuration format supports both stdio and remote (HTTP/SSE) transports, with comprehensive
field definitions for server metadata, authentication, and execution parameters.

Example configuration:
```json
{
    "mcpServers": {
        "my-server": {
            "command": "npx",
            "args": ["-y", "@my/mcp-server"],
            "env": {"API_KEY": "secret"},
            "timeout": 30000,
            "description": "My MCP server"
        }
    }
}
```
    )annotationsN)Path)TYPE_CHECKING	AnnotatedAnyLiteralcast)urlparse)AnyUrl	BaseModel
ConfigDictFieldmodel_validator)Selfoverride)ToolTransformConfig)FastMCPBaseModel)ClientTransportSSETransportStdioTransportStreamableHttpTransportFastMCPurlstr | AnyUrlreturnLiteral['http', 'sse']c                 C  sB   t | } | dstd|  t| }|j}td|rdS dS )zB
    Infer the appropriate transport type from the given URL.
    httpzInvalid URL: z/sse(/|\?|&|$)sse)str
startswith
ValueErrorr	   pathresearch)r   
parsed_urlr"    r&   X/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/mcp_config.pyinfer_transport_type_from_url8   s   
r(   c                      sn   e Zd ZU dZedZded< 	 edddZded	< edd
dZded< 		dd fddZ	dddZ
  ZS )_TransformingMCPServerMixinzAA mixin that enables wrapping an MCP Server with tool transforms..zdict[str, ToolTransformConfig]toolsNz!The tags to include in the proxy.)defaultdescriptionzset[str] | Noneinclude_tagsz!The tags to exclude in the proxy.exclude_tagsserver_name
str | Noneclient_namer   $tuple[FastMCP[Any], ClientTransport]c           	        sf   ddl m} ddlm} ddlm} t  }t||}|||d}|j	||| j
| j| jd}||fS )z_Turn the Transforming MCPServer into a FastMCP Server and also return the underlying transport.r   r   )Client)r   )	transportname)r5   backendtool_transformationsr-   r.   )fastmcpr   fastmcp.clientr3   fastmcp.client.transportsr   superto_transportr   as_proxyr*   r-   r.   )	selfr/   r1   r   r3   r   r4   clientwrapped_mcp_server	__class__r&   r'   #_to_server_and_underlying_transport\   s   

z?_TransformingMCPServerMixin._to_server_and_underlying_transportr   c                 C  s   ddl m} ||  d dS )z2Get the transport for the transforming MCP server.r   )FastMCPTransport)mcp)r:   rD   rC   )r>   rD   r&   r&   r'   r<   w   s   z(_TransformingMCPServerMixin.to_transport)NN)r/   r0   r1   r0   r   r2   )r   r   )__name__
__module____qualname____doc__r   r*   __annotations__r-   r.   rC   r<   __classcell__r&   r&   rA   r'   r)   L   s    
 r)   c                   @  s   e Zd ZU dZded< eedZded< eedZ	ded< d	Z
d
ed< dZded< dZded< dZded< dZded< dZded< dZded< eddZdddZdS )StdioMCPServerzMCP server configuration for stdio transport.

    This is the canonical configuration format for MCP servers using stdio transport.
    r   commanddefault_factoryz	list[str]argsdict[str, Any]envstdiozLiteral['stdio']r4   NzLiteral['stdio'] | Nonetyper0   cwd
int | Nonetimeoutr,   icondict[str, Any] | Noneauthenticationallowextrar   r   c                 C  s$   ddl m} || j| j| j| jdS )Nr   )r   )rM   rP   rR   rU   )r:   r   rM   rP   rR   rU   )r>   r   r&   r&   r'   r<      s   zStdioMCPServer.to_transport)r   r   )rF   rG   rH   rI   rJ   r   listrP   dictrR   r4   rT   rU   rW   r,   rX   rZ   r   model_configr<   r&   r&   r&   r'   rL   ~   s   
 
rL   c                   @     e Zd ZdZdS )TransformingStdioMCPServerz$A Stdio server with tool transforms.NrF   rG   rH   rI   r&   r&   r&   r'   rb          rb   c                   @  s   e Zd ZU dZded< dZded< eedZded	< dZ	d
ed< dZ
ded< dZded< dZded< dZded< dZded< edddZdddZdS )RemoteMCPServerzMCP server configuration for HTTP/SSE transport.

    This is the canonical configuration format for MCP servers using remote transports.
    r   r   Nz0Literal['http', 'streamable-http', 'sse'] | Noner4   rN   zdict[str, str]headerszAnnotated[str | Literal['oauth'] | httpx.Auth | None, Field(description='Either a string representing a Bearer token, the literal "oauth" to use OAuth authentication, or an httpx.Auth instance for custom authentication.')]authz'datetime.timedelta | int | float | Nonesse_read_timeoutrV   rW   r0   r,   rX   rY   rZ   r[   T)r]   arbitrary_types_allowedr   &StreamableHttpTransport | SSETransportc                 C  sd   ddl m}m} | jd u rt| j}n| j}|dkr&|| j| j| j| jdS || j| j| j| jdS )Nr   )r   r   r   )rf   rg   rh   )	r:   r   r   r4   r(   r   rf   rg   rh   )r>   r   r   r4   r&   r&   r'   r<      s"   
zRemoteMCPServer.to_transport)r   rj   )rF   rG   rH   rI   rJ   r4   r   r_   rf   rg   rh   rW   r,   rX   rZ   r   r`   r<   r&   r&   r&   r'   re      s    
 
re   c                   @  ra   )TransformingRemoteMCPServerz%A Remote server with tool transforms.Nrc   r&   r&   r&   r'   rk      rd   rk   c                   @  s   e Zd ZU dZeedZded< eddZ	e
dded"ddZd#ddZed$ddZd%ddZd&ddZed'dd Zd!S )(	MCPConfiga8  A configuration object for MCP Servers that conforms to the canonical MCP configuration format
    while adding additional fields for enabling FastMCP-specific features like tool transformations
    and filtering by tags.

    For an MCPConfig that is strictly canonical, see the `CanonicalMCPConfig` class.
    rN   zdict[str, MCPServerTypes]
mcpServersr[   r\   before)modevaluesrQ   r   c                 C  s.   d|vrt dd | D }|rd|iS |S )zMIf there's no mcpServers key but there are server configs at root, wrap them.rm   c                 s  s*    | ]}t |tod |v pd|v V  qdS )rM   r   N)
isinstancer_   ).0vr&   r&   r'   	<genexpr>  s
    
z1MCPConfig.wrap_servers_at_root.<locals>.<genexpr>)anyrp   )clsrp   has_serversr&   r&   r'   wrap_servers_at_root   s   zMCPConfig.wrap_servers_at_rootr5   r   serverMCPServerTypesNonec                 C     || j |< dS z,Add or update a server in the configuration.Nrm   r>   r5   ry   r&   r&   r'   
add_server  s   zMCPConfig.add_serverconfigr   c                 C  s
   |  |S )z/Parse MCP configuration from dictionary format.)model_validate)rv   r   r&   r&   r'   	from_dict  s   
zMCPConfig.from_dictc                 C  s   | j ddS )z>Convert MCPConfig to dictionary format, preserving all fields.Texclude_none)
model_dump)r>   r&   r&   r'   to_dict  s   zMCPConfig.to_dict	file_pathr   c                 C  s&   |j jddd || jdd dS )z!Write configuration to JSON file.T)parentsexist_ok   )indentN)parentmkdir
write_textmodel_dump_json)r>   r   r&   r&   r'   write_to_file  s   zMCPConfig.write_to_filec                 C  s0   |  r|   }r| |S td| )z"Load configuration from JSON file.z&No MCP servers defined in the config: )exists	read_textstripmodel_validate_jsonr!   )rv   r   contentr&   r&   r'   	from_file   s   
zMCPConfig.from_fileN)rp   rQ   r   rQ   )r5   r   ry   rz   r   r{   )r   rQ   r   r   )r   rQ   )r   r   r   r{   )r   r   r   r   )rF   rG   rH   rI   r   r_   rm   rJ   r   r`   r   classmethodrx   r   r   r   r   r   r&   r&   r&   r'   rl      s   
 



rl   c                   @  s2   e Zd ZU dZeedZded< edddZ	dS )CanonicalMCPConfigzCanonical MCP configuration format.

    This defines the standard configuration format for Model Context Protocol servers.
    The format is designed to be client-agnostic and extensible for future use cases.
    rN   z"dict[str, CanonicalMCPServerTypes]rm   r5   r   ry   CanonicalMCPServerTypesr   r{   c                 C  r|   r}   r~   r   r&   r&   r'   r   2  s   zCanonicalMCPConfig.add_serverN)r5   r   ry   r   r   r{   )
rF   rG   rH   rI   r   r_   rm   rJ   r   r   r&   r&   r&   r'   r   )  s
   
 r   r   r   r/   r   server_configr   r{   c                 C  sh   t | }|j| }r'| }|jdd}|i ||}||| n||| ||  dS )zUpdate an MCP configuration file from a server object, preserving existing fields.

    This is used for updating the mcpServer configurations of third-party tools so we do not
    worry about transforming server objects here.Tr   N)rl   r   rm   getr   r   r   r   )r   r/   r   r   existing_serverexisting_dictnew_dictmerged_configr&   r&   r'   update_config_file8  s   
	r   )r   r   r   r   )r   r   r/   r   r   r   r   r{   )0rI   
__future__r   datetimer#   pathlibr   typingr   r   r   r   r   urllib.parser	   httpxpydanticr
   r   r   r   r   typing_extensionsr   r   fastmcp.tools.tool_transformr   fastmcp.utilities.typesr   r:   r   r   r   r   fastmcp.server.serverr   r(   r)   rL   rb   re   rk   TransformingMCPServerTypesr   rz   rl   r   r   r&   r&   r&   r'   <module>   s6    
2)=6