
    Jj_                       U d Z ddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlmZ ddlmZ ddlmZmZmZmZmZ ddlmZ  ej        e          ZdZdaee         ed<    ej                    Z d	efd
Z!de"d	dfdZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*	 ddl+m,Z,m-Z- ddl.m/Z/ dZ$	 ddl0m1Z1 dZ%n# e2$ r dZ%Y nw xY w	 ddl0m3Z3 dZ4n# e2$ r dZ4Y nw xY w	 ddl5m*Z* n # e2$ r e6                    d           Y nw xY w	 ddl7m8Z8 n"# e2$ r dZ8e6                    d           Y nw xY w	 ddl5m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? dZ&n # e2$ r e6                    d           Y nw xY w	 ddl5m@Z@mAZA dZ(n # e2$ r e6                    d           Y nw xY w	 ddl5mBZBmCZCmDZDmEZE dZ'n # e2$ r e6                    d           Y nw xY wn # e2$ r e6                    d           Y nw xY wd	eFfdZG eG            Z)e$re)se6                    d            d	eFfd!ZH eH            ZIejJ        ejK        ejK        ejL        ejM        ejM        ejM        ejM        d"ZNd#ZOd$ZPd%ZQd&ZRd$ZSd'ZTd%ZU eVh d(          ZW eVh d)          ZX e
jY        d*e
jZ                  Z[ e
jY        d+          Z\d,e"d	e"fd-Z]d.ee^         d	e^fd/Z_d0e"d	e"fd1Z`d2ead	e"fd3Zb	 dd4l5mcZd n# ee$ r d5ZdY nw xY wd2ead	eFfd6Zf e
jY        d7e
jg                  d8f e
jY        d9e
jg                  d:f e
jY        d;e
jg                  d<f e
jY        d=e
jg                  d>f e
jY        d?e
jg                  d@f e
jY        dAe
jg                  dBf e
jY        dCe
jg                  dDf e
jY        dEe
jg                  dFf e
jY        dGe
jg                  dHf e
jY        dIe
jg                  dJfg
Zhde"dKe"dLe"d	ee"         fdMZidNe^dOe"d	e^fdPZjdQe"dNe^d	eke"e^f         fdRZldSe"d	e"fdTZmd	e"fdUZn G dV dWeo          Zp G dX dYeq          Zrde"dZed	e"fd[Zsde"d\e^fd]Ztd2ead	e"fd^Zuevd_fd`Zw G da db          Zxdce^de"d	e"fddZy G de df          Zz G dg dh          Z{i Z|ee"e{f         edi<    e}            Z~e}e"         edj<   i Zee"e"f         edk<   i Zee"evf         edl<   i Zee"ef         edm<   d&ZdnZde"d	dfdoZde"d	dfdpZdqed	eFfdrZdsaekedt<   d	ekfduZd2ead	eFfdvZde"d2eadwe"fdxZdyZekedz<   d2ead	eFfd{Zde"d2eadwe"fd|Z e}            Ze}ed}<   i Zee"e"f         ed~<   daeej                 ed<   daeej                 ed<    ej                    Zi Zeeve"f         ed<    e}            Ze}ed<   i Zeevevf         ed<   d	e}fdZdZeke"df         ed<   de}d	e}fdZd Zd ZddZddefdZd	e"fdZd Zdee"e^f         d	ee"e^f         fdZd	ee"e^f         fdZde"d\e^d	e{fdZde"dKe"defdZde"defdZde"defdZde"defdZde"defdZde"fdZdce^dz  d	e^fdZde"d	e"fdZdZdZde"dKe"d	e"fdZde"d	e^fdZde"d	ee^         fdZdede"d	e}e"         fdZddedeFd	eFfdZdddddZdddddZdKe"de"d	dfdZdKe"d	dfdZde"dqe{d\e^d	ee^         fdZd	ee"         fdZde"dqe{d\e^d	ee"         fdZde"d\e^d	ee"         fdZdee"e^f         d	ee"         fdZd	ee"         fdZdKe"d	eFfdZd	ee^         fdZd	ee"eek         f         fdZ ej                    Zd	eFfdZdddddeFd	e}fdZdede}d	e}fdĄZdń ZddeFd	dfdǄZd	eFfdȄZddɜdeFd	eFfd˄ZdS )a  
MCP (Model Context Protocol) Client Support

Connects to external MCP servers via stdio, HTTP/StreamableHTTP, or SSE
transport, discovers their tools, and registers them into the hermes-agent
tool registry so the agent can call them like any built-in tool.

Configuration is read from ~/.hermes/config.yaml under the ``mcp_servers`` key.
The ``mcp`` Python package is optional -- if not installed, this module is a
no-op and logs a debug message.

Example config::

    mcp_servers:
      filesystem:
        command: "npx"
        args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
        env: {}
        timeout: 120         # per-tool-call timeout in seconds (default: 300)
        connect_timeout: 60  # initial connection timeout (default: 60)
        keepalive_interval: 10  # liveness ping cadence in seconds (default:
                                # 180). Set below the server's session TTL for
                                # servers that GC idle sessions quickly (e.g.
                                # Unreal Engine editor MCP, ~15s). Floored at 5s.
      github:
        command: "npx"
        args: ["-y", "@modelcontextprotocol/server-github"]
        env:
          GITHUB_PERSONAL_ACCESS_TOKEN: "ghp_..."
        supports_parallel_tool_calls: true  # tools from this server may run concurrently
      remote_api:
        url: "https://my-mcp-server.example.com/mcp"
        headers:
          Authorization: "Bearer sk-..."
        timeout: 180
      searxng:
        url: "http://localhost:8000/sse"
        transport: sse       # use SSE transport instead of Streamable HTTP
        timeout: 180
        connect_timeout: 10
        command: "npx"
        args: ["-y", "analysis-server"]
        sampling:                    # server-initiated LLM requests
          enabled: true              # default: true
          model: "gemini-3-flash"    # override model (optional)
          max_tokens_cap: 4096       # max tokens per request
          timeout: 30                # LLM call timeout (seconds)
          max_rpm: 10                # max requests per minute
          allowed_models: []         # model whitelist (empty = all)
          max_tool_rounds: 5         # tool loop limit (0 = disable)
          log_level: "info"          # audit verbosity

Features:
    - Stdio transport (command + args) and HTTP/StreamableHTTP transport (url)
    - SSE transport (transport: sse) for MCP servers using the SSE protocol
    - Automatic reconnection with exponential backoff (up to 5 retries)
    - Environment variable filtering for stdio subprocesses (security)
    - Credential stripping in error messages returned to the LLM
    - Configurable per-server timeouts for tool calls and connections
    - Thread-safe architecture with dedicated background event loop
    - Sampling support: MCP servers can request LLM completions via
      sampling/createMessage (text and tool-use responses)
    - Parallel tool call opt-in: per-server ``supports_parallel_tool_calls``
      flag allows concurrent execution of tools from the same server

Architecture:
    A dedicated background event loop (_mcp_loop) runs in a daemon thread.
    Each MCP server runs as a long-lived asyncio Task on this loop, keeping
    its transport context alive. Tool call coroutines are scheduled onto the
    loop via ``run_coroutine_threadsafe()``.

    On shutdown, each server Task is signalled to exit its ``async with``
    block, ensuring the anyio cancel-scope cleanup happens in the *same*
    Task that opened the connection (required by anyio).

Thread safety:
    _servers and _mcp_loop/_mcp_thread are accessed from both the MCP
    background thread and caller threads.  All mutations are protected by
    _lock so the code is safe regardless of GIL presence (e.g. Python 3.13+
    free-threading).
    N)Callable)datetime)Any	CoroutineDictListOptional)urlparseg      (@_mcp_stderr_log_fhreturnc                     t           5  t          t          cddd           S 	 ddlm}   |             dz  }|                    dd           |dz  }t          |dd	d
d          }|                                 |anl# t          $ r_}t          	                    d|           	 t          t          j        dd	          an# t          $ r t          j        aY nw xY wY d}~nd}~ww xY wt          cddd           S # 1 swxY w Y   dS )a^  Return a shared append-mode file handle for MCP subprocess stderr.

    Opened once per process and reused for every stdio server.  Must have a
    real OS-level file descriptor (``fileno()``) because asyncio's subprocess
    machinery wires the child's stderr directly to that fd.  Falls back to
    ``/dev/null`` if opening the log file fails.
    Nr   )get_hermes_homelogsT)parentsexist_okzmcp-stderr.logautf-8replace   )encodingerrors	bufferingz0Failed to open MCP stderr log, using devnull: %swr   )_mcp_stderr_log_lockr   hermes_constantsr   mkdiropenfileno	Exceptionloggerdebugosdevnullsysstderr)r   log_dirlog_pathfhexcs        4/home/rurouni/.hermes/hermes-agent/tools/mcp_tool.py_get_mcp_stderr_logr,      s    
 " ")%" " " " " " " "	0888888%o''&0GMM$M666!11H hgiSTUUUBIIKKK!# 	0 	0 	0LLKSQQQ0%)"*cG%L%L%L"" 0 0 0 &)Z"""0		0 "/" " " " " " " " " " " " " " " " " "s_   C=AA>=C=>
C'C"$C C"CC"CC"C="C''	C==DDserver_namec                     t                      }	 t          j                                        d          }|                    d| d|  d           |                                 dS # t          $ r Y dS w xY w)a  Write a human-readable session marker before launching a server.

    Gives operators a way to find each server's output in the shared
    ``mcp-stderr.log`` file without needing per-line prefixes (which would
    require a pipe + reader thread and complicate shutdown).
    z%Y-%m-%d %H:%M:%Sz
===== [z] starting MCP server 'z' =====
N)r,   r   nowstrftimewriteflushr    )r-   r)   tss      r+   _write_stderr_log_headerr4      s     
		B\^^$$%899
NRNNNNNOOO





   s   AA( (
A65A6Fz
2025-03-26)ClientSessionStdioServerParameters)stdio_clientT)streamablehttp_client)streamable_http_client)LATEST_PROTOCOL_VERSIONzRmcp.types.LATEST_PROTOCOL_VERSION not available -- using fallback protocol version)
sse_clientzAmcp.client.sse.sse_client not available -- SSE transport disabled)CreateMessageResultCreateMessageResultWithTools	ErrorDataSamplingCapabilitySamplingToolsCapabilityTextContentToolUseContentz5MCP sampling types not available -- sampling disabled)ElicitRequestParamsElicitResultz;MCP elicitation types not available -- elicitation disabled)ServerNotificationToolListChangedNotificationPromptListChangedNotificationResourceListChangedNotificationzGMCP notification types not available -- dynamic tool discovery disabledz6mcp package not installed -- MCP tool support disabledc                      t           sdS 	 dt          j        t                    j        v S # t
          t          f$ r Y dS w xY w)zCheck if ClientSession accepts ``message_handler`` kwarg.

    Inspects the constructor signature for backward compatibility with older
    MCP SDK versions that don't support notification handlers.
    Fmessage_handler_MCP_AVAILABLEinspect	signaturer5   
parameters	TypeError
ValueError     r+   _check_message_handler_supportrT   	  sV      u G$5m$D$D$OOOz"   uu   + A A zKMCP SDK does not support message_handler -- dynamic tool discovery disabledc                      t           sdS 	 dt          j        t                    j        v S # t
          t          f$ r Y dS w xY w)ae  Check if ClientSession accepts the ``logging_callback`` kwarg.

    Mirrors ``_check_message_handler_support`` for backward compatibility
    with older MCP SDK versions.  Without a logging_callback, the SDK's
    default handler silently discards every ``notifications/message`` a
    server emits, so server-side diagnostics never reach Hermes' logs.
    Flogging_callbackrK   rR   rS   r+   _check_logging_callback_supportrX     sV      u!W%6}%E%E%PPPz"   uurU   )r"   infonoticewarningerrorcriticalalert	emergency,  <            >   HOMELANGPATHTERMUSERSHELLLC_ALLTMPDIR>   PROGRAMFILES(X86)COMMONPROGRAMFILES(X86)OSTMPTEMPPUBLICWINDIRAPPDATACOMSPECPATHEXTHOMEPATHUSERNAME	HOMEDRIVE
SYSTEMROOT
USERDOMAINPROGRAMDATASYSTEMDRIVEUSERPROFILECOMPUTERNAMELOCALAPPDATAPROGRAMFILESPROGRAMW6432ALLUSERSPROFILECOMMONPROGRAMFILESCOMMONPROGRAMW6432NUMBER_OF_PROCESSORSPROCESSOR_ARCHITECTUREz(?:ghp_[A-Za-z0-9_]{1,255}|sk-[A-Za-z0-9_]{1,255}|Bearer\s+\S+|token=[^\s&,;\"']{1,255}|key=[^\s&,;\"']{1,255}|API_KEY=[^\s&,;\"']{1,255}|password=[^\s&,;\"']{1,255}|secret=[^\s&,;\"']{1,255})z\$\{([^}]+)\}refc                     |                                  } |                     d          r)| t          d          d                                          } | S )a  Normalize a ``${...}`` reference body into an env-var name.

    Accepts Cursor-style ``${env:VAR}`` in addition to plain ``${VAR}`` by
    stripping a leading ``env:`` prefix. The result is the bare variable name
    to look up in the secret scope / ``os.environ``.
    zenv:N)strip
startswithlen)r   s    r+   _env_ref_namer     sJ     ))++C
~~f (#f++,,%%''JrS   user_envc                     i }t           j                                        D ]C\  }}|t          v s0|                                t
          v s|                    d          r|||<   D| r|                    |            |S )a  Build a filtered environment dict for stdio subprocesses.

    Only passes through safe baseline variables (PATH, HOME, etc.) and XDG_*
    variables from the current process environment, plus any variables
    explicitly specified by the user in the server config.

    This prevents accidentally leaking secrets like API keys, tokens, or
    credentials to MCP server subprocesses.
    XDG_)r#   environitems_SAFE_ENV_KEYSupper_SAFE_ENV_KEYS_CASE_INSENSITIVEr   update)r   envkeyvalues       r+   _build_safe_envr     s     Cj&&((  
U>!!yy{{===~~f%% > CH 

8JrS   textc                 8    t                               d|           S )zStrip credential-like patterns from error text before returning to LLM.

    Replaces tokens, keys, and other secrets with [REDACTED] to prevent
    accidental credential exposure in tool error responses.
    z
[REDACTED])_CREDENTIAL_PATTERNsubr   s    r+   _sanitize_errorr     s     ""<666rS   r*   c                 j    t          |                                           }|r|nt          |           S )aX  Return a non-empty human-readable string for *exc*.

    Some exception classes (e.g. ``anyio.ClosedResourceError``) are raised
    without a message argument, so ``str(exc)`` is ``""``.  This helper
    falls back to ``repr(exc)`` so that error messages shown to the user
    and logged to disk always carry *some* diagnostic information.
    )strr   repr)r*   r   s     r+   _exc_strr     s.     s88>>D&44T#YY&rS   )METHOD_NOT_FOUNDic                     t          | dd          }t          |dd          }|t          k    rdS t          |                                           }|sdS t          t                    |v pd|v pd|v pd|v S )	u  Return True if *exc* is a JSON-RPC ``method not found`` (-32601).

    ``ping`` is an *optional* MCP utility (spec: "optional ping mechanism").
    A server that doesn't implement it answers a ping with -32601 rather than
    an empty result. Structurally inspect ``McpError.error.code`` first, then
    fall back to a substring match so detection survives SDK version drift and
    servers that surface the condition as a plain message.

    The substring fallback matters when a server reports method-not-found
    without a structural ``-32601`` code (e.g. surfaced as a plain exception
    string). Besides the canonical "method not found", many JSON-RPC
    implementations phrase it as "Unknown method: <name>" — agentmemory's MCP
    server is one such case (#50028). Without matching that phrasing the
    ping→list_tools fallback never latches and the keepalive reconnect-loops.
    r\   NcodeTFzmethod not foundzunknown methodznot found: ping)getattr_JSONRPC_METHOD_NOT_FOUNDr   lower)r*   errr   msgs       r+   _is_method_not_found_errorr     s    " #w
%
%C3%%D(((t
c((..

C u%&&#- 	$$	$s"	$ #	rS   z)ignore\s+(all\s+)?previous\s+instructionsz8prompt override attempt ('ignore previous instructions')zyou\s+are\s+now\s+az.identity override attempt ('you are now a...')z1your\s+new\s+(task|role|instructions?)\s+(is|are)ztask override attemptzsystem\s*:\s*zsystem prompt injection attemptz <\s*(system|human|assistant)\s*>zrole tag injection attemptz'do\s+not\s+(tell|inform|mention|reveal)zconcealment instructionz(curl|wget|fetch)\s+https?://znetwork command in descriptionzbase64\.(b64decode|decodebytes)zbase64 decode referencezexec\s*\(|eval\s*\(zcode execution referencez&import\s+(subprocess|os|shutil|socket)zdangerous import reference	tool_namedescriptionc                     g }|s|S t           D ]/\  }}|                    |          r|                    |           0|r1t                              d| |d                    |          |           |S )zxScan an MCP tool description for prompt injection patterns.

    Returns a list of finding strings (empty = clean).
    uU   MCP server '%s' tool '%s': suspicious description content — %s. Description: %.200s; )_MCP_INJECTION_PATTERNSsearchappendr!   r[   join)r-   r   r   findingspatternreasons         r+   _scan_mcp_descriptionr     s    
 H 2 $ $>>+&& 	$OOF### 
"DIIh$7$7		
 	
 	
 OrS   r   	directoryc                    t          | pi           }|s|S |                    dd          }d |                    t          j                  D             }||vr|g|}|rt          j                            |          n||d<   |S )z=Prepend *directory* to env PATH if it is not already present.rg    c                     g | ]}||S rR   rR   ).0parts     r+   
<listcomp>z!_prepend_path.<locals>.<listcomp>,  s    AAAdDATAAArS   )dictgetsplitr#   pathsepr   )r   r   updatedexistingpartss        r+   _prepend_pathr   %  s    39"ooG {{62&&HAAhnnRZ88AAAE#U#05Dbjooe,,,9GFONrS   commandc           
         t           j                            t          |                                                     }t          |pi           }t           j        |vrpd|v r|d         nd}t          j        ||          }|r|}nF|dv rAt           j                            t          j	        dt           j        
                    t           j                            d          d                              }t           j        
                    |dd	|          t           j        
                    t           j                            d          d
d	|          t           j        
                    t           j        ddd	|          g}|D ]D}t           j                            |          r#t          j        |t           j                  r|} nEt           j                            |          }	|	rt          ||	          }||fS )zResolve a stdio MCP command against the exact subprocess environment.

    This primarily exists to make bare ``npx``/``npm``/``node`` commands work
    reliably even when MCP subprocesses run under a filtered PATH.
    rg   N)path>   npmnpxnodeHERMES_HOME~z.hermesr   binz.localusrlocal)r#   r   
expanduserr   r   r   sepshutilwhichgetenvr   isfileaccessX_OKdirnamer   )
r   r   resolved_commandresolved_envpath_arg	which_hithermes_home
candidates	candidatecommand_dirs
             r+   _resolve_stdio_commandr   3  s    w))#g,,*<*<*>*>??	r??L	v%%%+1\+A+A<''tL!1AAA	 	(!777',,	!27<<0B0B30G0G#S#S  K [&%9IJJRW//44hGWXX RVUGU<LMMJ (  	7>>),, 9bg1N1N '0$E'//"233K @$\;??\))rS   	mime_typec                     ddl }| pd                    dd          d                                                                         }|dv rdS |                    |          pdS )	z>Return a reasonable file extension for an MCP image MIME type.r   Nr   ;r   >   	image/jpg
image/jpegz.jpgz.png)	mimetypesr   r   r   guess_extension)r   r   
normalizeds      r+   "_mcp_image_extension_for_mime_typer   g  sn    /r((a00399;;AACCJ000v$$Z00:F:rS   c                    ddl }t          | dd          }t          | dd          }t          |pd                              dd          d                                                                         }||                    d          sdS 	 |                    |          }n;# t          t          f$ r'}t                              d	||           Y d}~dS d}~ww xY w	 dd
lm}  ||t          |                    }nY# t          $ r t                              d           Y dS t"          $ r&}t                              d|           Y d}~dS d}~ww xY wd| S )a  Cache an MCP ``ImageContent`` block to the shared image cache and
    return a ``MEDIA:<path>`` tag that Hermes gateways know how to render.

    Returns an empty string when *block* is not an image, when the base64
    payload is malformed, or when the cache helper rejects the bytes (e.g.
    non-image MIME masquerading as an image). Errors are logged, not raised:
    a single bad block shouldn't kill the tool result, and the caller will
    fall through to any text blocks that did parse.
    r   NdatamimeTyper   r   r   zimage/z&MCP image block decode failed (%s): %s)cache_image_from_bytes)extu@   MCP image caching skipped — gateway.platforms.base unavailablez MCP image block cache failed: %szMEDIA:)base64r   r   r   r   r   r   	b64decoderP   rQ   r!   r[   gateway.platforms.baser   r   ImportErrorr"   r    )	blockr   r   r   normalized_mime	raw_bytesr*   r   
image_paths	            r+   _cache_mcp_image_blockr   p  s    MMM5&$''Dz400I)/r**00a88;AACCIIKKO|?55h??|r$$T**		z"   ?RUVVVrrrrrAAAAAA++2?CC
 
 


     	WXXXrr   93???rrrrr !J   s6   B& &C7CC" D $E*	E3EEc                       e Zd ZdZdS )InvalidMcpUrlErrora  Raised when a remote MCP server's ``url`` cannot be parsed as http(s)://.

    Validated once at startup so we fail fast with a clear message instead of
    burning through the reconnect-backoff loop on every attempt.  (Ported from
    anomalyco/opencode#25019.)
    N__name__
__module____qualname____doc__rR   rS   r+   r   r     s           rS   r   c                       e Zd ZdZdS )NonMcpEndpointErroran  Raised when an HTTP MCP URL serves a non-MCP response.

    A genuine MCP Streamable-HTTP endpoint answers with ``application/json``
    or ``text/event-stream``.  Anything else on a 2xx response (typically
    ``text/html`` from a web-app root) means the configured ``url`` points at
    the wrong place.  This is non-retryable: every attempt returns the same
    page, so the reconnect-backoff loop is skipped and the server is reported
    failed immediately with an actionable message.

    Subclasses :class:`ConnectionError` so callers that only catch the broad
    class still treat it as a connection problem.
    Nr   rR   rS   r+   r  r    s           rS   r  urlc           
      0   t          |t                    s't          d|  dt          |          j                   |                                }|st          d|  d          	 t          |          }n,# t          $ r}t          d|  d|d| d          |d}~ww xY w|j        	                                dvrt          d|  d	|j        d|d          |j
        st          d|  d
|d          |j        st          d|  d|d          |S )ut  Return the URL as a string if it's a valid http(s) remote MCP URL.

    Raises :class:`InvalidMcpUrlError` otherwise with a message naming the
    offending server, so users can spot the bad entry in their config.

    Accepts:
    - ``http://host`` / ``https://host`` with optional port, path, query
    - IPv4, IPv6 (bracketed), DNS hostnames

    Rejects:
    - Non-string values (``None``, dicts, ints)
    - Missing scheme (``example.com/mcp``)
    - Non-http(s) schemes (``file://``, ``ws://``, ``stdio:`` — stdio servers
      use the ``command`` key, not ``url``)
    - Empty host (``http://``, ``https:///path``)
    zInvalid MCP URL for 'z': expected a string, got z': empty url':  ()N>   httphttpsz%': scheme must be http or https, got z': missing host (z': missing hostname ()
isinstancer   r   typer   r   r
   r    schemer   netlochostname)r-   r  strippedparsedr*   s        r+   _validate_remote_mcp_urlr    s   " c3 
 $K $ $Cyy!$ $
 
 	
 yy{{H 
 =K===
 
 	
(##    HKHHHHH#HHH
 
	 }$555 ;K ; ; -; ;-5; ; ;
 
 	
 = 
 OKOO(OOO
 
 	

 ? 
 K    
 
 	
 Os   'A7 7
B BB configc                     |                     d          }|                     d          }||dS dt          dt          dt          f fd}t          |t          t
          f          r|t          d  d	          t          |          d
k    r( ||d         d          } ||d         d          }||fS t          |          dk    rY ||d         d          } ||d         d          }|d
         }t          |t                    st          d  d          |||fS t          d  dt          |           d           ||d          }| ||d          }||fS |S )us  Resolve the ``client_cert`` / ``client_key`` config for mTLS.

    Returns whatever ``httpx``'s ``cert=`` parameter accepts, or ``None`` when
    no client certificate is configured:

      - ``None`` if neither ``client_cert`` nor ``client_key`` is set.
      - A single absolute path string if ``client_cert`` is a string and
        ``client_key`` is unset (PEM file with cert + key combined).
      - A ``(cert_path, key_path)`` tuple when both are set, or when
        ``client_cert`` is a 2-element list/tuple.
      - A ``(cert_path, key_path, password)`` tuple when ``client_cert`` is
        a 3-element list/tuple — the third element is the key passphrase.

    User paths support ``~`` expansion. Missing files raise ``FileNotFoundError``
    with a server-scoped message so the failure surfaces as a clear setup
    error rather than an opaque TLS handshake error.
    client_cert
client_keyNr   labelr   c           
         t          | t                    r|                                 s+t          d d| dt	          |           j         d          t          j                            |                                           }t          j        	                    |          st          d d| d|          |S )NMCP server 'r  z& must be a non-empty string path (got r
  z not found at )r  r   r   rQ   r  r   r#   r   r   r   FileNotFoundError)r   r  expandedr-   s      r+   _expandz%_resolve_client_cert.<locals>._expand  s    $$$ 	DJJLL 	;{ ; ;u ; ;$(JJ$7; ; ;   7%%djjll33w~~h'' 	# {    u          rS   r  zY': specify either client_cert as a list [cert, key] OR client_cert + client_key, not both   r   zclient_cert[0]r   zclient_cert[1]rc   z3': client_cert[2] (key passphrase) must be a stringz8': client_cert list form must have 2 or 3 elements (got r
  )r   r   r   r  listtuplerQ   r   )r-   r  raw_certraw_keyr  	cert_pathkey_pathpasswords   `       r+   _resolve_client_certr'    s   $ zz-((Hjj&&GGOtc # #       (T5M** 
L{ L L L   x==A-=>>Iwx{,<==Hx((x==A-=>>Iwx{,<==H{Hh,,  4; 4 4 4   x223; 3 3"%h--3 3 3
 
 	
 -00I77L118$$rS   c                    dt           dt          t                   ffddt           dt          t                   ffd |           }|r;d| d}t          j                            |          dv r|dz  }t          |          S g } |           D ]}||vr|                    |           t          d		                    |d
d                             S )zERender nested MCP connection errors into an actionable short message.currentr   c                    t          | dd           }|r|D ]} |          }|r|c S d S t          | t                    r^t          | dd           rt          | j                  S t          j        dt          |                     }|r|                    d          S dD ]9}t          | |d           }t          |t                    r |          }|r|c S :d S )N
exceptionsfilenamez$No such file or directory: '([^']+)'r   	__cause____context__)	r   r  r  r   r,  rer   groupBaseException)r)  nestedchildmissingmatchattr
nested_exc_find_missings          r+   r9  z,_format_connect_error.<locals>._find_missing9  s   ,55 	 # #'-.. #"NNN#4g011 	&w
D11 -7+,,,IEs7||TTE &{{1~~%0 	# 	#D $55J*m44 #'-
33 #"NNNtrS   c                    t          | dd           }|r'g }|D ] }|                     |                     !|S g }t          |                                           }|r|                    |           dD ]F}t          | |d           }t          |t                    r|                     |                     G|p| j        j        gS )Nr+  r-  )	r   extendr   r   r   r  r2  	__class__r   )	r)  r3  	flattenedr4  messagesr   r7  r8  _flatten_messagess	           r+   r?  z0_format_connect_error.<locals>._flatten_messagesO  s    ,55 	#%I ; ;  !2!25!9!9::::7||!!## 	"OOD!!!0 	? 	?D $55J*m44 ? 1 1* = =>>>7G-677rS   zmissing executable ''>   r   r   r   z (ensure Node.js is installed and PATH includes its bin directory, or set mcp_servers.<name>.command to an absolute path and include that directory in mcp_servers.<name>.env.PATH)r   Nrc   )
r2  r	   r   r   r#   r   basenamer   r   r   )r*   r5  messagededupeditemr9  r?  s        @@r+   _format_connect_errorrE  6  s(   } #      ,8= 8T#Y 8 8 8 8 8 8" mC  G (33337G$$(>>>AG
 w'''G!!#&& ! !wNN4   499WRaR[11222rS   r   c                     	  ||           }t          |t                    rt          j        |          s|S t	          ||          S # t
          t          t          f$ r |cY S w xY w)zCoerce a config value to a numeric type, returning *default* on failure.

    Handles string values from YAML (e.g. ``"10"`` instead of ``10``),
    non-finite floats, and values below *minimum*.
    )r  floatmathisfinitemaxrP   rQ   OverflowError)r   defaultcoerceminimumresults        r+   _safe_numericrP  v  sw    fe$$ 	T]6-B-B 	N67###z=1   s   5A A A$#A$c                       e Zd ZdZddddZdedefdZd	efd
Z	d	e
e         fdZed	efd            Zd	ee         fdZeddedefd            Zd Zd Zd	efdZd ZdS )SamplingHandlera+  Handles sampling/createMessage requests for a single MCP server.

    Each MCPServerTask that has sampling enabled creates one SamplingHandler.
    The handler is callable and passed directly to ``ClientSession`` as
    the ``sampling_callback``.  All state (rate-limit timestamps, metrics,
    tool-loop counters) lives on the instance -- no module-level globals.

    The callback is async and runs on the MCP background event loop.  The
    sync LLM call is offloaded to a thread via ``asyncio.to_thread()`` so
    it doesn't block the event loop.
    endTurn	maxTokenstoolUse)stoplength
tool_callsr-   r  c                 &   || _         t          |                    dd          dt                    | _        t          |                    dd          dt
                    | _        t          |                    dd          dt                    | _        t          |                    dd          dt          d	
          | _        |                    d          | _	        |                    dg           | _
        t          j        t          j        t          j        d}|                    t          |                    dd                                                    t          j                  | _        g | _        d	| _        d	d	d	d	d| _        d S )Nmax_rpm
   timeout   max_tokens_capi   max_tool_roundsrb   r   )rN  modelallowed_models)r"   rY   r[   	log_levelrY   )requestsr   tokens_usedtool_use_count)r-   rP  r   intrZ  rG  r\  r^  r_  model_overridera  loggingDEBUGINFOWARNINGr   r   audit_level_rate_timestamps_tool_loop_countmetrics)selfr-   r  _log_levelss       r+   __init__zSamplingHandler.__init__  sM   &$VZZ	2%>%>CHH$VZZ	2%>%>EJJ+FJJ7G,N,NPTVYZZ,JJ(!,,aa 
  
  
 %jj11$jj)92>> 'w|PWP_``&??

;//006688',
 

 .0 !$%1XYZZrS   r   c                     t          j                     }|dz
  fd| j        D             | j        dd<   t          | j                  | j        k    rdS | j                            |           dS )zASliding-window rate limiter.  Returns True if request is allowed.ra   c                      g | ]
}|k    |S rR   rR   )r   twindows     r+   r   z5SamplingHandler._check_rate_limit.<locals>.<listcomp>  s    #S#S#S!F

A


rS   NFT)timerm  r   rZ  r   )rp  r/   rv  s     @r+   _check_rate_limitz!SamplingHandler._check_rate_limit  sx    ikkr#S#S#S#St/D#S#S#Saaa t$%%555$$S)))trS   c                     | j         r| j         S |rAt          |d          r1|j        r*|j        D ]"}t          |d          r|j        r	|j        c S #dS )z3Config override > server hint > None (use default).hintsnameN)rg  hasattrrz  r{  )rp  preferenceshints      r+   _resolve_modelzSamplingHandler._resolve_model  sz     	'&& 	%7;88 	%[=N 	%#) % %4(( %TY %9$$$trS   c                     t          | d          r| j        dS t          | j        t                    r| j        n| j        g}d                    d |D                       S )z,Extract text from a ToolResultContent block.contentNr   
c              3   D   K   | ]}t          |d           |j        V  dS )r   Nr|  r   r   rD  s     r+   	<genexpr>z<SamplingHandler._extract_tool_result_text.<locals>.<genexpr>  s3      NNtf8M8MNNNNNNNrS   )r|  r  r  r   r   )r   r   s     r+   _extract_tool_result_textz)SamplingHandler._extract_tool_result_text  sc     ui(( 	EM,A2!+EM4!@!@Uu}oyyNNuNNNNNNrS   c                 H   g }|j         D ]}t          |d          r|j        n(t          |j        t
                    r|j        n|j        g}d |D             }d |D             }d |D             }|D ]3}|                    d|j        |                     |          d           4|rg }	|D ]}
|	                    t          |
ddt          |	                     d	|
j        t          |
j        t                    rt          j        |
j        d
          nt!          |
j                  dd           |j        |	d}d |D             }|rd                    |          |d<   |                    |           t|rt          |          dk    r@t          |d         d          r*|                    |j        |d         j        d           g }|D ]}t          |d          r|                    d|j        d           0t          |d          r;t          |d          r+|                    ddd|j         d|j         id           {t,                              dt1          |          j                   |r|                    |j        |d           |S )aL  Convert MCP SamplingMessages to OpenAI format.

        Uses ``msg.content_as_list`` (SDK helper) so single-block and
        list-of-blocks are handled uniformly.  Dispatches per block type
        with ``isinstance`` on real SDK types when available, falling back
        to duck-typing via ``hasattr`` for compatibility.
        content_as_listc                 2    g | ]}t          |d           |S )	toolUseIdr|  r   bs     r+   r   z5SamplingHandler._convert_messages.<locals>.<listcomp>  s'    III!K1H1HIAIIIrS   c                 r    g | ]4}t          |d           t          |d          "t          |d          2|5S )r{  inputr  r  r  s     r+   r   z5SamplingHandler._convert_messages.<locals>.<listcomp>  sI    yyyqga.@.@yWQPWEXEXyahijlwaxaxyyyyrS   c                 r    g | ]4}t          |d           t          |d          rt          |d          2|5S )r  r{  r  r  r  s     r+   r   z5SamplingHandler._convert_messages.<locals>.<listcomp>  sr      E  E  EAwq+7N7N  EX_`aciXjXj  Eovwx  {B  pC  pC  Ea  E  E  ErS   tool)roletool_call_idr  idcall_functionFensure_asciir{  	arguments)r  r  r  )r  rX  c                 <    g | ]}t          |d           |j        S r   r  r  s     r+   r   z5SamplingHandler._convert_messages.<locals>.<listcomp>  s)    SSS6@R@RSafSSSrS   r  r  r   r   r   r  r  r  r   r   r   	image_urlr  zdata:z;base64,)r  r  z5Unsupported sampling content block type: %s (skipped))r>  r|  r  r  r  r   r   r  r  r   r   r{  r  r   jsondumpsr   r  r   r   r   r   r!   r[   r  r   )rp  paramsr>  r   blockstool_results	tool_usescontent_blockstrtc_listtumsg_dict
text_partsr   r   s                  r+   _convert_messagesz!SamplingHandler._convert_messages  si     "? 8	N 8	NC,3C9J,K,K S(()#+t<<O3;- 
 JIvIIILyyFyyyI E  E  E  E  EN #  "$&L#==bAA! !      %N#  BNN%b$0FG0F0FGG *$&GU_`b`hjnUoUo  *CBH5)Q)Q)Q)Quxy{  zB  vC  vC% %$ $     +.('!J!JSSnSSS
 @*.))J*?*?HY')))) N~&&!++q8I60R0R+OOSX.QRBSBX$Y$YZZZZE!/  "5&11 !LL&%*)M)MNNNN$UF33 	z8R8R 	!LL(3.35aU^5a5aUZU_5a5a-b* *    
 #NN W $U 4     N e(L(LMMMrS   rB  r   c                 P    t           rt          ||           S t          |           )z1Return ErrorData (MCP spec) or raise as fallback.)r   rB  )_MCP_SAMPLING_TYPESr>   r    )rB  r   s     r+   _errorzSamplingHandler._error  s-      	9$8888   rS   c                    | j         dxx         dz  cc<   | j        dk    r%d| _        |                     d| j         d          S | xj        dz  c_        | j        | j        k    r-d| _        |                     d| j         d| j         d          S g }|j        j        D ]}|j        j        }t          |t                    rW	 t          j        |          }ni# t          j        t          f$ r( t                              d	| j        |           d
|i}Y n,w xY wt          |t"                    r|nd
t          |          i}|                    t'          d|j        |j        j        |                     t                              | j        d| j        |j        t3          t3          |dd          dd          t5          |                     t7          d||j        d          S )zEBuild a CreateMessageResultWithTools from an LLM tool_calls response.re  r   r   z Tool loops disabled for server 'z' (max_tool_rounds=0)z%Tool loop limit exceeded for server 'z' (max z rounds)zRMCP server '%s': malformed tool_calls arguments from LLM (wrapping as raw): %.100s_rawtool_use)r  r  r{  r  zEMCP server '%s' sampling response: model=%s, tokens=%s, tool_calls=%dusageNtotal_tokens?	assistantrU  r  r  r`  
stopReason)ro  r_  rn  r  r-   rB  rX  r  r  r  r   r  loadsJSONDecodeErrorrQ   r!   r[   r   r   rB   r  r{  logrl  r`  r   r   r=   )rp  choiceresponser  tcargsr  s          r+   _build_tool_use_resultz&SamplingHandler._build_tool_use_result  sO   %&&&!+&&& 1$$$%D!;;Z43CZZZ   	" 4#777$%D!;;78H 7 7,7 7 7  
 .+ 	 	B;(D$$$ Q,!Z--FF,j9 , , ,NN=($  
 %d^FFF, ",D$!7!7Pfc$ii=P!!.5[%	# # #     	

ShnGHgt44ncJJ	
 	
 	
 ,". 	
 
 
 	
s   C;DDc                 f   d| _         |j        j        pd}t                              | j        d| j        |j        t          t          |dd          dd                     t          dt          d	t          |          
          |j        | j                            |j        d                    S )z8Build a CreateMessageResult from a normal text response.r   r   z6MCP server '%s' sampling response: model=%s, tokens=%sr  Nr  r  r  r   r  rS  r  )rn  rB  r  r!   r  rl  r-   r`  r   r<   rA   r   _STOP_REASON_MAPr   finish_reason)rp  r  r  response_texts       r+   _build_text_resultz"SamplingHandler._build_text_resultT  s     !.4"

DhnGHgt44ncJJ		
 	
 	
 #V/-2P2PQQQ.,001EyQQ	
 
 
 	
rS   c                 @    | t          t                                dS )z<Return kwargs to pass to ClientSession for sampling support.)tools)sampling_callbacksampling_capabilities)r?   r@   rp  s    r+   session_kwargszSamplingHandler.session_kwargsi  s1     "&%7-//& & &
 
 	
rS   c           
         
K                                     sat                              d j         j                    j        dxx         dz  cc<                        d j         d j         d          S                      t          |dd                    }d	d
l	m

 |p j        pd j        r|rz j        vrqt                              d j                    j        dxx         dz  cc<                        d d j         dd                     j                             S                      |          t          |d          r%|j        r                    d	d|j        d           t%          |j         j                  dt          |d          r|j        |j        dt          |dd          }|rd |D             t                               j        d j        t1                               
 fd}	 t3          j        t3          j        |           j                   d{V }n# t2          j        $ r>  j        dxx         dz  cc<                        d j         d j         d          cY S t<          $ rQ} j        dxx         dz  cc<                        dt?          tA          |                               cY d}~S d}~ww xY wt          |dd          s3 j        dxx         dz  cc<                        d j         d          S |j!        d	         } j        d xx         dz  cc<   t          t          |d!d          d"d	          }	tE          |	tF                    r j        d#xx         |	z  cc<   |j$        d$k    r7t          |j%        d$          r"|j%        j&        r '                    ||          S  (                    ||          S )%zSampling callback invoked by the MCP SDK.

        Conforms to ``SamplingFnT`` protocol.  Returns
        ``CreateMessageResult``, ``CreateMessageResultWithTools``, or
        ``ErrorData``.
        z5MCP server '%s' sampling rate limit exceeded (%d/min)r   r   z)Sampling rate limit exceeded for server 'z' (z requests/minute)modelPreferencesNr   )call_llmr   z:MCP server '%s' requested model '%s' not in allowed_modelszModel 'z' not allowed for server 'z'. Allowed: , systemPromptsystemr  temperaturer  c                     g | ]G}d t          |dd          t          |dd          pdt          t          |dd                    ddHS )r  r{  r   r   inputSchemaNr{  r   rO   r  r  )r   _normalize_mcp_input_schemar   ru  s     r+   r   z,SamplingHandler.__call__.<locals>.<listcomp>  s}         ' '62 6 6'.q-'D'D'J&A#A}d;;' '! !	 	  rS   zFMCP server '%s' sampling request: model=%s, max_tokens=%d, messages=%dc            	      6      dpd j                   S )Nmcp)taskr`  r>  r  
max_tokensr  r\  r\  )r  call_temperature
call_toolsr  r>  resolved_modelrp  s   r+   
_sync_callz,SamplingHandler.__call__.<locals>._sync_call  s8    8$,!,%    rS   r  z"Sampling LLM call timed out after zs for server 'r@  zSampling LLM call failed: choicesz5LLM returned empty response (no choices) for server 'rc  r  r  rd  rX  ))rx  r!   r[   r-   rZ  ro  r  r  r   agent.auxiliary_clientr  rg  ra  r   r  r|  r  insertminrT  r^  r  r  rl  r   asynciowait_for	to_threadr\  TimeoutErrorr    r   r   r  r  rf  r  rB  rX  r  r  )rp  contextr  r`  server_toolsr  r  r*   r  r  r  r  r  r  r>  r  s   `         @@@@@@r+   __call__zSamplingHandler.__call__t  st      %%'' 		NNG $,   L"""a'""";;4D<L 4 4L4 4 4   ##GF4F$M$MNN 	433333 ;$"5; 		> 		nDL_6_6_NNL .   L"""a'""";;S. S S$S S26))D<O2P2PS S   ))&116>** 	Sv/B 	SOOAV=PQQRRR )4+>??
6=)) 	2f.@.L%1 
vw55 	  &  J 	

Tnj#h--	
 	
 	
		 		 		 		 		 		 		 		 		 		 			$-!*--t|        HH # 	 	 	L"""a'""";;3T\ 3 3#/3 3 3      	 	 	L"""a'""";;M_Xc]]-K-KMM       	 xD11 	L"""a'""";;($( ( (   !!$Z   A%   wx$??QRSSlC(( 	8L'''<7'''  L0055 1) 1 ..vx@@@&&vx888s&   3I A
K8	K8'AK3-K83K8N)r  )r   r  r  r  r  r   r   rr  boolrx  r	   r  staticmethodr  r   r  rf  r  r  r  r  r  rR   rS   r+   rR  rR    se       
 
 !*[PYZZ[C [ [ [ [ [.4    Xc]     OC O O O \OC4: C C C CN ! ! !3 ! ! ! \!7
 7
 7
r
 
 
*
 
 
 
 
}9 }9 }9 }9 }9rS   rR  schemac                 N   t          | t                    r|                     d          nd}t          |t                    r|sd| dS d| dg}|                                D ]\  }}d}d}t          |t                    rJt	          |                    dd          pd          }t	          |                    d	d          pd          }|rd
| dnd}|r|                    d| | d|            |                    d| |            d                    |          S )a%  Render a JSON-schema-ish requested_schema to a human-readable field list.

    Elicitation schemas are restricted to a flat object with named top-level
    properties. We surface field names, types, and descriptions so the user
    can tell what the server is asking for before approving.
    
propertiesNz"Approval requested by MCP server 'z'.z Fields requested by MCP server 'z':r   r  r   r	  r
  z  - : r  )r  r   r   r   r   r   r   )	r  r-   propslines
field_name
field_spec
field_type
field_descsuffixs	            r+   "_format_elicitation_schema_summaryr    sd    )364(@(@JFJJ|$$$dEeT"" D% DCKCCCC????@E"'++-- 
6 
6
J

j$'' 	FZ^^FB77=2>>JZ^^M2>>D"EEJ'19#j####r 	6LLB
BFBBjBBCCCCLL4
4F44555599UrS   c                   J    e Zd ZdZdZddededed         fdZd	efd
Z	d Z
dS )ElicitationHandlera  Handles ``elicitation/create`` requests for a single MCP server.

    Each ``MCPServerTask`` that has elicitation enabled creates one handler.
    The handler is callable and passed directly to ``ClientSession`` as the
    ``elicitation_callback`` (added in mcp Python SDK 1.11.0).

    Elicitation lets a server ask the client to collect structured input from
    the user mid-tool-call (e.g. payment authorization, OAuth confirmation).
    Form-mode elicitations are routed through Hermes' existing approval
    system (``tools.approval.prompt_dangerous_approval``), which surfaces
    the prompt on whichever surface the active session uses -- CLI, TUI,
    Telegram, Slack, etc. URL-mode elicitations are declined as unsupported.

    Failure modes are fail-closed: any timeout, exception, or unexpected
    state returns ``decline``/``cancel`` rather than silently accepting.
    The server treats this as the user not approving.
    rb   Nr-   r  ownerMCPServerTaskc                     || _         t          |                    dd          dt                    | _        || _        ddddd| _        d S )Nr\  r`   r   )rc  accepteddeclinedr   )r-   rP  r   rG  r\  r  ro  )rp  r-   r  r  s       r+   rr  zElicitationHandler.__init__+  sT    & %VZZ	3%?%?eLL 
	
 
rS   r   c                 
    d| iS )z?Return kwargs to pass to ClientSession for elicitation support.elicitation_callbackrR   r  s    r+   r  z!ElicitationHandler.session_kwargs<  s    &--rS   c                    	
K    j         dxx         dz  cc<   t          |dd          }|dk    rEt                              d j                    j         dxx         dz  cc<   t          d	          S t          |d
d          p
d j         d
t          |di           pi }t          | j                  	t                              d j        t          
          dd                    	 ddlm	 n]# t          $ rP}t                              d j        |            j         dxx         dz  cc<   t          d	          cY d}~S d}~ww xY w j        rt           j        dd          nddt          f	
 fd}	 t          j        t          j        |           j         j        z              d{V }n# t          j        $ r[ t                              d j        t+           j                              j         dxx         dz  cc<   t          d	          cY S t          $ rR}t                              d j        |d            j         dxx         dz  cc<   t          d	          cY d}~S d}~ww xY w|dk    r& j         d xx         dz  cc<   t          di !          S |dk    r% j         dxx         dz  cc<   t          d	          S  j         dxx         dz  cc<   t          d	          S )"zElicitation callback invoked by the MCP SDK.

        Conforms to ``ElicitationFnT`` protocol. Returns ``ElicitResult``
        or ``ErrorData``.
        rc  r   modeformr  z`MCP server '%s' requested URL-mode elicitation; declining (URL-mode elicitation not implemented)r  decline)actionrB  r   r  z' is requesting your approvalrequested_schemaz'MCP server '%s' elicitation request: %sN   r   )request_elicitation_consentz<MCP server '%s' elicitation: approval system unavailable: %sr   _pending_call_contextr   c                       ) t          j                  dj                   S                                                      t          j                  dj                   S )Nzmcp-elicitation/)timeout_secondssurface)rf  r\  r-   copyrun)capturedr   rB  r  rp  s   r+   _invoke_consentz4ElicitationHandler.__call__.<locals>._invoke_consent  s    22$'$5$5At/?AA	    ==??&&+ #DL 1 1=4+;== '   rS   r  z/MCP server '%s' elicitation timed out after %dscancelz&MCP server '%s' elicitation failed: %sTexc_infoacceptr  )r	  r  )ro  r   r!   rY   r-   rD   r  r   tools.approvalr  r    r\   r  r   r  r  r  r\  _OUTER_TIMEOUT_GRACE_SECONDSr  r[   rf  )rp  r  r  r  r  r*   r  answerr  r   rB  r  s   `       @@@@r+   r  zElicitationHandler.__call__@  s      	Z   A%    vvv..5==KKC   
 L$$$)$$$y1111&)R00 
J4+JJJ 	 !3R88>B8AQRR5og66tt<	
 	
 	
	2BBBBBBB 	2 	2 	2LLN #   L"""a'"""y111111111	2* JN]74:'>EEEY]	 	 	 	 	 	 	 	 	 	 	$	2"+!/22t'HH        FF # 	1 	1 	1NNA #dl"3"3   L"""a'"""x000000 	2 	2 	2LL8 #     L"""a'"""y111111111	2 XL$$$)$$$x<<<<XL"""a'"""x0000Z   A%   9----sE   4C; ;
EAE
EE	;G A'J	.	J	7AJ>J	J	N)r   r  r  r  r  r   r   r	   rr  r  r  rR   rS   r+   r  r    s         , $% 
 
C 
 
h>W 
 
 
 
". . . . .l. l. l. l. l.rS   r  c                      e Zd ZdZdZdefdZdefdZdefdZ	d Z
dej        fd	Zd
 Zd Zd Zd"dZdefdZdefdZdefdZdZddddddedee         dededdf
dZdefdZd ZdefdZdefdZd  Zd"d!ZdS )#r  ac  Manages a single MCP server connection in a dedicated asyncio Task.

    The entire connection lifecycle (connect, discover, serve, disconnect)
    runs inside one asyncio Task so that anyio cancel-scopes created by
    the transport client are entered and exited in the same Task context.

    Supports both stdio and HTTP/StreamableHTTP transports.
    )r{  sessiontool_timeout_task_ready_shutdown_event_reconnect_event_toolsr  _config	_sampling_elicitation_registered_tool_names
_auth_type_refresh_lock	_rpc_lock_pending_refresh_tasksr  initialize_result_ping_unsupportedr{  c                    || _         d | _        t          | _        d | _        t          j                    | _        t          j                    | _        t          j                    | _	        g | _
        d | _        i | _        d | _        d | _        g | _        d| _        t          j                    | _        t          j                    | _        t)                      | _        d | _        d | _        d| _        d S )Nr   F)r{  r  _DEFAULT_TOOL_TIMEOUTr  r   r  Eventr!  r"  r#  r$  r  r%  r&  r'  r(  r)  Lockr*  r+  setr,  r  r-  r.  )rp  r{  s     r+   rr  zMCPServerTask.__init__  s    	&*#8-1
moo&} !(+/48:>13#!$\^^ !9<# EI" 15 (-rS   r   c                     d| j         v S )z)Check if this server uses HTTP transport.r  )r%  r  s    r+   _is_httpzMCPServerTask._is_http  s    $$rS   c                 h    | j         }|t          |dd          nd}|dS t          |dd          duS )u  Whether the server advertises the ``tools`` capability.

        Per the MCP spec, ``InitializeResult.capabilities.tools`` is non-None
        iff the server implements the ``tools/*`` request family. Prompt-only
        or resource-only servers omit it, and calling ``tools/list`` against
        them raises ``McpError(-32601 Method not found)`` — which previously
        killed the connection during discovery and made every keepalive fail.
        (Ported from anomalyco/opencode#31271.)

        Returns True when no capability info was captured (legacy fallback:
        preserve the old always-call-list_tools behavior rather than regress
        any server that was working before this gate).
        NcapabilitiesTr  )r-  r   )rp  init_resultcapss      r+   _advertises_toolszMCPServerTask._advertises_tools   sI     ,=H=Tw{ND999Z^<4tWd++477rS   c                    K   	 |                                   d{V  dS # t          j        $ r  t          $ r$ t                              d| j                   Y dS w xY w)zBRun a dynamic tool refresh and log failures from background tasks.Nz,MCP server '%s': dynamic tool refresh failed)_refresh_toolsr  CancelledErrorr    r!   	exceptionr{  r  s    r+   _refresh_tools_taskz!MCPServerTask._refresh_tools_task  s      	X%%'''''''''''% 	 	 	 	X 	X 	XKTYWWWWWW	Xs     9AAc                     t          j        |                                           }| j                            |           |                    | j        j                   |S )zCSchedule a background tool refresh and keep it strongly referenced.)r  create_taskr?  r,  addadd_done_callbackdiscardrp  r  s     r+   _schedule_tools_refreshz%MCPServerTask._schedule_tools_refresh  sT    "4#;#;#=#=>>#''---t:BCCCrS   c                       fd}|S )a  Build a ``logging_callback`` for ``ClientSession``.

        Routes MCP ``notifications/message`` log notifications from the
        server into Hermes' logging (agent.log via hermes_logging), tagged
        with the server name.  Without this, the SDK's default callback
        silently discards them, so server-side warnings/errors during a
        tool call were invisible.  Port of anomalyco/opencode#34529.
        c           	        K   	 t                               t          t          | dd                                                    t
          j                  }t          | dd           }t          |t                    sD	 t          j	        |dt                    }n&# t          t          f$ r t          |          }Y nw xY wt          |          dk    r|d d         dz   }t          | dd           }|rj         d	| nj        }t                              |d
||           d S # t           $ r& t                              dj        d           Y d S w xY w)NlevelrY   r   F)r  rL  i  z... [truncated]r!   /zMCP server log [%s]: %sz/Failed to handle MCP log notification from '%s'Tr  )_MCP_LOG_LEVEL_MAPr   r   r   r   rh  rj  r  r  r  rP   rQ   r   r{  r!   r  r    r"   )r  rI  r   logger_nameoriginrp  s        r+   _on_logz5MCPServerTask._make_logging_callback.<locals>._on_log/  s     *..8899??AA7<  vvt44!$,, ))#z$UCPPP%z2 ) ) )"4yy) t99t##;)::D%fh==9DSDI55555$)

5";VTJJJJJ   EI       s7   A9D' ?B D'  B?<D' >B??A&D' ',EErR   )rp  rN  s   ` r+   _make_logging_callbackz$MCPServerTask._make_logging_callback&  s#    	 	 	 	 	. rS   c                       fd}|S )a  Build a ``message_handler`` callback for ``ClientSession``.

        Dispatches on notification type.  Only ``ToolListChangedNotification``
        triggers a refresh; prompt and resource change notifications are
        logged as stubs for future work.
        c                   K   	 t          | t                    r#t                              dj        |            d S t
          rt          | t                    r| j        xt          d xS\    t          	                    dj                   
                                 t          j        d           d {V  d S  xt          d x%\    t                              dj                   d S  t          d x$\   t                              dj                   d S  	 d S d S d S # t          $ r$ t                              dj                   Y d S w xY w)Nz'MCP message handler (%s): exception: %srR   z9MCP server '%s': received tools/list_changed notificationr   z/MCP server '%s': prompts/list_changed (ignored)z1MCP server '%s': resources/list_changed (ignored)z%Error in MCP message handler for '%s')r  r    r!   r"   r{  _MCP_NOTIFICATION_TYPESrE   rootrF   rY   rF  r  sleeprG   rH   r>  )rB  rp  s    r+   _handlerz5MCPServerTask._make_message_handler.<locals>._handlerO  s      Ugy11 LL!JDIW^___F* !z'CU/V/V !!,:8::::::"KK [ $	   !88::: #*-"2"2222222222% ;& =:<<<<<<"LL)Z\`\efffff =<>>>>>"LL)\^b^ghhhhh ? D5! ! ! !6  U U U  !H$)TTTTTTUs)   6D% A>D% =/D% .-D% D% %*EErR   )rp  rU  s   ` r+   _make_message_handlerz#MCPServerTask._make_message_handlerH  s)    !	U !	U !	U !	U !	UD rS   c           	      `   K   ddl m}                                  sdS  j        4 d{V  t	           j                  } j        4 d{V   j                                         d{V }ddd          d{V  n# 1 d{V swxY w Y   t          |d          r|j
        ng }| fd|D             z
  }|D ]&}|                    |           t          |           '| _        t           j          j                   _        t	           j                  }||z
  }||z
  }	g }
|r8|
                    dd                    t'          |                                |	r8|
                    dd                    t'          |	                                |
r5t(                              d	 j        d
                    |
                     n3t(                              d j        t/           j                             ddd          d{V  dS # 1 d{V swxY w Y   dS )ua  Re-fetch tools from the server and update the registry.

        Called when the server sends ``notifications/tools/list_changed``.
        The lock prevents overlapping refreshes from rapid-fire notifications.
        After the initial ``await`` (list_tools), all mutations are synchronous
        — atomic from the event loop's perspective.
        r   registryNr  c                 D    h | ]}t          j        |j                  S rR   )mcp_prefixed_tool_namer{  )r   r  rp  s     r+   	<setcomp>z/MCPServerTask._refresh_tools.<locals>.<setcomp>  s7     1 1 1 'ty$)<<1 1 1rS   zadded: r  z	removed: uU   MCP server '%s': tools changed dynamically — %s. Verify these changes are expected.r   z>MCP server '%s': dynamically refreshed %d tool(s) (no changes))tools.registryrY  r:  r*  r3  r(  r+  r  
list_toolsr|  r  
deregister_forget_mcp_tool_serverr$  _register_server_toolsr{  r%  r   r   sortedr!   r[   rY   r   )rp  rY  old_tool_namestools_resultnew_mcp_toolsstale_tool_namesr   new_tool_namesaddedremovedchangess   `          r+   r<  zMCPServerTask._refresh_toolss  s      	,+++++%%'' 	 F% 1	 1	 1	 1	 1	 1	 1	 1	 !<==N ~ ? ? ? ? ? ? ? ?%)\%<%<%>%>>>>>>>? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?29,2P2PXL..VXM  . 1 1 1 1)1 1 1   . 3 3	##I...'	2222 (DK*@	4+ +D'
 !!<==N"^3E$~5GG EC6%==)A)ACCDDD IG499VG__+E+EGGHHH 
9Ityy11    TIs4#>??  ]1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	 1	s6   "H B/H
B	HB	E;H
H'*H'Nc                   K   | j         s	 t          j        | j                                        d           d{V  dS # t
          $ rV}t          |          s |                                 s d| _         t          	                    d| j
                   Y d}~nd}~ww xY wt          j        | j                                        d           d{V  dS )ub  Exercise the session to detect a stale/expired connection.

        Uses ``ping`` (cheap, transport-agnostic liveness) by default. ``ping``
        is an OPTIONAL MCP utility: a server that doesn't implement it answers
        JSON-RPC -32601. The first time that happens we latch
        ``_ping_unsupported`` and fall back to the pre-ping probe — capability
        permitting, ``list_tools``; otherwise ``ping`` is the only option and
        the -32601 propagates (a server advertising neither a working ping nor
        tools has no liveness primitive left). The latch resets on each fresh
        transport connection so a server that gains ping support after a
        reconnect is re-probed with the cheap path.

        Raises on a genuine connection failure so the caller triggers a
        reconnect; returns normally when the session is alive.
              >@r  NTz~MCP server '%s': does not implement the optional 'ping' utility (-32601); using 'list_tools' for keepalive on this connection.)r.  r  r  r  	send_pingr    r   r:  r!   rY   r{  r^  )rp  r*   s     r+   _keepalive_probezMCPServerTask._keepalive_probe  s       % 	&t|'='='?'?NNNNNNNNNN    2#66 --// )-&' I	       $ t|6688$GGGGGGGGGGGGs   3A   
B 
ABB c           	      J  K   t          t          t          | j                            dt
                                        }t          j        | j        	                                          }t          j        | j
        	                                          }	 	 t          j	        ||h|t          j                   d{V \  }}|rnu| j        rm	 |                                  d{V  nQ# t          $ rD}t                              d| j        |           | j
                                         Y d}~n	d}~ww xY w||fD ]P}|                                s:|                                 	 | d{V  4# t          j        t          f$ r Y Lw xY wQnZ# ||fD ]P}|                                s:|                                 	 | d{V  4# t          j        t          f$ r Y Lw xY wQw xY w| j                                        rdS | j
                                         dS )u1  Block until either _shutdown_event or _reconnect_event fires.

        Returns:
            "shutdown"  if the server should exit the run loop entirely.
            "reconnect" if the server should tear down the current MCP
                        session and re-enter the transport (fresh OAuth
                        tokens, new session ID, etc.). The reconnect event
                        is cleared before return so the next cycle starts
                        with a fresh signal.

        Shutdown takes precedence if both events are set simultaneously.

        Periodically sends a lightweight keepalive (``ping``, with a
        ``list_tools`` fallback for servers that don't implement the optional
        ping utility — see :meth:`_keepalive_probe`) to prevent TCP/session
        state from going stale during idle periods (#17003). If the keepalive
        fails, triggers a reconnect.

        The cadence is ``keepalive_interval`` from server config (default
        :data:`_DEFAULT_KEEPALIVE_INTERVAL`, floored at
        :data:`_MIN_KEEPALIVE_INTERVAL`). Servers that GC idle sessions on a
        short TTL (e.g. Unreal Engine's editor MCP, ~15s) need an interval
        below that TTL, otherwise every idle tool call lands on an
        already-expired session and pays the full reconnect path.
        keepalive_intervalT)r\  return_whenNz:MCP server '%s' keepalive failed, triggering reconnect: %sshutdown	reconnect)rJ  _MIN_KEEPALIVE_INTERVALrG  r%  r   _DEFAULT_KEEPALIVE_INTERVALr  rA  r"  waitr#  FIRST_COMPLETEDr  rn  r    r!   r[   r{  r3  doner  r=  is_setclear)rp  rp  shutdown_taskreconnect_taskrx  _pendingr*   ru  s           r+   _wait_for_lifecycle_eventz'MCPServerTask._wait_for_lifecycle_event  s     @ !#$,""#79TUUVV
 

  +D,@,E,E,G,GHH ,T-B-G-G-I-IJJ$	'.|"N3. ' 7( ( ( " " " " " "h
   < 
	"335555555555$   7 Is  
 -11333): $^4  vvxx HHJJJ#2I>   	m^4  vvxx HHJJJ#2I>   	 &&(( 	:##%%%{sl   7F C- ,F -
D;7:D61F 6D;;F .E77FF/G,GG,G'	$G,&G'	'G,c                   K   t          j        | j                                                  }t          j        | j                                                  }	 t          j        ||ht           j                   d{V  ||fD ]P}|                                s:|                                 	 | d{V  4# t           j        t          f$ r Y Lw xY wQnZ# ||fD ]P}|                                s:|                                 	 | d{V  4# t           j        t          f$ r Y Lw xY wQw xY w| j        
                                rdS | j                                         dS )u  Block until a reconnect or shutdown is requested while parked.

        Used by :meth:`run` after the reconnect budget is exhausted. The
        task stays alive (so ``_reconnect_event`` always has a listener) but
        does no work until something explicitly asks it to come back —
        the circuit-breaker half-open probe, OAuth recovery, or a manual
        ``/mcp`` refresh.

        Returns:
            ``"shutdown"`` if the server should exit the run loop entirely,
            ``"reconnect"`` if it should rebuild the transport. The reconnect
            event is cleared before returning so the next park cycle starts
            from a fresh signal. Shutdown takes precedence.
        )rq  Nrr  rs  )r  ensure_futurer"  rv  r#  rw  rx  r  r=  r    ry  rz  )rp  r{  r|  ru  s       r+   _wait_for_reconnect_or_shutdownz-MCPServerTask._wait_for_reconnect_or_shutdown0  s       -d.B.G.G.I.IJJ .t/D/I/I/K/KLL	,/#3         
 $^4  vvxx HHJJJ#2I>   	m^4  vvxx HHJJJ#2I>   	 &&(( 	:##%%%{sB   (C 1B::CC/D/DD/D*	'D/)D*	*D/r  c           	        K   t           st          d| j         d          |                    d          }|                    dg           }|                    d          }|st	          d| j         d          t          |          }t          ||          \  }}ddlm} 	 t          j
        t          j        |||          t          	           d
{V }n=# t          j        $ r+ t                              d| j        t                     d
}Y nw xY w|rt	          d| j         d|           t!          |||r|nd
          }| j        r| j                                        ni }	| j        r,|	                    | j                                                   t*          rt,          r|                                 |	d<   t0          r|                                 |	d<   t5                      }
t7                      }t9          | j                   t;                      }	 t=          ||          4 d
{V \  }}t?          t5                      |
z
            }|ri }|D ]7}	 tA          j!        |          ||<   # tD          tF          tH          f$ r Y 4w xY wtJ          5  |D ]}| j        tL          |<   tN                              |           d
d
d
           n# 1 swxY w Y   tQ          ||fi |	4 d
{V 	 }|)                                 d
{V | _*        || _+        | ,                                 d
{V  | j-                                         t]          | j                   | /                                 d
{V  d
d
d
          d
{V  n# 1 d
{V swxY w Y   d
d
d
          d
{V  n# 1 d
{V swxY w Y   |rddl0m1} te          t@          dd
          }tJ          5  |D ]}tL          3                    |d
           |D ]} ||          }d}tN                              |          }|s3|1|/	  ||d           d}n# tF          th          tH          f$ r d}Y nw xY w|s|rtj          6                    |           }tN          3                    |d
           	 d
d
d
           d
S # 1 swxY w Y   d
S d
S # |rddl0m1} te          t@          dd
          }tJ          5  |D ]}tL          3                    |d
           |D ]} ||          }d}tN                              |          }|s3|1|/	  ||d           d}n# tF          th          tH          f$ r d}Y nw xY w|s|rtj          6                    |           }tN          3                    |d
           	 d
d
d
           w # 1 swxY w Y   w w xY w)z%Run the server using stdio transport.r  z' requires the 'mcp' Python SDK, but it is not installed. Install with:
  pip install 'hermes-agent[mcp]'
or (full install):
  pip install 'hermes-agent[all]'r   r  r   z' has no 'command' in configr   )check_package_for_malwarer  Nuy   MCP server '%s': OSV malware preflight timed out after %.0fs (network slow/unreachable) — proceeding without the check.r  )r   r  r   rJ   rW   )errlog_pid_existskillpgFT)7rL   r   r{  r   rQ   r   r   tools.osv_checkr  r  r  r  _OSV_MALWARE_CHECK_TIMEOUT_Sr  r!   r[   r6   r&  r  r'  r   rR  _MCP_MESSAGE_HANDLER_SUPPORTEDrV  _MCP_LOGGING_CALLBACK_SUPPORTEDrO  _snapshot_child_pidsr3  r4   r,   r7   _filter_mcp_childrenr#   getpgidAttributeErrorProcessLookupErrorOSError_lock_stdio_pids_stdio_pgidsr5   
initializer-  r  _discover_toolsr!  _reset_server_errorr~  gateway.statusr  r   popPermissionError_orphan_stdio_pidsrB  )rp  r  r   r  r   safe_envr  malware_errorserver_paramssampling_kwargspids_beforenew_pids_errlogread_streamwrite_stream	new_pgids_pidr  r  _killpgpid	pid_alivepgroup_alivepgids                           r+   
_run_stdiozMCPServerTask._run_stdioS  s	      	4ty 4 4 4   **Y''zz&"%%::e$$ 	FtyFFF   #8,,27HEE 	>=====	!")"2!";WdKK4# # #      MM # 	! 	! 	!NNO	7  
 !MMM	!  	<ty<<]<<   .$.$
 
 
 >B^S$.77999QS 	G""4#4#C#C#E#EFFF" 	N'E 	N151K1K1M1MO-.* 	P262M2M2O2OO./ +,,
 	!+++%''P	8#M'BBB -; -; -; -; -; -; -; G 0(**[8   7
 13I ( ! !!.0j.>.>IdOO .0BGL ! ! ! !D!  7 7$, : :D04	K--$++I6667 7 7 7 7 7 7 7 7 7 7 7 7 7 7 ) 1@  ; ; ; ; ; ; ; ;3:3E3E3G3G-G-G-G-G-G-GD*#*DL..000000000KOO%%% (	222 88:::::::::; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;?-; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -; -;h  8666666!"h55 8 8 ( 4 4#d3333' 8 8 %0K$4$4	',+//44( 	5T-='BU
5 'a 0 0 0/3$6#Q 5 5 5/45$ 8 8.2237777 ),,S$7777+88 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 88 8x 8666666!"h55 8 8 ( 4 4#d3333' 8 8 %0K$4$4	',+//44( 	5T-='BU
5 'a 0 0 0/3$6#Q 5 5 5/45$ 8 8.2237777 ),,S$7777+88 8 8 8 8 8 8 8 8 8 8 8 8 8 8 88s/  %5C 7DD!S 8*N7#I;:N7;JN7J
N7/KN7K	N7!K	"N7:BNN7
N	N7!N	"N7%S 7
OS OS -AR7 QR7Q+(R7*Q++>R77R;>R;&W,AV5?UV5U*'V5)U**>V5)W5V99W<V9=W)zapplication/jsonztext/event-streamTg      @)headers
ssl_verifyr  r\  r  r  r  r\  c                "  K   	 ddl }n# t          $ r Y dS w xY w|d|                    |          d}|||d<   |rt          |          ni }	  |j        di |4 d{V }	|	                    ||           d{V }
|
j        dv r|	                    ||           d{V }
	 ddd          d{V  n# 1 d{V swxY w Y   n# |j        $ r Y dS w xY wd|
j        cxk    rd	k     sn dS |
j	                            d
d          
                    d          d                                                                         }|sdS || j        v rdS t          d| j         d| d| dd                    | j                   d	          )u   Probe *url* for an MCP-shaped response before the SDK connects.

        A misconfigured ``mcp_servers.<name>.url`` pointed at a plain web app
        returns HTML (or some other non-MCP body). The MCP SDK then sits on
        the connection for the full ``connect_timeout`` (default 60 s) before
        surfacing an opaque ``CancelledError``. A cheap, short-timeout probe
        here catches that in ≤ ``timeout`` seconds and raises
        :class:`NonMcpEndpointError` with an actionable message.

        Detection is allow-list based: a 2xx response is rejected only when it
        carries a definite content type that is NOT one an MCP endpoint uses
        (``application/json`` / ``text/event-stream``). A missing or empty
        content type, non-2xx status, or any network/transport error passes
        through silently — the probe is strictly best-effort, and the real
        handshake remains the source of truth for everything except the
        unambiguous "this is a web page, not MCP" case.

        Runs on its own httpx client OUTSIDE the SDK's anyio task group, so the
        raised error propagates as itself rather than being wrapped in an
        ``ExceptionGroup`` (which is what defeats hooks installed inside the
        SDK transport).
        r   NT)verifyfollow_redirectsr\  cert)r  )i  i  r  r`   zcontent-typer   r   r  z' at z returned Content-Type 'z)', not an MCP response (expected one of: r  u   ). The URL most likely points at a web page rather than an MCP endpoint — check it resolves to a Streamable HTTP / SSE endpoint (e.g. https://host/mcp, not https://host/).rR   )httpxr   Timeoutr   AsyncClientheadstatus_coder   	HTTPErrorr  r   r   r   _MCP_CONTENT_TYPESr  r{  r   )rp  r  r  r  r  r\  _httpxclient_kwargsprobe_headersclientrespct_bases               r+   _preflight_content_typez%MCPServerTask._preflight_content_type  s     >	""""" 	 	 	FF	 ! $~~g..
 

 "$/M&!)08Wb	)v)::M:: H H H H H H Hf $[[m[DDDDDDDD#z11!'C!G!GGGGGGGDGH H H H H H H H H H H H H H H H H H H H H H H H H H H  	 	 	FF	
 t'----#----F,"">266<<SAA!DJJLLRRTT 	Fd---F!:49 : :3 : :: :yy011: : :
 
 	
sC   	 
C
 !AB8&C
 8
CC
 CC
 

CCc                   K   t           st          d| j         d          |d         }t          |                    d          pi           }t          d |D                       s
t          |d<   |                    dt                    }|                    dd	          }t          | j        |          }d
}| j	        dk    rs	 ddl
m}  |                                | j        ||                    d                    }n4# t          $ r'}	t                              d| j        |	            d
}	~	ww xY w| j        r| j                                        ni }
| j        r,|
                    | j                                                   t(          rt*          r|                                 |
d<   t.          r|                                 |
d<   |                    d          dk    ryt2          t          d| j         d          ||pd
t5          |          dd}|||d<   ||d	urdd
l||	 d$fd	}||d<   t3          d%i |4 d
{V \  }}t9          ||fi |
4 d
{V 	 }|                                 d
{V | _        || _        |                                   d
{V  | j!        "                                 tG          | j                   | $                                 d
{V }|dk    r t          %                    d| j                   d
d
d
          d
{V  n# 1 d
{V swxY w Y   d
d
d
          d
{V  n# 1 d
{V swxY w Y   d
S tL          rdd
l}|'                    |          fd}d	|(                    t5          |          d          |d|gid}|r||d<   |||d<   |||d<    |j)        d%i |4 d
{V }tU          ||           4 d
{V \  }}}t9          ||fi |
4 d
{V }|                                 d
{V | _        || _        |                                   d
{V  | j!        "                                 tG          | j                   | $                                 d
{V }|dk    r t          %                    d!| j                   d
d
d
          d
{V  n# 1 d
{V swxY w Y   d
d
d
          d
{V  n# 1 d
{V swxY w Y   d
d
d
          d
{V  d
S # 1 d
{V swxY w Y   d
S |t5          |          |d"}|||d<   tW          |fi |4 d
{V \  }}}t9          ||fi |
4 d
{V }|                                 d
{V | _        || _        |                                   d
{V  | j!        "                                 tG          | j                   | $                                 d
{V }|dk    r t          %                    d#| j                   d
d
d
          d
{V  n# 1 d
{V swxY w Y   d
d
d
          d
{V  d
S # 1 d
{V swxY w Y   d
S )&z3Run the server using HTTP/StreamableHTTP transport.r  zw' requires HTTP transport but mcp.client.streamable_http is not available. Upgrade the mcp package to get HTTP support.r  r  c              3   F   K   | ]}|                                 d k    V  dS )mcp-protocol-versionN)r   )r   r   s     r+   r  z*MCPServerTask._run_http.<locals>.<genexpr>I  s0      LLS399;;"88LLLLLLrS   r  connect_timeoutr  TNoauthr   get_managerz#MCP OAuth setup failed for '%s': %srJ   rW   	transportssezt' requires SSE transport but mcp.client.sse.sse_client is not available. Upgrade the mcp package to get SSE support.     r@)r  r  r\  sse_read_timeoutauthc                     dd}|||d<   n                     dd          |d<   | | |d<   |||d<   |d	<    j        d
i |S )NT)r  r  r\  rl  r  readr  r  r  rR   )r  r  )r  r\  r  kwargs_cert_for_factory
_httpx_mod_verify_for_factorys       r+   _mcp_http_client_factoryz9MCPServerTask._run_http.<locals>._mcp_http_client_factory  s     -1"5$ $F *,3y)),6,>,>t%,>,P,Py)*,3y)')-v(4):v1:1;;F;;;rS   httpx_client_factoryrs  uA   MCP server '%s': reconnect requested — tearing down SSE sessionc                    K   | j         r| j        rz| j        j        }|j        |j        |j        fj        j        j        fk    rF| j        j                            dd           | j        j                            dd           dS dS dS dS )zBStrip Authorization headers when redirected to a different origin.authorizationNAuthorization)is_redirectnext_requestr  r  hostportr  r  )r  target_original_urls     r+   $_strip_auth_on_cross_origin_redirectzEMCPServerTask._run_http.<locals>._strip_auth_on_cross_origin_redirect  s      ' QH,A Q%26Fv{FK@%,m.@-BTE   !-599/4PPP -599/4PPPPPQ Q Q Q rS   r  r  )r  r\  r  event_hooksr  )http_clientuB   MCP server '%s': reconnect requested — tearing down HTTP session)r  r\  r  uI   MCP server '%s': reconnect requested — tearing down legacy HTTP session)NNNrR   ),_MCP_HTTP_AVAILABLEr   r{  r   r   anyr:   _DEFAULT_CONNECT_TIMEOUTr'  r)  tools.mcp_oauth_managerr  get_or_build_providerr    r!   r[   r&  r  r'  r   rR  r  rV  r  rO  r;   rG  r  r5   r  r-  r  r  r!  r3  r  r~  rY   _MCP_NEW_HTTPURLr  r  r9   r8   )rp  r  r  r  r  r  r  _oauth_authr  r*   r  _sse_kwargsr  r  r  r  r   r  r  r  r  _get_session_id_http_kwargsr  r  r  r  s                          @@@@r+   	_run_httpzMCPServerTask._run_http:  s     " 	?ty ? ? ?   Umvzz),,233
 LLGLLLLL 	F.EG*+ **%68PQQZZd33
*49f== ?g%%??????)kmmAAIsFJJw$7$7     DdiQTUUU >B^S$.77999QS 	G""4#4#C#C#E#EFFF" 	N'E 	N151K1K1M1MO-.* 	P262M2M2O2OO./
 ::k""e++!!B49 B B B   "?d 11$)	! !K & '2F#&*D*@*@ +***$/!&0# 6:< < < < < < < <& 7O23!00K00       4O[,( 1@         3:3E3E3G3G-G-G-G-G-G-GD*#*DL..000000000KOO%%% (	222#'#A#A#C#CCCCCCCF,,78<	                                                      $ F M	 LLL!IIcNNMQ Q Q Q Q %) ==)?)?e=LL$ *-Q,RS	# #M  3+2i(&(3f%&(3f% )u(99=99       [1#;OOO        T,[,ZZ/ZZ       ^e7>7I7I7K7K1K1K1K1K1K1K.'."22444444444))) ,DI666'+'E'E'G'G!G!G!G!G!G!G![00"KK!<=AY                                                                                   , # 11$" "L
 &'2V$,SAALAA        F\?(lVVoVV       Za3:3E3E3G3G-G-G-G-G-G-GD*#*DL..000000000KOO%%% (	222#'#A#A#C#CCCCCCCF,,?@D	                                                         s   	=D 
D8"D33D8M0B.L0M0
L:	:M=L:	>M
M M T8S4B.S?S4
SS4SS4"T4
S>	>TS>	T
T"%T"Y1B.X1Y1
X;	;Y>X;	?Y
Y"Yc                   K   d| _         | j        dS |                                 s)t                              d| j                   g | _        dS | j        4 d{V  | j                                         d{V }ddd          d{V  n# 1 d{V swxY w Y   t          |d          r|j
        ng | _        dS )u  Discover tools from the connected session.

        Capability-gated: prompt-only / resource-only MCP servers don't
        implement ``tools/list``, and calling it raises ``McpError(-32601)``,
        which previously aborted the connection — those servers could never
        stay connected for their prompts/resources. Skip the call when the
        server doesn't advertise the ``tools`` capability.
        (Ported from anomalyco/opencode#31271.)
        FNus   MCP server '%s': does not advertise 'tools' capability — skipping tools/list (prompts/resources remain available)r  )r.  r  r:  r!   rY   r{  r$  r+  r^  r|  r  )rp  rd  s     r+   r  zMCPServerTask._discover_tools	  sf      "'<F%%'' 	KKK	  
 DKF> 	; 	; 	; 	; 	; 	; 	; 	;!%!8!8!:!:::::::L	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; |W--L 	s    B
BBc           	        K   || _         |                    dt                    | _        |                    d          pd                                                                | _        |                    di           }|                    dd          r"t          rt          | j	        |          | _
        nd| _
        |                    di           }|                    dd          r$t          rt          | j	        || 	          | _        nd| _        d
|v r$d|v r t                              d| j	                   |                                 r	 t#          | j	        |                    d
                     nS# t$          $ rF}t                              d|           || _        | j                                         Y d}~dS d}~ww xY w|                    d          dk    r| j                                        s| j        dk    r	 t/          |                    d          pi           }|                     |d
         ||                    dd          t3          | j	        |                     d{V  nS# t4          $ rF}t                              d|           || _        | j                                         Y d}~dS d}~ww xY wd}d}d}	 	 |                                 r|                     |           d{V  n|                     |           d{V  | j                                        r
	 d| _        dS t                              d| j	                   d}d}d| _        	 d| _        # t@          j!        $ r	 d| _         tD          $ r$}d| _        | j                                        sotG          |          rNt                              d| j	        |           || _        | j                                         Y d}~d| _        dS |dz  }|tH          k    rTt                              d| j	        tH          |           || _        | j                                         Y d}~d| _        dS t                              d| j	        |tH          ||           tA          j%        |           d{V  tM          |dz  tN                    }| j                                        r-|| _        | j                                         Y d}~d| _        dS Y d}~d| _        U| j                                        r.t          (                    d| j	        |           Y d}~d| _        dS |dz  }|tR          k    rt                              d| j	        tR          |           | *                                 | j+        ,                                 | -                                 d{V }	|	dk    rY d}~d| _        dS t                              d| j	                   d}d}Y d}~d| _        ^t                              d | j	        |tR          ||           tA          j%        |           d{V  tM          |dz  tN                    }| j                                        rY d}~d| _        dS Y d}~nd}~ww xY w	 d| _        n# d| _        w xY w)!zLong-lived coroutine: connect, discover tools, wait, disconnect.

        Includes automatic reconnection with exponential backoff if the
        connection drops unexpectedly (unless shutdown was requested).
        r\  r  r   samplingenabledTNelicitation)r  r  r   zMCP server '%s' has both 'url' and 'command' in config. Using HTTP transport ('url'). Remove 'command' to silence this warning.z%sr  r  r  r  r  )r  r  r  r   g      ?z@MCP server '%s': reconnecting (OAuth recovery or manual refresh)zSMCP server '%s' failed initial OAuth authentication, not retrying automatically: %sr   zJMCP server '%s' failed initial connection after %d attempts, giving up: %szPMCP server '%s' initial connection failed (attempt %d/%d), retrying in %.0fs: %sr  z0MCP server '%s' disconnected during shutdown: %szaMCP server '%s' failed after %d reconnection attempts, parking until a reconnect is requested: %srr  zHMCP server '%s': reconnect requested while parked; rebuilding transport.zJMCP server '%s' connection lost (attempt %d/%d), reconnecting in %.0fs: %s).r%  r   r0  r  r   r   r)  r  rR  r{  r&  _MCP_ELICITATION_TYPESr  r'  r!   r[   r5  r  r   r  r!  r3  ry  r   r  r'  r  r  r  r"  r  rY   r  r=  r    _is_auth_error_MAX_INITIAL_CONNECT_RETRIESrT  r  _MAX_BACKOFF_SECONDSr"   _MAX_RECONNECT_RETRIES_deregister_toolsr#  rz  r  )
rp  r  sampling_configelicitation_configr*   _probe_headersretriesinitial_retriesbackoffparkeds
             r+   r  zMCPServerTask.run'	  s      "JJy2GHH!::f--3::<<BBDD !**Z44y$// 	"4G 	",TYHHDNN!DN $ZZr::!!)T22 	%7M 	% 249>PX\ ] ] ]D $D F??yF22NN  		   ==?? "	(FJJu4E4EFFFF%   tS)))!!!!	$ zz+&&%//8J8J8L8L/QUQ`dkQkQk%)&**Y*?*?*E2%F%FN66u .#)::lD#A#A$8F$K$K	 7           +   NN4---"%DKKOO%%%FFFFF	 O	$N$==?? 2..0000000000//&111111111 '..00 F  $E &I     $ \  $[ )     $ _ _ _# {))++ $%c** = Is  
 '*)))b  $_ $q(O&)EEE9 I'CS  
 '*)))L  $I NNA	?4gs	   "-000000000!'A+/CDDG +2244 &))))n  $m HHHl  $g '..00 LLJ	3   FFF\  $Y 1333NNE	#93   **,,,)//111#'#G#G#I#IIIIIIIF++.  $- KK0	  
  G!GHHH  $ 0Iw(>S	   mG,,,,,,,,,gk+?@@ '..00 FFF#    }_|  $t####_O	$s   (E= =
G;GGA0I? ?
K	;K

KA$M< +M< <![A1Z<[ AZ<2[ ?BZ<[  [ -:Z<'[ 4BZ<8[ $Z<)[ 6A4Z<*[ 7[ <[[ 	[c                    K   t          j        |                     |                    | _        | j                                         d{V  | j        r| j        dS )z<Create the background Task and wait until ready (or failed).N)r  r  r  r   r!  rv  r  )rp  r  s     r+   startzMCPServerTask.start	
  sf      *488F+;+;<<
k         ; 	+	 	rS   c                   K   | j                                          | j                                         | j        r| j                                        s	 t          j        | j        d           d{V  nr# t
          j        $ r` t          	                    d| j
                   | j                                         	 | j         d{V  n# t
          j        $ r Y nw xY wY nw xY w| j        r`t          | j                  D ]}|                                 t          j        | j        ddi d{V  | j                                         |                                  d| _        dS )z=Signal the Task to exit and wait for clean resource teardown.r[  r  Nz3MCP server '%s' shutdown timed out, cancelling taskreturn_exceptionsT)r"  r3  r#  r   rx  r  r  r  r!   r[   r{  r  r=  r,  r   gatherrz  r  r  rE  s     r+   rr  zMCPServerTask.shutdown
  s       """ 	!!###: 	djoo// 	&tz2>>>>>>>>>>>' 	 	 	II   
!!###*$$$$$$$$-   D	 & 	0T899  .$"=VQUVVVVVVVVV'--///   s7   !A8 8AC'CC'C!C' C!!C'&C'c                     ddl m} t          t          | dg                     D ]&}|                    |           t          |           'g | _        dS )a  Drop this server's tools from the global registry (idempotent).

        Pulls the server's tool schemas out of the registry so the agent
        stops advertising them to the model. Called on shutdown AND when the
        reconnect budget is exhausted, so a dead server never leaves phantom
        tool definitions bloating the prompt cache and producing "not
        connected" errors on every turn.
        r   rX  r(  N)r]  rY  r   r   r_  r`  r(  )rp  rY  r   s      r+   r  zMCPServerTask._deregister_tools.
  sm     	,+++++gd,DbIIJJ 	/ 	/I	***#I....&(###rS   )r   N) r   r  r  r  	__slots__r   rr  r  r5  r:  r?  r  TaskrF  rO  rV  r<  rn  r~  r  r   r  r  r	   rG  r  r  r  r  r  rr  r  rR   rS   r+   r  r    sU        	I2-S 2- 2- 2- 2-h%$ % % % %84 8 8 8 8,X X X         D) ) )VA A AF&H &H &H &HPP P P P Pd!s ! ! ! !FU8t U8 U8 U8 U8t C #'I
 I
 I
I
 $	I

 I
 I
 
I
 I
 I
 I
VKd K K K KZ
 
 
@`$ `$ `$ `$ `$D$      <) ) ) ) ) )rS   r  _servers_server_connecting_server_connect_errors_server_error_counts_server_breaker_opened_atg      N@c                     t                               | d          dz   }|t           | <   |t          k    rt          j                    t
          | <   dS dS )a  Increment the consecutive-failure count for ``server_name``.

    When the count crosses :data:`_CIRCUIT_BREAKER_THRESHOLD`, stamp the
    breaker-open timestamp so the cooldown clock starts (or re-starts,
    for probe failures in the half-open state).
    r   r   N)r  r   _CIRCUIT_BREAKER_THRESHOLDrw  	monotonicr  )r-   ns     r+   _bump_server_errorr  ^
  sV     	  a0014A()%&&&151A1A!+... '&rS   c                 P    dt           | <   t                              | d           dS )zFully close the breaker for ``server_name``.

    Clears both the failure count and the breaker-open timestamp. Call
    this on any unambiguous success signal (successful tool call,
    successful reconnect, manual /mcp refresh).
    r   N)r  r  r  r-   s    r+   r  r  k
  s+     )*%!!+t44444rS   serverc                     t          | dd          }|dS t          }|/|                                r|                    |j                   n|                                 dS )a*  Ask a server task to rebuild its transport, thread-safely.

    The tool handlers run on caller threads, while the server task and its
    ``_reconnect_event`` live on the background MCP loop. Setting an
    asyncio.Event from another thread must go through
    ``loop.call_soon_threadsafe``; only fall back to a direct ``.set()``
    when the loop isn't running (e.g. unit tests that drive the handler
    synchronously).

    Returns True if a reconnect signal was delivered, False if the server
    has no reconnect machinery (nothing to revive).
    r#  NFT)r   	_mcp_loop
is_runningcall_soon_threadsafer3  )r  eventloops      r+   _signal_reconnectr  v
  se     F.55E}uDDOO--!!%),,,,		4rS   rR   _AUTH_ERROR_TYPESc                     t           rt           S g } 	 ddlm}m} |                     ||g           n# t
          $ r Y nw xY w	 ddlm} |                     |           n# t
          $ r Y nw xY w	 ddlm	} |                     |           n# t
          $ r Y nw xY w	 ddl
}|                     |j                   n# t
          $ r Y nw xY wt          |           a t           S )u  Return a tuple of exception types that indicate MCP OAuth failure.

    Cached after first call. Includes:
      - ``mcp.client.auth.OAuthFlowError`` / ``OAuthTokenError`` — raised by
        the SDK's auth flow when discovery, refresh, or full re-auth fails.
      - ``mcp.client.auth.UnauthorizedError`` (older MCP SDKs) — kept as an
        optional import for forward/backward compatibility.
      - ``tools.mcp_oauth.OAuthNonInteractiveError`` — raised by our callback
        handler when no user is present to complete a browser flow.
      - ``httpx.HTTPStatusError`` — caller must additionally check
        ``status_code == 401`` via :func:`_is_auth_error`.
    r   )OAuthFlowErrorOAuthTokenError)UnauthorizedError)OAuthNonInteractiveErrorN)r  mcp.client.authr  r  r;  r   r   r   tools.mcp_oauthr!  r  HTTPStatusErrorr!  )typesr  r  r   r!  r  s         r+   _get_auth_error_typesr&  
  s`     !  ECCCCCCCCno67777   555555&''''   <<<<<<-....   U*++++   esB   2 
??A 
A,+A,0B 
BBB< <
C	C	c                     t                      }|rt          | |          sdS 	 ddl}t          | |j                  rt	          | j        dd          dk    S n# t          $ r Y nw xY wdS )zReturn True if ``exc`` indicates an MCP OAuth failure.

    ``httpx.HTTPStatusError`` is only treated as auth-related when the
    response status code is 401. Other HTTP errors fall through to the
    generic error path in the tool handlers.
    Fr   Nr  i  T)r&  r  r  r$  r   r  r   )r*   r%  r  s      r+   r  r  
  s     "##E 
3.. uc5011 	E3<==DD	E   4s   2A 
A%$A%op_descriptionc                 ^    t          |          sdS ddlm}  |             fd}	 t          |d          }n5# t          $ r(}t
                              d |           d}Y d}~nd}~ww xY w|rt          5  t          	                               ddd           n# 1 swxY w Y   t          d	          rt          }||                                rz|                    j        j                   d
t           ffd}		 t           |	            d           n3# t          $ r&}t
                              d |           Y d}~nd}~ww xY wt#                      	  |            }
	 t%          j        |
          }d|vrt#                      |
S n-# t$          j        t*          f$ r t#                      |
cY S w xY wn4# t          $ r'}t
                              d ||           Y d}~nd}~ww xY wt-                      t%          j        d  d  dd dd          S )aQ  Attempt auth recovery and one retry; return None to fall through.

    Called by the 5 MCP tool handlers when ``session.<op>()`` raises an
    auth-related exception. Workflow:

      1. Ask :class:`tools.mcp_oauth_manager.MCPOAuthManager.handle_401` if
         recovery is viable (i.e., disk has fresh tokens, or the SDK can
         refresh in-place).
      2. If yes, set the server's ``_reconnect_event`` so the server task
         tears down the current MCP session and rebuilds it with fresh
         credentials. Wait briefly for ``_ready`` to re-fire.
      3. Retry the operation once. Return the retry result if it produced
         a non-error JSON payload. Otherwise return the ``needs_reauth``
         error dict so the model stops hallucinating manual refresh.
      4. Return None if ``exc`` is not an auth error, signalling the
         caller to use the generic error path.

    Args:
        server_name: Name of the MCP server that raised.
        exc: The exception from the failed tool call.
        retry_call: Zero-arg callable that re-runs the tool call, returning
            the same JSON string format as the handler.
        op_description: Human-readable name of the operation (for logs).

    Returns:
        A JSON string if auth recovery was attempted, or None to fall
        through to the caller's generic error path.
    Nr   r  c                  @   K                         d            d {V S r  )
handle_401)managerr-   s   r+   _recoverz._handle_auth_error_and_retry.<locals>._recover
  s/      ''T:::::::::rS   r[  r  z+MCP OAuth '%s': recovery attempt failed: %sFr#  r   c                    K   t          j                    dz   } t          j                    | k     rSj        j                                        rdS t          j        d           d {V  t          j                    | k     SdS )N   T      ?F)rw  r  r  r!  ry  r  rT  )deadlinesrvs    r+   _await_readyz2_handle_auth_error_and_retry.<locals>._await_ready  s      #~//"4H.**X55;2sz7H7H7J7J2#'4%mD111111111 .**X55 !5rS   r/  z%MCP OAuth '%s': ready poll failed: %sr\   z.MCP %s/%s retry after auth recovery failed: %sr  z4' requires re-authentication. Run `hermes mcp login u   ` (or delete the tokens file under ~/.hermes/mcp-tokens/ and restart). Do NOT retry this tool — ask the user to re-authenticate.T)r\   needs_reauthr  r  )r  r  r  _run_on_mcp_loopr    r!   r[   r  r  r   r|  r  r  r  r#  r3  r  r  r  r  r  rP   r  r  )r-   r*   
retry_callr(  r  r-  	recoveredrec_excr  r3  rO  r  	retry_excr,  r2  s   `            @@r+   _handle_auth_error_and_retryr:  
  sn   D # t333333kmmG; ; ; ; ; ;$Xr:::		   9	
 	
 	
 						  5 	, 	,,,{++C	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	,?ws,>???DDOO$5$5))#*>*BCCC!D ! ! ! ! ! !$\\^^R@@@@@    NN?#S        	K(((	Z\\FF++&(('444!M ) ()4   #K000 )  	 	 	NN@^Y       	 {###:>; > >%0> > >
 	 	 	 	 	 	s{   > 
A0A++A0=B$$B(+B(D% %
E/EE(
G 3(F G 'GG GG 
G<G77G<)zinvalid or expired sessionzexpired sessionzsession expiredzsession not foundzunknown sessionzsession terminatedclosedresourceerrorzclosed resourceztransport is closedzconnection closedzbroken pipezend of file_SESSION_EXPIRED_MARKERSc                     t          | t                    rdS t          |                                           sdS t	          fdt
          D                       S )u  Return True if ``exc`` looks like an MCP transport session expiry.

    Streamable HTTP MCP servers may garbage-collect server-side session
    state while the OAuth token remains valid — idle TTL, server
    restart, horizontal-scaling pod rotation, etc.  The SDK surfaces
    this as a JSON-RPC error whose message contains phrases like
    ``"Invalid or expired session"``.  This class of failure is
    distinct from :func:`_is_auth_error`: re-running the OAuth refresh
    flow would be pointless because the access token is fine.  What's
    needed is a transport reconnect — tear down and rebuild the
    ``streamablehttp_client`` + ``ClientSession`` pair, which is
    exactly what ``MCPServerTask._reconnect_event`` triggers.
    Fc              3       K   | ]}|v V  	d S r  rR   )r   markerr   s     r+   r  z,_is_session_expired_error.<locals>.<genexpr>z  s'      DDv}DDDDDDrS   )r  InterruptedErrorr   r   r  r<  )r*   r   s    @r+   _is_session_expired_errorrA  c  se     #'(( u
 c((..

C uDDDD+CDDDDDDrS   c                    t          |          sdS t          5  t                              |           }ddd           n# 1 swxY w Y   |t	          |d          sdS t
          }||                                sdS t                              d| ||           |	                    |j
        j                   t          j                    dz   }d}t          j                    |k     rN|j        |j                                        rd}n+t          j        d           t          j                    |k     N|st                              d|            dS 	  |            }	 t'          j        |          }	d	|	vrd
t*          | <   |S n(# t&          j        t.          f$ r d
t*          | <   |cY S w xY wn4# t0          $ r'}
t                              d| ||
           Y d}
~
nd}
~
ww xY wdS )uO  Trigger a transport reconnect and retry once on session expiry.

    Unlike :func:`_handle_auth_error_and_retry`, this does **not** call
    the OAuth manager's ``handle_401`` — the access token is still
    valid, only the server-side session state is stale.  Setting
    ``_reconnect_event`` causes the server task's lifecycle loop to
    tear down the current ``streamablehttp_client`` + ``ClientSession``
    and rebuild them, reusing the existing OAuth provider instance.
    See #13383.

    Args:
        server_name: Name of the MCP server that raised.
        exc: The exception from the failed call.
        retry_call: Zero-arg callable that re-runs the operation,
            returning the same JSON string format as the handler.
        op_description: Human-readable name of the operation (logs).

    Returns:
        A JSON string if reconnect + retry was attempted and produced
        a response, or ``None`` to fall through to the caller's
        generic error path (not a session-expired error, no server
        record, reconnect didn't ready in time, or retry also failed).
    Nr#  zmMCP server '%s': %s failed with session-expired error (%s); signalling transport reconnect and retrying once.r/  FTr0  zsMCP server '%s': reconnect did not ready within 15s after session-expired error; falling through to error response.r\   r   z2MCP %s/%s retry after session reconnect failed: %s)rA  r  r  r   r|  r  r  r!   rY   r  r#  r3  rw  r  r  r!  ry  rT  r[   r  r  r  r  rP   r    )r-   r*   r6  r(  r2  r  r1  readyrO  r  r9  s              r+   !_handle_session_expired_and_retryrD  }  s~   : %S)) t	 ( (ll;''( ( ( ( ( ( ( ( ( ( ( ( ( ( (
{'#'9::{tD|4??,,|t
KK	<^S   	c26777~"$HE
.

X
%
%;"sz'8'8':':"E
4	 .

X
%
%
  H	
 	
 	

 t
	Z''Ff$$45$[1 % $i0 	 	 	01 -MMM	 %  
 
 
@	
 	
 	
 	
 	
 	
 	
 	


 4sM   A  AA
F0 "#F F0 "F,)F0 +F,,F0 0
G!:GG!_parallel_safe_servers_mcp_tool_server_namesr  _mcp_threadr  r  r  c                     t          j                    } 	 d|  d|  d}t          |d          5 }d |                                                                D             cddd           S # 1 swxY w Y   n# t
          t          t          f$ r Y nw xY w	 ddl}d	 |	                    |           
                                D             S # t          $ r Y nw xY wt                      S )
zReturn a set of current child process PIDs.

    Uses /proc on Linux, falls back to psutil, then empty set.
    Used by _run_stdio to identify the subprocess spawned by stdio_client.
    z/proc/z/task/z	/childrenr   r   c                 T    h | ]%}|                                 t          |          &S rR   )r   rf  )r   ps     r+   r\  z'_snapshot_child_pids.<locals>.<setcomp>  s+    BBBq		BCFFBBBrS   Nr   c                     h | ]	}|j         
S rR   )r  )r   cs     r+   r\  z'_snapshot_child_pids.<locals>.<setcomp>  s    AAA!AAArS   )r#   getpidr   r  r   r  r  rQ   psutilProcesschildrenr    r3  )my_pidchildren_pathfrN  s       r+   r  r     s\    Y[[F@@@v@@@-'222 	CaBBAFFHHNN$4$4BBB	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	Cw
3   AAv~~f55>>@@AAAA    55LsF   A8 0A,A8 ,A00A8 3A04A8 8BB4C 
CC)ztui_gateway.slash_workerztui_gateway.entryz-dorg.eclipse.equinox.launcherzeclipse.jdt.lszorg.eclipse.equinox.launcher_._NON_MCP_CHILD_CMDLINE_MARKERSpidsc                 ^   | s| S 	 ddl }n# t          $ r | cY S w xY wt                      }| D ]}	 |                    |                                          }n# |j        |j        t          f$ r Y Dw xY wt          d |dd         D                       rj|	                    |           |S )a  Remove non-MCP children from a PID snapshot delta.

    _snapshot_child_pids() returns *all* direct children of the gateway. When
    a stdio MCP server spawns concurrently with a slash_worker or LSP server
    spawn, the delta ``_snapshot_child_pids() - pids_before`` can include
    PIDs that are NOT the MCP server. Tracking those PIDs in _stdio_pgids is
    catastrophic if a future child lacks start_new_session: its pgid can be the
    TUI parent's PID, so the shutdown sweep's killpg() kills the TUI itself.
    r   Nc              3   2   K   | ]}t           D ]}||v V  	d S r  )rT  )r   argr?  s      r+   r  z'_filter_mcp_children.<locals>.<genexpr>B  sQ       
 
8
 
  cM
 
 
 
 
 
 
rS   r   )
rN  r   r3  rO  cmdlineNoSuchProcessAccessDeniedr  r  rB  )rU  rN  filteredr  argvs        r+   r  r  )  s	         EEH  	>>#&&..00DD$f&97C 	 	 	 H	  
 
ABBx
 
 
 
 
 	
 SOs    'AA21A2c                     |                     d          }t          |t                    rdt          |          v rdS |                     |           dS )a  Suppress benign 'Event loop is closed' noise during shutdown.

    When the MCP event loop is stopped and closed, httpx/httpcore async
    transports may fire __del__ finalizers that call call_soon() on the
    dead loop.  asyncio catches that RuntimeError and routes it here.
    We silence it because the connection is being torn down anyway; all
    other exceptions are forwarded to the default handler.
    r>  zEvent loop is closedN)r   r  RuntimeErrorr   default_exception_handler)r  r  r*   s      r+   _mcp_loop_exception_handlerra  L  sW     ++k
"
"C#|$$ )?3s88)K)K""7+++++rS   c                  z   t           5  t          't                                          r	 ddd           dS t          j                    at                              t                     t          j        t          j	        dd          a
t                                           ddd           dS # 1 swxY w Y   dS )z>Start the background event loop thread if not already running.Nzmcp-event-loopT)r  r{  daemon)r  r  r  r  new_event_loopset_exception_handlerra  	threadingThreadrun_foreverrG  r  rR   rS   r+   _ensure_mcp_loopri  [  s    
 
 
 Y%9%9%;%; 
 
 
 
 
 
 
 
 *,,	''(CDDD&(!
 
 

 	
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   "B0A,B00B47B4coror   c                      	 ddl m}mm  |            n# t          $ r  cY S w xY ws S  fd} |            S )uW  Carry the caller's context-local HERMES_HOME override into ``coro``.

    Returns ``coro`` unchanged when no override is active. Otherwise wraps
    it so the override is set inside the coroutine's own (task-local)
    context on the MCP loop and reset when it completes — concurrent calls
    carrying different scopes don't interfere.
    r   )get_hermes_home_overridereset_hermes_home_overrideset_hermes_home_overridec                  h   K              } 	  d {V 	  |            S #  |            w xY wr  rR   )tokenrj  home_overriderm  rn  s    r+   _scopedz)_wrap_with_home_override.<locals>._scoped  sZ      ((77	.::::::&&u----&&u----s   $ 1)r   rl  rm  rn  r    )rj  rl  rr  rq  rm  rn  s   `  @@@r+   _wrap_with_home_overriders  k  s    		
 	
 	
 	
 	
 	
 	
 	
 	
 	
 1022    . . . . . . . . 799s    **r]  r\  c                    ddl m} ddlm} t          5  t
          }ddd           n# 1 swxY w Y   ||                                s7t          j        |           r| 	                                 t          d          t          |           r
 |             n| }t          |          } |||t          d          }|t          d          t          j                    }|dn||z   }	  |            r#|                                 t#          d
          d}	|{|t          j                    z
  }
|
dk    rO|                                 t          j                    |z
  }t%          d|ddt'          |          dd          t)          |	|
          }		 |                    |	          S # t,          j        j        $ r Y w xY w)a  Schedule a coroutine on the MCP event loop and block until done.

    Accepts either a coroutine object or a zero-arg callable that returns one.
    Callers can pass a factory to avoid constructing coroutine objects when
    the MCP loop is unavailable (which would otherwise leak the coroutine
    frame and emit ``"coroutine was never awaited"`` warnings).

    Poll in short intervals so the calling agent thread can honor user
    interrupts while the MCP work is still running on the background loop.
    r   )is_interruptedsafe_schedule_threadsafeNzMCP event loop is not runningzMCP scheduling failedr!   log_messagez/MCP event loop unavailable (failed to schedule)TzUser sent a new messageg?zMCP call timed out after z.1fzs (configured timeout: zs)r  )tools.interruptru  agent.async_utilsrw  r  r  r  r  iscoroutinecloser_  callablers  r!   rw  r  r  r@  r  rG  r  rO  
concurrentfutures)coro_or_factoryr\  ru  rw  r  rj  future
start_timer1  wait_timeout	remainingelapseds               r+   r5  r5    sa    /.....::::::	                |4??,,|// 	$!!###:;;; ( 9 9N??D $D))D%%d+  F
 ~LMMM!!JttJ,@H> 	>MMOOO"#<=== 4>#3#33IA~~.**Z7"C? C C,1'NNBC C C   |Y77L	===666!. 	 	 	H	s   (,,F/ /GGc                  2    t          j        ddid          S )z=Standardized JSON error for a user-interrupted MCP tool call.r\   z-MCP call interrupted: user sent a new messageFr  )r  r  rR   rS   r+   _interrupted_call_resultr    s)    :@   rS   c                 &   ddl m t          | t                    r fd}t                              ||           S t          | t                    rd |                                 D             S t          | t                    rd | D             S | S )u9  Recursively resolve ``${VAR}`` placeholders.

    Both ``${VAR}`` and Cursor-style ``${env:VAR}`` are accepted — the
    ``env:`` prefix is stripped so a doc copied from a Cursor / Claude MCP
    config resolves the same secret. Resolves from the active profile's secret
    scope when multiplexing is on (so an MCP server config's ``${API_KEY}``
    picks up the routed profile's value, not the process-global ``os.environ``
    which may hold another profile's), falling back to ``os.environ``
    otherwise. Unset vars keep the literal placeholder, as before.
    r   )
get_secretc                     t          |                     d                    } ||                     d                    p|                     d          S )Nr   r   )r   r1  )mr{  _get_secrets     r+   _replacez'_interpolate_env_vars.<locals>._replace  sE     ,,D;tQWWQZZ00>AGGAJJ>rS   c                 4    i | ]\  }}|t          |          S rR   _interpolate_env_varsr   kvs      r+   
<dictcomp>z)_interpolate_env_vars.<locals>.<dictcomp>  s'    FFF1(++FFFrS   c                 ,    g | ]}t          |          S rR   r  )r   r  s     r+   r   z)_interpolate_env_vars.<locals>.<listcomp>  s!    888Q%a((888rS   )	agent.secret_scoper  r  r   _ENV_VAR_PATTERNr   r   r   r   )r   r  r  s     @r+   r  r    s     =<<<<<% 5	? 	? 	? 	? 	?  ##He444% GFFFFFF% 988%8888LrS   serversc                 6   	 ddl m} n# t          $ r d}Y nw xY w|| S i }|                                 D ]c\  }}t	          |t
                    s|||<     |||          }|r0t                              d|d                    |                     ^|||<   d|S )zADrop exfiltration-shaped MCP configs before any stdio spawn path.r   )validate_mcp_server_entryNz'Skipping suspicious MCP server '%s': %sr   )	hermes_cli.mcp_securityr  r    r   r  r   r!   r[   r   )r  _validate_mcp_server_entrysafe_serversr{  cfgissuess         r+   _filter_suspicious_mcp_serversr    s    ]ccccccc ] ] ]X\"""] ")L]]__ ! !	c#t$$ 	!$L++D#66 	NN9		&!!  
  Ts   	 c                     	 ddl m}  ddlm}  |d          ri S  |             }|                    d          }|rt          |t                    si S 	 ddlm}  |             n# t          $ r Y nw xY wi }t          |                                          D ].\  }}t          |          }t          |t                    r|||<   /|S # t          $ r'}	t                              d|	           i cY d}	~	S d}	~	ww xY w)	a  Read ``mcp_servers`` from the Hermes config file.

    Returns a dict of ``{server_name: server_config}`` or empty dict.
    Server config can contain either ``command``/``args``/``env`` for stdio
    transport or ``url``/``headers`` for HTTP transport, plus optional
    ``timeout``, ``connect_timeout``, and ``auth`` overrides.

    ``${ENV_VAR}`` placeholders in string values are resolved from
    ``os.environ`` (which includes ``~/.hermes/.env`` loaded at startup).
    r   )load_config)env_var_enabledHERMES_SAFE_MODEmcp_servers)load_hermes_dotenvzFailed to load MCP config: %sN)hermes_cli.configr  utilsr  r   r  r   hermes_cli.env_loaderr  r    r  r   r  r!   r"   )
r  _env_enabledr  r  r  r  r{  r  interpolatedr*   s
             r+   _load_mcp_configr    sg   111111 	:99999<*++ 	I**]++ 	j$77 	I	@@@@@@     	 	 	D	(*7@@FFHH 	2 	2ID#055L,-- 2%1T"   4c:::						sG   C	 7C	 A% $C	 %
A2/C	 1A22AC	 	
C:C5/C:5C:r{  c                 ^   K   t          |           }|                    |           d{V  |S )a  Create an MCPServerTask, start it, and return when ready.

    The server Task keeps the connection alive in the background.
    Call ``server.shutdown()`` (on the same event loop) to tear it down.

    Raises:
        ValueError: if required config keys are missing.
        ImportError: if HTTP transport is needed but not available.
        Exception: on connection or initialization failure.
    N)r  r  )r{  r  r  s      r+   _connect_serverr  8  s>       4  F
,,v

MrS   r  c                 8     dt           dt          f fd}|S )zReturn a sync handler that calls an MCP tool via the background loop.

    The handler conforms to the registry's dispatch interface:
    ``handler(args_dict, **kwargs) -> str``
    r  r   c                    
 t                               d          t          k    rt                              d          }t	          j                    |z
  }|t          k     rRt          dt          t          |z
                      }t          j
        dd dt                     d| did	
          S t          5  t                                        d d d            n# 1 swxY w Y   s+t                     t          j
        dd did	
          S j        sVt                     t                    rt          j
        dd did	
          S t          j
        dd did	
          S  fd

fd}	  |            }	 t          j        |          }d|v rt                     nt#                     n+# t          j        t&          f$ r t#                     Y nw xY w|S # t(          $ r t+                      cY S t,          $ r}t/          ||d           }	|	|	cY d }~S t1          ||d           }	|	|	cY d }~S t                     t2                              d|           t          j
        dt7          dt9          |          j         dt=          |                     id	
          cY d }~S d }~ww xY w)Nr   g        r   r\   r  z' is unreachable after z0 consecutive failures. Auto-retry available in ~ue   s. Do NOT retry this tool yet — use alternative approaches or ask the user to check the MCP server.Fr  ' is not connectedut   ' transport is down; reconnect requested. Do NOT retry this tool immediately — give it a few seconds to come back.c                  p  K   j         4 d {V  t          j                    _        	 j                            	           d {V } d _        n# d _        w xY w	 d d d           d {V  n# 1 d {V swxY w Y   | j        rOd}| j        pg D ]}t          |d          r
||j	        z  }t          j        dt          |pd          id          S g }| j        pg D ]Z}t          |d          r"|j	        r|                    |j	                   4t          |          }|r|                    |           [|rd                    |          nd}t!          | d	d           }|3|rt          j        ||d
d          S t          j        d|id          S t          j        d|id          S )Nr  r   r   r\   zMCP tool returned an errorFr  r  structuredContent)rO  r  rO  )r+  contextvarscopy_contextr  r  	call_toolisErrorr  r|  r   r  r  r   r   r   r   r   )
rO  
error_textr   r   	image_tagtext_result
structuredr  r  r   s
          r+   _callz3_make_tool_handler.<locals>._handler.<locals>._call  s     ' 	8 	8 	8 	8 	8 	8 	8 	8
 0;/G/I/I,8#)>#;#;IQU#;#V#VVVVVVVF37F004F077777	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 ~ 	'
$n2 1 1Euf-- 1"ej0
z_"B&B # !&	' ' ' '"  "E ..B , ,5&)) ej LL,,,2599	 ,LL+++.3;$))E***K !)<dCCJ% +:"--7' ' %*+ + + + z8Z"8uMMMM:x5EJJJJs(   A4"AA4	AA44
A>A>c                  &    t                     S Nr  r5  r  r  s   r+   
_call_oncez8_make_tool_handler.<locals>._handler.<locals>._call_once      #E<@@@@rS   ztools/call zMCP tool %s/%s call failed: %sMCP call failed: r  )r  r   r  r  rw  r  _CIRCUIT_BREAKER_COOLDOWN_SECrJ  rf  r  r  r  r  r  r  r  r  r  r  rP   r@  r  r    r:  rD  r!   r\   r   r  r   r   )r  r  	opened_atager  r  rO  r  r*   r7  r  r  r-   r   r  s   `         @@r+   rU  z$_make_tool_handler.<locals>._handlerS  sg     ##K337QQQ155k3GGI.""Y.C2223'Ds'J#K#KLL	zO{ O O/<O O>GO O O# !&' ' ' '  	/ 	/\\+..F	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	#{+++:GGGG!# # # # ~ 	# {+++ (( 'zO{ O O O# !&' ' ' ' :GGGG!# # # #8	K 8	K 8	K 8	K 8	K 8	K 8	Kt	A 	A 	A 	A 	A 	A,	#Z\\F1F++f$$&{3333'444()4 1 1 1#K000001M 	. 	. 	.+----- 	# 	# 	# 5S*)i)) I $       
 :S*)i)) I $       {+++LL0Y   :MS		(:MMhsmmMM  "	# # # # # # # # #5	#ss   >C%%C),C)
G8 7G 
G8 %G30G8 2G33G8 8K	KK3K9KKA5KKKr   r   )r-   r   r  rU  s   ``` r+   _make_tool_handlerr  L  sM    c#t c## c# c# c# c# c# c# c# c#J OrS   c                 4     dt           dt          f fd}|S )z>Return a sync handler that lists resources from an MCP server.r  r   c                    t           5  t                                        d d d            n# 1 swxY w Y   rj        st	          j        dd did          S fdfd}	  |            S # t          $ r t                      cY S t          $ r}t          ||d          }||cY d }~S t          ||d          }||cY d }~S t                              d	|           t	          j        dt          d
t          |          j         dt!          |                     id          cY d }~S d }~ww xY w)Nr\   r  r  Fr  c                  H  K   j         4 d {V  j                                         d {V } d d d           d {V  n# 1 d {V swxY w Y   g }t          | d          r| j        ng D ]}i }t          |d          rt          |j                  |d<   t          |d          r
|j        |d<   t          |d          r|j        r
|j        |d<   t          |d          r|j	        r
|j	        |d<   |
                    |           t          j        d|id          S )N	resourcesurir{  r   r   Fr  )r+  r  list_resourcesr|  r  r   r  r{  r   r   r   r  r  )rO  r  rentryr  s       r+   r  z=_make_list_resources_handler.<locals>._handler.<locals>._call  s     ' ? ? ? ? ? ? ? ?%~<<>>>>>>>>? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?I*1&+*F*FNf&&B 
( 
(1e$$ .#&qu::E%L1f%% +$%FE&M1m,, 9 9+,=E-(1j)) 3aj 3()
E*%  '''':{I6UKKKK    A
AAc                  &    t                     S r  r  r  s   r+   r  zB_make_list_resources_handler.<locals>._handler.<locals>._call_once  r  rS   zresources/listz MCP %s/list_resources failed: %sr  r  r  r  r   r  r  r  r@  r  r    r:  rD  r!   r\   r   r  r   r   	r  r  r  r*   r7  r  r  r-   r  s	        @@r+   rU  z._make_list_resources_handler.<locals>._handler  sB    	/ 	/\\+..F	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	#V^ 	#:GGGG!# # # #	L 	L 	L 	L 	L"	A 	A 	A 	A 	A 	A	#:<< 	. 	. 	.+----- 	# 	# 	#4S*.> I $       9S*.> I $       LL2K   :MS		(:MMhsmmMM  "	# # # # # # # # #	#I   266.	A8 8E	ED<0E6D<EA%D<6E<Er  r-   r  rU  s   `` r+   _make_list_resources_handlerr    s=    2#t 2## 2# 2# 2# 2# 2# 2# 2#h OrS   c                 4     dt           dt          f fd}|S )zFReturn a sync handler that reads a resource by URI from an MCP server.r  r   c                    ddl m} t          5  t                              	          d d d            n# 1 swxY w Y   rj        st          j        dd	 did          S |                     d          s |d	          S fd

fd}	  |            S # t          $ r t                      cY S t          $ r}t          	||d          }||cY d }~S t          	||d          }||cY d }~S t                              d	|           t          j        dt          dt!          |          j         dt%          |                     id          cY d }~S d }~ww xY w)Nr   
tool_errorr\   r  r  Fr  r  z Missing required parameter 'uri'c                    K   j         4 d {V  j                                       d {V } d d d           d {V  n# 1 d {V swxY w Y   g }t          | d          r| j        ng }|D ]h}t          |d          r|                    |j                   -t          |d          r+|                    dt          |j                   d           it          j
        d|rd                    |          ndid	
          S )Ncontentsr   blobz[binary data, z bytes]rO  r  r   Fr  )r+  r  read_resourcer|  r  r   r   r   r  r  r  r   )rO  r   r  r   r  r  s       r+   r  z<_make_read_resource_handler.<locals>._handler.<locals>._callF  s     ' A A A A A A A A%~;;C@@@@@@@@A A A A A A A A A A A A A A A A A A A A A A A A A A A  "E*1&**E*EMv2H! L L5&)) LLL,,,,UF++ LLL!J#ej//!J!J!JKKK:xU)J5)9)9)9KZ_````s   !A
AAc                  &    t                     S r  r  r  s   r+   r  zA_make_read_resource_handler.<locals>._handler.<locals>._call_onceS  r  rS   zresources/readzMCP %s/read_resource failed: %sr  r  r]  r  r  r  r   r  r  r  r@  r  r    r:  rD  r!   r\   r   r  r   r   )r  r  r  r  r*   r7  r  r  r  r-   r  s         @@@r+   rU  z-_make_read_resource_handler.<locals>._handler8  s   ------ 	/ 	/\\+..F	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	#V^ 	#:GGGG!# # # # hhuoo 	B:@AAA	a 	a 	a 	a 	a 	a	A 	A 	A 	A 	A 	A	#:<< 	. 	. 	.+----- 	# 	# 	#4S*.> I $       9S*.> I $       LL1;   :MS		(:MMhsmmMM  "	# # # # # # # # #	#sJ   9= =	B" "E+<	E+E&E+ E&5E+;A%E& E+&E+r  r  s   `` r+   _make_read_resource_handlerr  5  s=    4#t 4## 4# 4# 4# 4# 4# 4# 4#l OrS   c                 4     dt           dt          f fd}|S )z<Return a sync handler that lists prompts from an MCP server.r  r   c                    t           5  t                                        d d d            n# 1 swxY w Y   rj        st	          j        dd did          S fdfd}	  |            S # t          $ r t                      cY S t          $ r}t          ||d          }||cY d }~S t          ||d          }||cY d }~S t                              d	|           t	          j        dt          d
t          |          j         dt!          |                     id          cY d }~S d }~ww xY w)Nr\   r  r  Fr  c                    K   j         4 d {V  j                                         d {V } d d d           d {V  n# 1 d {V swxY w Y   g }t          | d          r| j        ng D ]}i }t          |d          r
|j        |d<   t          |d          r|j        r
|j        |d<   t          |d          r|j        rd |j        D             |d<   |                    |           t          j
        d|id          S )Npromptsr{  r   r  c                     g | ]H}d |j         it          |d          r|j        r	d|j        ini t          |d          r	d|j        ini IS )r{  r   required)r{  r|  r   r  )r   r   s     r+   r   zO_make_list_prompts_handler.<locals>._handler.<locals>._call.<locals>.<listcomp>  s     * * * 	 #AFAHMAZAZt_`_ltq}==rt <C1j;Q;QY
AJ77WY* * *rS   Fr  )r+  r  list_promptsr|  r  r{  r   r  r   r  r  )rO  r  rJ  r  r  s       r+   r  z;_make_list_prompts_handler.<locals>._handler.<locals>._call|  s     ' = = = = = = = =%~::<<<<<<<<= = = = = = = = = = = = = = = = = = = = = = = = = = =G(/	(B(BJfnn & &1f%% +$%FE&M1m,, 9 9+,=E-(1k** q{ * * "#* * *E+& u%%%%:y'2GGGGr  c                  &    t                     S r  r  r  s   r+   r  z@_make_list_prompts_handler.<locals>._handler.<locals>._call_once  r  rS   zprompts/listzMCP %s/list_prompts failed: %sr  r  r  r  s	        @@r+   rU  z,_make_list_prompts_handler.<locals>._handlert  s@    	/ 	/\\+..F	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	#V^ 	#:GGGG!# # # #	H 	H 	H 	H 	H,	A 	A 	A 	A 	A 	A	#:<< 	. 	. 	.+----- 	# 	# 	#4S*n I $       9S*n I $       LL0+s   :MS		(:MMhsmmMM  "	# # # # # # # # #	#r  r  r  s   `` r+   _make_list_prompts_handlerr  q  s=    7#t 7## 7# 7# 7# 7# 7# 7# 7#r OrS   c                 4     dt           dt          f fd}|S )zDReturn a sync handler that gets a prompt by name from an MCP server.r  r   c                   	 ddl m} t          5  t                              
          	d d d            n# 1 swxY w Y   	r	j        st          j        dd
 did          S |                     d          s |d	          S |                     d
i           	fdfd}	  |            S # t          $ r t                      cY S t          $ r}t          
||d          }||cY d }~S t          
||d          }||cY d }~S t                              d
|           t          j        dt          dt!          |          j         dt%          |                     id          cY d }~S d }~ww xY w)Nr   r  r\   r  r  Fr  r{  z!Missing required parameter 'name'r  c                    K   j         4 d {V  j                                       d {V } d d d           d {V  n# 1 d {V swxY w Y   g }t          | d          r| j        ng D ]}i }t          |d          r
|j        |d<   t          |d          rO|j        }t          |d          r|j        |d<   n-t          |t                    r||d<   nt          |          |d<   |
                    |           d|i}t          | d          r| j        r
| j        |d<   t          j        |d          S )	Nr  r>  r  r  r   r   Fr  )r+  r  
get_promptr|  r>  r  r  r   r  r   r   r   r  r  )	rO  r>  r   r  r  r  r  r{  r  s	         r+   r  z9_make_get_prompt_handler.<locals>._handler.<locals>._call  s!     ' T T T T T T T T%~888SSSSSSSST T T T T T T T T T T T T T T T T T T T T T T T T T T H+26:+F+FNB ' '3'' -$'HE&M3	** 8!kGw// 8+2<i((#GS11 8+2i((+.w<<i(&&&&)Dv}-- 9&2D 9&,&8]#:d7777s   #A
AAc                  &    t                     S r  r  r  s   r+   r  z>_make_get_prompt_handler.<locals>._handler.<locals>._call_once  r  rS   zprompts/getzMCP %s/get_prompt failed: %sr  r  r  )r  r  r  r  r*   r7  r  r  r{  r  r-   r  s         @@@@r+   rU  z*_make_get_prompt_handler.<locals>._handler  s   ------ 	/ 	/\\+..F	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	#V^ 	#:GGGG!# # # # xx 	C:ABBBHH["--		8 	8 	8 	8 	8 	8 	8.	A 	A 	A 	A 	A 	A	#:<< 	. 	. 	.+----- 	# 	# 	#4S*m I $       9S*m I $       LL.S   :MS		(:MMhsmmMM  "	# # # # # # # # #	#sJ   :>>0	B: :F	FE>2F8E>FA%E>8F>Fr  r  s   `` r+   _make_get_prompt_handlerr    s=    ?#t ?## ?# ?# ?# ?# ?# ?# ?#B OrS   c                 "     dt           f fd}|S )zBReturn a check function that verifies the MCP connection is alive.r   c                      t           5  t                                        } d d d            n# 1 swxY w Y   | d uo| j        d uS r  )r  r  r   r  )r  r-   s    r+   _checkz_make_check_fn.<locals>._check  s     	/ 	/\\+..F	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/T!@fnD&@@s   044)r  )r-   r  s   ` r+   _make_check_fnr    s6    AD A A A A A A
 MrS   c                     | sdi dS fdd }fd |           } ||          } |          }t          |t                    sdi dS |                    d          dk    rd|vri |di i}|S )ad  Normalize MCP input schemas for LLM tool-calling compatibility.

    MCP servers can emit plain JSON Schema with ``definitions`` /
    ``#/definitions/...`` references.  Kimi / Moonshot rejects that form and
    requires local refs to point into ``#/$defs/...`` instead.  Normalize the
    common draft-07 shape here so MCP tool schemas remain portable across
    OpenAI-compatible providers.

    Additional MCP-server robustness repairs applied recursively:

    * Missing or ``null`` ``type`` on an object-shaped node is coerced to
      ``"object"`` (some servers omit it).  See PR #4897.
    * When an ``object`` node lacks ``properties``, an empty ``properties``
      dict is added so ``required`` entries don't dangle.
    * ``required`` arrays are pruned to only names that exist in
      ``properties``; otherwise Google AI Studio / Gemini 400s with
      ``property is not defined``.  See PR #4651.
    * MCP/Pydantic optional fields commonly arrive as
      ``anyOf: [{...}, {"type": "null"}], default: null``.  Anthropic rejects
      nullable branches in tool input schemas, so nullable unions are collapsed
      to the non-null branch and optionality remains represented solely by the
      parent object's ``required`` list.

    All repairs are provider-agnostic and ideally produce a schema valid on
    OpenAI, Anthropic, Gemini, and Moonshot in one pass.
    objectr  r  c                    t          | t                    ri }|                                 D ]Z\  }}|dv r9t          |t                    r$fd|                                D             ||<   B|dk    rdn|} |          ||<   [|                    d          }t          |t                    r2|                    d          rd|t          d          d         z   |d<   |S t          | t                    rfd	| D             S | S )
a  Walk the schema, promoting legacy ``definitions`` to ``$defs``.

        The promotion is contextual: ``definitions`` is renamed only when it
        appears as a JSON Schema *meta-keyword* (sibling of ``properties`` /
        ``$ref`` at a schema node), never when it appears as the *name of a
        property* (i.e., as a key inside a ``properties`` dict).

        Without this gate, MCP servers that legitimately expose a tool
        parameter named ``definitions`` (e.g. a CI/pipelines tool that uses
        ``definitions`` for an array of pipeline-definition IDs) would have
        that user-facing property name silently rewritten to ``$defs``.
        Anthropic and OpenAI both reject ``$`` in property names
        (``^[a-zA-Z0-9_.-]{1,64}$``), so the whole tool array gets a 400 and
        every conversation breaks.

        The gate works by treating ``properties`` and ``patternProperties``
        specially during descent: we iterate the property-name -> schema map
        directly, leaving the property names verbatim, then recurse into each
        property's schema where ordinary JSON Schema semantics resume (so any
        legitimately-nested ``definitions`` meta-keyword inside a property's
        schema is still promoted).
        )r  patternPropertiesc                 .    i | ]\  }}| |          S rR   rR   )r   	prop_nameprop_schema_rewrite_local_refss      r+   r  zL_normalize_mcp_input_schema.<locals>._rewrite_local_refs.<locals>.<dictcomp>C  s;     ' ' '2I{ "#6#6{#C#C' ' 'rS   definitionsz$defsz$refz#/definitions/z#/$defs/Nc                 &    g | ]} |          S rR   rR   )r   rD  r   s     r+   r   zL_normalize_mcp_input_schema.<locals>._rewrite_local_refs.<locals>.<listcomp>O  s%    ???$''--???rS   )r  r   r   r   r   r   r   r   )r   r   r   r   out_keyr   r   s         r+   r   z8_normalize_mcp_input_schema.<locals>._rewrite_local_refs$  sL   . dD!! 	J"jjll E E
U===*UTXBYBY=
' ' ' '6;kkmm' ' 'JsOO
 *-)=)=gg3G*=*=e*D*DJw''..((C#s## N7G(H(H N%/#c:J6K6K6L6L2M%M
6"dD!! 	@????$????rS   c                 (    ddl m}  || d          S )a  Collapse JSON Schema nullable unions to provider-safe non-null schemas.

        Delegates to ``tools.schema_sanitizer.strip_nullable_unions`` so MCP
        ingestion, the Anthropic guard, and the global sanitizer all share one
        implementation. Keeps the ``nullable: true`` hint so runtime argument
        coercion can still map a model-emitted ``"null"`` string to Python
        ``None`` for this optional field.
        r   )strip_nullable_unionsT)keep_nullable_hint)tools.schema_sanitizerr  )r   r  s     r+   _strip_nullable_unionz:_normalize_mcp_input_schema.<locals>._strip_nullable_unionR  s-     	A@@@@@$$TdCCCCrS   c                 "   t          | t                    rfd| D             S t          | t                    s| S fd|                                 D             }|                    d          sd|v sd|v rd|d<   |                    d          dk    rd|vs(t          |                    d          t                    s>d|vri n|d         |d<   t          |                    d          t                    si |d<   |                    d          }t          |t                    rc|                    d          pi fd|D             }t          |          t          |          k    r|r||d<   n|                    dd           |S )	zBRecursively repair object-shaped nodes: fill type, prune required.c                 &    g | ]} |          S rR   rR   )r   rD  _repair_object_shapes     r+   r   zM_normalize_mcp_input_schema.<locals>._repair_object_shape.<locals>.<listcomp>b  s%    @@@4((..@@@rS   c                 .    i | ]\  }}| |          S rR   rR   )r   r  r  r  s      r+   r  zM_normalize_mcp_input_schema.<locals>._repair_object_shape.<locals>.<dictcomp>f  s+    HHH41aA++A..HHHrS   r  r  r  r  c                 F    g | ]}t          |t                    |v |S rR   )r  r   )r   r  r  s     r+   r   zM_normalize_mcp_input_schema.<locals>._repair_object_shape.<locals>.<listcomp>|  s-    RRRq
1c0B0BRqEzzzzzrS   N)r  r   r   r   r   r   r  )r   repairedr  validr  r  s       @r+   r  z9_normalize_mcp_input_schema.<locals>._repair_object_shape_  s   dD!! 	A@@@@4@@@@$%% 	KHHHH4::<<HHH ||F## 	(H$$
h(>(>'HV<<8++8++:\**D4 4+ 0<8/K/KQYZfQg&!(,,|"<"<dCC 0-/H\*  ||J//H(D)) 7 \228bRRRRHRRRu::X.. 7/4,, Z666rS   r  r  )r  r   r   )r  r  r   r  r   s      @@r+   r  r    s    6  4 333, , , , ,\D D D$ $ $ $ $L %$V,,J&&z22J%%j11J j$'' 4 333~~f))l*.L.L5
5L"55
rS   r   c                 L    t          j        ddt          | pd                    S )a5  Return an MCP name component safe for tool and prefix generation.

    Preserves Hermes's historical behavior of converting hyphens to
    underscores, and also replaces any other character outside
    ``[A-Za-z0-9_]`` with ``_`` so generated tool names are compatible with
    provider validation rules.
    z[^A-Za-z0-9_]_r   )r0  r   r   )r   s    r+   sanitize_mcp_name_componentr    s%     6"CU[b)9)9:::rS   mcp____c                 f    t          |           }t          |          }t           | t           | S )zmBuild the registry/wire name for an MCP tool.

    Produces ``mcp__<sanitizedServer>__<sanitizedTool>``.
    )r  MCP_TOOL_NAME_PREFIX_MCP_NAME_DELIM)r-   r   safe_server	safe_tools       r+   r[  r[    s9    
 .k::K+I66I"MKMM)MMMrS   c           	          t          | |j                  }||j        pd|j         d|  t          t	          |dd                    dS )aS  Convert an MCP tool listing to the Hermes registry schema format.

    Args:
        server_name: The logical server name for prefixing.
        mcp_tool:    An MCP ``Tool`` object with ``.name``, ``.description``,
                     and ``.inputSchema``.

    Returns:
        A dict suitable for ``registry.register(schema=...)``.
    z	MCP tool z from r  Nr  )r[  r{  r   r  r   )r-   mcp_toolprefixed_names      r+   _convert_mcp_schemar    s^     +;FFM+]/]8=/]/]P[/]/]1'(MSW2X2XYY  rS   c                    t          | d          d|  ddi ddddt          | d          d	|  ddd
dddid
gddddt          | d          d|  ddi ddddt          | d          d|  dddddddi ddddgddddgS )zBuild schemas for the MCP utility tools (resources & prompts).

    Returns a list of (schema, handler_factory_name) tuples encoded as dicts
    with keys: schema, handler_key.
    r  z*List available resources from MCP server 'r@  r  r  r  )r  handler_keyr  z(Read a resource by URI from MCP server 'r  stringzURI of the resource to read)r  r   )r  r  r  r  z(List available prompts from MCP server 'r  z&Get a prompt by name from MCP server 'zName of the prompt to retrievez(Optional arguments to pass to the promptT)r  r   r  additionalPropertiesr  r{  )r[  r  s    r+   _build_utility_schemasr"    sz    /{<LMMZKZZZ$"$   ,
	
 
	
 /{OLLX+XXX$$,+H   # "'	 	  +	
 	
& /{NKKX+XXX$"$   *
	
 
	
 /{LIIVVVV$ %-+K! !
 %-+U*,48	& &# # "(  ( (+	
 	
Q? ?rS   r  c                    | t                      S t          | t                    r| hS t          | t          t          t           f          rd | D             S t
                              d||            t                      S )z8Normalize include/exclude config to a set of tool names.Nc                 ,    h | ]}t          |          S rR   )r   r  s     r+   r\  z)_normalize_name_filter.<locals>.<setcomp>  s    ,,,dD		,,,rS   z>MCP config %s must be a string or list of strings; ignoring %r)r3  r  r   r   r!  r!   r[   )r   r  s     r+   _normalize_name_filterr%    sx    }uu% w%$s+,, -,,e,,,,
NNSUZ\abbb55LrS   rL  c                    | |S t          | t                    r| S t          | t                    r2|                                                                 }|dv rdS |dv rdS t
                              d| |           |S )z2Parse a bool-like config value with safe fallback.N>   1onyestrueT>   0noofffalseFzAMCP config expected a boolean-ish value, got %r; using default=%s)r  r  r   r   r   r!   r[   )r   rL  lowereds      r+   _parse_boolishr0    s    }% % ++--%%''00041115
NNVX]_fgggNrS   r  r  r  r  r  r  r  r  r  r  c                 x    t          |          }t          5  |t          | <   ddd           dS # 1 swxY w Y   dS )z:Remember the exact MCP server that registered *tool_name*.N)r  r  rF  )r   r-   safe_server_names      r+   _track_mcp_tool_serverr4  B  s    2;??	 = =,<y)= = = = = = = = = = = = = = = = = =s   /33c                 |    t           5  t                              | d           ddd           dS # 1 swxY w Y   dS )z5Forget MCP server provenance for a deregistered tool.N)r  rF  r  )r   s    r+   r`  r`  I  s    	 4 4""9d3334 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4s   155c                    |                     d          pi }t          |                     d          d          }t          |                     d          d          }d}t          |dd          }|t          |dd          }g }t          |           D ]}	|	d	         }
|
d
v r|st                              d| |
           -|
dv r|st                              d| |
           P|=t          |
         }t          ||d          t                              d| |
|           n@t          |
         }t          |j	        |          st                              d| |
|           |
                    |	           |S )z?Select utility schemas based on config and server capabilities.r  r  TrL  r  Nr-  r7  r  >   r  r  z;MCP server '%s': skipping utility '%s' (resources disabled)>   r  r  z9MCP server '%s': skipping utility '%s' (prompts disabled)zRMCP server '%s': skipping utility '%s' (server does not advertise '%s' capability)z9MCP server '%s': skipping utility '%s' (session lacks %s))r   r0  r   r"  r!   r"   _UTILITY_CAPABILITY_ATTRS_UTILITY_CAPABILITY_METHODSr|  r  r   )r-   r  r  tools_filterresources_enabledprompts_enabledadvertised_capsr8  selectedr  r  cap_attrrequired_methods                r+   _select_utility_schemasrA  O  s   ::g&&,"L&|'7'7'D'DdSSS$\%5%5i%@%@$OOOO O&"5t<<K!+~tDDH'44 $ $M*===FW=LLVXcepqqq8888LLTVacnooo &0=H$77?B    @ :+FO6>?;; O#	   OrS   c                     g } t                                           D ]j\  }}t          |d          r|                     |j                   0|j        D ]2}t          |j        |          }|                     |d                    3k| S )z6Return tool names for all currently connected servers.r(  r{  )	r  r   r|  r;  r(  r$  r  r{  r   )names_snamer  r  r  s        r+   _existing_tool_namesrE    s    E"..** ) )6344 	LL6777 	) 	)H(h??FLL((((	) LrS   c                    ddl m} g }d|  }|                    d          pi }t          |                    d          d|  d          t          |                    d          d|  d	          d
t          dt
          ffd}|j        D ]'} ||j                  s"t          	                    d| |j                   5t          | |j        |j        pd           t          | |          }	|	d         }
|                    |
          }|r9|                    d          s$t                              d| |j        |
|           |                    |
||	t#          | |j        |j                  t'          |           d|	d                    t)          |
|            |                    |
           )t,          t.          t0          t2          d}t'          |           }t5          | ||          D ]}|d         }	|d         } ||         | |j                  }|	d         }|                    |          }|r3|                    d          st                              d| ||           {|                    |||	||d|	d                    t)          ||            |                    |           |r|                    | |           |S )a  Register tools from an already-connected server into the registry.

    Handles include/exclude filtering and utility tools. Toolset resolution
    for ``mcp-{server}`` and raw server-name aliases is derived from the live
    registry, rather than mutating ``toolsets.TOOLSETS`` at runtime.

    Used by both initial discovery and dynamic refresh (list_changed).

    Returns:
        List of registered prefixed tool names.
    r   rX  zmcp-r  includezmcp_servers.z.tools.includeexcludez.tools.excluder   r   c                      r| v S r| vS dS )NTrR   )r   exclude_setinclude_sets    r+   _should_registerz0_register_server_tools.<locals>._should_register  s.     	,++ 	0K//trS   z8MCP server '%s': skipping tool '%s' (filtered by config)r   r{  us   MCP server '%s': tool '%s' (→ '%s') collides with built-in tool in toolset '%s' — skipping to preserve built-inFr   )r{  toolsetr  handlercheck_fnis_asyncr   r1  r  r  up   MCP server '%s': utility tool '%s' collides with built-in tool in toolset '%s' — skipping to preserve built-in)r]  rY  r   r%  r   r  r$  r{  r!   r"   r   r   r  get_toolset_for_toolr   r[   registerr  r  r  r4  r   r  r  r  r  rA  register_toolset_alias)r{  r  r  rY  registered_namestoolset_namer:  rL  r  r  tool_name_prefixedexisting_toolset_handler_factoriesrO  r  r  rN  	util_namerJ  rK  s                     @@r+   ra  ra    s~    ('''''"$ $==L ::g&&,"L()9)9))D)DFiUYFiFiFijjK()9)9))D)DFiUYFiFiFijjKC D        M 4 4.. 	LLSUY[c[hiii 	dHM83G3M2NNN$T844#F^ $889KLL 	$4$?$?$G$G 	NNIhm%79I  
 # &tX]F<OPP#D))}- 	 	
 	
 	
 	14888 23333
 742.	  d##H(vv>> + +xM*1$[1$8KLL6N	 $88CC 	$4$?$?$G$G 	NNIi!1  
  }- 	 	
 	
 	
 	y$///	**** <''l;;;rS   c           	      &  K   |                     dt                    }t          j        t	          | |          |           d{V }t
          5  t                              |            t          	                    | d           |t          | <   ddd           n# 1 swxY w Y   t          | ||          }t          |          |_        d|v rdnd}t                              d| |t!          |          d                    |                     |S )	zsConnect to a single MCP server, discover tools, and register them.

    Returns list of registered tool names.
    r  r  Nr  HTTPstdioz/MCP server '%s' (%s): registered %d tool(s): %sr  )r   r  r  r  r  r  r	  rD  r
  r  r  ra  r   r(  r!   rY   r   r   )r{  r  r  r  rT  transport_types         r+   _discover_and_register_serverr^    si     
 jj!24LMMO#f%%        F 
    ""4(((""4...                             
 .dFFCC$()9$:$:F!$VVGN
KK9nc"233		"##  
 s   A BB"Bc                 F   t           st                              d           g S t          |           } | st                              d           g S t          5  d |                                 D             t                                         D ]}t          	                    |d           |                                 D ]y\  }}t          |                    dd          d          r(t                              t          |                     Rt                              t          |                     z	 ddd           n# 1 swxY w Y   st!                      S t#                       dt$          d	t&          d
t(          t$                   fdfd}ddlm}m}  |            }|r |d           	 t1          |d           |r |d           n# |r |d           w w xY wt          5  d D             }t3          d |D                       }ddd           n# 1 swxY w Y   t5                    t5          |          z
  }	|s|	r;d| dt5          |           d}
|	r	|
d|	 dz  }
t                              |
           t!                      S )a[  Connect to explicit MCP servers and register their tools.

    Idempotent for already-connected server names. Servers with
    ``enabled: false`` are skipped without disconnecting existing sessions.

    Args:
        servers: Mapping of ``{server_name: server_config}``.

    Returns:
        List of all currently registered MCP tool names.
    z;MCP SDK not available -- skipping explicit MCP registrationz No explicit MCP servers providedc                 v    i | ]6\  }}|t           vt          |                    d d          d          3||7S r  Tr7  r  r0  r   r  s      r+   r  z(register_mcp_servers.<locals>.<dictcomp>:  sT     
 
 
1  ^AEE)T4J4JTX%Y%Y%Y  q   rS   Nsupports_parallel_tool_callsFr7  r{  r  r   c                 2   K   t          | |           d{V S )z@Connect to a single server and return its registered tool names.N)r^  )r{  r  s     r+   _discover_onez+register_mcp_servers.<locals>._discover_oneO  s(      24=========rS   c                    K   t                                                    } t          j        fd                                D             ddi d {V }t          | |          D ]\  }}t          |t                    r                    |i                               d          }t          |          }t          5  t                              |           |t          |<   d d d            n# 1 swxY w Y   t                              d||rd| dnd|           t          5  t                              |           t                              |d            d d d            n# 1 swxY w Y   d S )	Nc              3   6   K   | ]\  }} ||          V  d S r  rR   )r   r{  r  re  s      r+   r  z>register_mcp_servers.<locals>._discover_all.<locals>.<genexpr>W  s3      LL94mmD#&&LLLLLLrS   r  Tr   z*Failed to connect to MCP server '%s'%s: %sz
 (command=r
  r   )r   keysr  r  r   zipr  r2  r   rE  r  r	  rD  r
  r!   r[   r  )server_namesresultsr{  rO  r   rB  re  new_serverss         r+   _discover_allz+register_mcp_servers.<locals>._discover_allS  s$     K,,..//LLLL8I8I8K8KLLL
"
 
 
 
 
 
 
 
  g66 	; 	;LD&&-00 ;%//$3377	BB/77 ; ;&..t4443:*40; ; ; ; ; ; ; ; ; ; ; ; ; ; ; @/6>+++++B	     ; ;&..t444*..tT:::; ; ; ; ; ; ; ; ; ; ; ; ; ; ;	; 	;s$   %C55C9	<C9	-6E//E3	6E3	r   )ru  set_interruptx   r  Tc                 $    g | ]}|t           v |S rR   r  r   r  s     r+   r   z(register_mcp_servers.<locals>.<listcomp>~  s    ===1qH}}Q}}}rS   c              3   h   K   | ]-}t          t          t          |         d g                     V  .dS r(  Nr   r   r  rr  s     r+   r  z'register_mcp_servers.<locals>.<genexpr>  sO       
 
 %=rBBCC
 
 
 
 
 
rS   zMCP: registered  tool(s) from 
 server(s)r	   failed))rL   r!   r"   r  r  r   r	  r   r
  r  r0  r   rE  rB  r  rD  rE  ri  r   r   r   rz  ru  rn  r5  sumr   rY   )r  srv_namesrv_cfgrm  _is_interrupted_set_interrupt_was_interrupted	connectednew_tool_countfailedsummaryre  rl  s              @@r+   register_mcp_serversr  "  s     RSSS	,W55G 7888	 
 V V
 

 
 

 	!!+...# 	7 	7H"&&x6666!( 	V 	VHggkk*H%PPZ_``` V&**+Fx+P+PQQQQ&../J8/T/TUUUU		VV V V V V V V V V V V V V V V   &#%%% ># >D >T#Y > > > >; ; ; ; ; ;> cbbbbbbb&(( u!4444 	!N4     	!N4    	! 
 
 
=====	 
 

 
 
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 I.F  ]^]]3y>>]]] 	-,F,,,,GG!!!s1   C'EEEG   G0:&H,,H03H0c                     t           st                              d           g S t                      } | st                              d           g S t          5  d |                                 D             }ddd           n# 1 swxY w Y   t          |           }|s|S t          5  d |D             }t          d |D                       }ddd           n# 1 swxY w Y   t          |          t          |          z
  }|s|r;d| dt          |           d	}|r	|d
| dz  }t          	                    |           |S )a  Entry point: load config, connect to MCP servers, register tools.

    Called from ``model_tools`` after ``discover_builtin_tools()``. Safe to call even when
    the ``mcp`` package is not installed (returns empty list).

    Idempotent for already-connected servers. If some servers failed on a
    previous call, only the missing ones are retried.

    Returns:
        List of all registered MCP tool names.
    z4MCP SDK not available -- skipping MCP tool discoveryzNo MCP servers configuredc                 t    g | ]5\  }}|t           vt          |                    d d          d          3|6S ra  rb  )r   r{  r  s      r+   r   z&discover_mcp_tools.<locals>.<listcomp>  sR     
 
 
c8##swwy$7O7OY](^(^(^# ###rS   Nc                 $    g | ]}|t           v |S rR   rq  r   r{  s     r+   r   z&discover_mcp_tools.<locals>.<listcomp>  s"    !X!X!X4txGWGW$GWGWGWrS   c              3   h   K   | ]-}t          t          t          |         d g                     V  .dS rt  ru  r  s     r+   r  z%discover_mcp_tools.<locals>.<genexpr>  sO       
 
 (@"EEFF
 
 
 
 
 
rS   z  MCP: rv  rw  r	  rx  )
rL   r!   r"   r  r  r   r  ry  r   rY   )r  new_server_names
tool_namesconnected_server_namesr  failed_countr  s          r+   discover_mcp_toolsr    s     KLLL	  G 0111		 
 

 
$]]__
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 &g..J 	 
 
!X!X3C!X!X!X 
 
.
 
 
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 '((3/E+F+FFL  aNaa#>T:U:Uaaa 	32L2222GGs$   BB	B'&CC Cc                     |                      t                    sdS t          5  t                              |           }t          |o|t          v           cddd           S # 1 swxY w Y   dS )a  Check if an MCP tool belongs to a server that supports parallel tool calls.

    MCP tool names follow the pattern ``mcp__{server}__{tool}``, but that
    string shape is ambiguous when server names contain underscores. Use the
    exact server provenance captured at registration time rather than prefix
    matching, then check whether that server's config includes
    ``supports_parallel_tool_calls: true``.

    Returns False for non-MCP tools or tools from servers without the flag.
    FN)r   r  r  rF  r   r  rE  )r   r-   s     r+   is_mcp_tool_parallel_safer    s      455 u	 K K,00;;KIK3I$IJJK K K K K K K K K K K K K K K K K Ks   2A##A'*A'c                     g } t                      }|s| S t          5  t          t                    }t	          t
                    }t          t                    }ddd           n# 1 swxY w Y   |                                D ]c\  }}d|v r|                    dd          nd}t          |                    dd          d          }|                    |          }	|	r|	j
        x||t          |	d	          rt          |	j                  nt          |	j                  dd
dd}
|	j        rt          |	j        j                  |
d<   |                     |
           |s|                     ||dd
ddd           ||v r|                     ||dd
d
dd           ||v r%|                     ||dd
d
d||         d           G|                     ||dd
d
dd           e| S )a`  Return status of all configured MCP servers for banner display.

    Returns a list of dicts with keys: name, transport, tools, connected,
    disabled, and status. Includes connected servers, disabled servers,
    in-flight connection attempts, recorded failures, and servers that are
    configured but have not been started in this process yet.
    Nr  r  r  r\  r  Tr7  r(  Fr  )r{  r  r  r  disabledstatusr  r   r  
connectingr  )r{  r  r  r  r  r  r\   
configured)r  r  r   r  r3  r	  r
  r   r   r0  r  r|  r   r(  r$  r&  ro  r   )rO  r  active_serversr  connect_errorsr{  r  r  r  r  r  s              r+   get_mcp_statusr    s    F "##J 	 6 6h+,,
4556 6 6 6 6 6 6 6 6 6 6 6 6 6 6
  %%'' 7 7	c49SLLCGGK000g	 D!9!94HHH##D)) 3	fn0&?FvOg?h?h  AV:;;;nqrxr  oA  oA!!% E  C$()9)A$B$Bj!MM%     '	 MM&" $      ZMM&"!&      ^##MM&"!"'-      MM&"!&      Ms   =A%%A),A)c                     t           si S t                      } | si S d |                                 D             si S t                       i g fd}	 t	          |d           n2# t
          $ r%}t                              d|           Y d}~nd}~ww xY wt                       n# t                       w xY wS )u  Temporarily connect to configured MCP servers and list their tools.

    Designed for ``hermes tools`` interactive configuration — connects to each
    enabled server, grabs tool names and descriptions, then disconnects.
    Does NOT register tools in the Hermes registry.

    Returns:
        Dict mapping server name to list of (tool_name, description) tuples.
        Servers that fail to connect are omitted from the result.
    c                 d    i | ]-\  }}t          |                    d d          d          *||.S ra  )r0  r   r  s      r+   r  z*probe_mcp_server_tools.<locals>.<dictcomp>2  sO       A!%%	400$???	1  rS   c            	        K   t          
                                          } g }
                                D ]W\  }}|                    dt                    }|                    t          j        t          ||          |                     Xt          j	        |ddi d {V }t          | |          D ]\  }}t          |t                    rt                              d||           7                    |           g }|j        D ]1}t!          |dd          pd}	|                    |j        |	f           2||<   t          j	        d D             ddi d {V  d S )	Nr  r  r  Tz$Probe: failed to connect to '%s': %sr   r   c              3   >   K   | ]}|                                 V  d S r  rr  )r   ss     r+   r  z=probe_mcp_server_tools.<locals>._probe_all.<locals>.<genexpr>T  s*      33qajjll333333rS   )r   rh  r   r   r  r   r  r  r  r  ri  r  r    r!   r"   r$  r   r{  )rC  corosr{  r  ctoutcomesoutcomer  ru  descr  probed_serversrO  s             r+   
_probe_allz*probe_mcp_server_tools.<locals>._probe_all>  s     W\\^^$$  	S 	SID#*,DEEBLL)/$*D*DbQQQRRRR G$GGGGGGGG 11 		! 		!MD''9-- CT7SSS!!'***E^ - -q-44:afd^,,,, F4LL n33N333
"
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
rS   ro  r  zMCP probe failed: %sN)	rL   r  r   ri  r5  r    r!   r"   _stop_mcp_loop_if_idle)servers_configr  r*   r  r  rO  s      @@@r+   probe_mcp_server_toolsr     s%     	%''N 	 '--//  G  	%'F*,N
 
 
 
 
 
 
4!S11111 2 2 2+S111111112 	        Ms0   A- ,B. -
B7BB. BB. .B>c                  l    t           5  t          t                    cddd           S # 1 swxY w Y   dS )u  True if any MCP server has actually registered tools into the registry.

    Cheap — checks the global MCP-tool→server name map under ``_lock``, no
    registry walk.  Used by the per-turn refresh hook so a session with no MCP
    tools (the common case, and also a connected-but-zero-tool/prompt-only
    server) skips the ``get_tool_definitions`` rebuild entirely.  Checks
    registered TOOLS, not connected servers, so a server that registers no tools
    doesn't keep the hook firing every turn.
    N)r  r  rF  rR   rS   r+   has_registered_mcp_toolsr  j  sz     
 , ,*++, , , , , , , , , , , , , , , , , ,s   )--)enabled_overridedisabled_override
quiet_moder  c                   ddl m} ddlm} ||9||nt	          | dd          }||nt	          | dd          }|| _        || _        n"t	          | dd          }t	          | dd          }|j        }t           ||||          pg           }	d |	D             }
t          | |	|
          }t          5  t	          | d	d
          }t          |t                    r|nd
}||k     rt                      cddd           S d t	          | dd          pg D             }|
|k    r/t          ||          | _        t                      cddd           S |	| _        |
| _        t	          | dd          }t          |t                    r)|                                 |                    |           t          ||          | _        |
|z
  cddd           S # 1 swxY w Y   dS )u  Re-derive an already-built agent's tool snapshot from the live registry.

    The agent snapshots ``agent.tools`` once at build time and never re-reads
    the registry (see ``run_agent`` / ``agent_init``).  When MCP servers connect
    *after* that snapshot — a slow HTTP/OAuth server that misses the bounded
    startup wait, or a ``/reload-mcp`` — their tools are invisible until the
    snapshot is rebuilt.  This is the single shared rebuild used by every such
    caller (the TUI ``reload.mcp`` RPC, the gateway reload, the late-binding
    refresh thread, and the per-turn between-turns refresh) so they can't drift
    apart again.

    The rebuild respects the agent's own ``enabled_toolsets`` /
    ``disabled_toolsets`` (the same filtering it was built with) and diffs by
    tool **name** (not count — a count compare misses an equal-size add/remove
    swap).

    Crucially it is **additive-preserving**: ``get_tool_definitions`` returns
    only the registry-derived tools, but ``agent_init`` appends two further
    families directly onto ``agent.tools`` *after* that — external
    memory-provider tools (mem0/honcho/…) and context-engine tools
    (``lcm_*``).  A naive ``agent.tools = get_tool_definitions(...)`` would
    silently DELETE those.  So after rebuilding the registry set we re-run the
    same post-build injectors ``agent_init`` used, reconstructing the full
    surface.  The new ``(tools, valid_tool_names)`` pair is published together
    under ``_agent_tools_lock`` so a concurrent reader never sees a
    cross-attribute half-swap.

    Returns the set of newly-added tool names (empty when nothing changed), so
    callers can decide whether to notify the user / re-emit session info.  The
    caller owns the prompt-cache contract: this helper does NOT check turn state,
    because each caller has a different policy (``/reload-mcp`` rebuilds after
    explicit user consent; the late-binding and between-turns paths only rebuild
    at a turn boundary, before that turn's ``tools=`` prefix is assembled).
    r   )get_tool_definitionsrX  Nenabled_toolsetsdisabled_toolsets)r  r  r  c                 *    h | ]}|d          d         S r  r{  rR   r  s     r+   r\  z*refresh_agent_mcp_tools.<locals>.<setcomp>  s!    9991:v&999rS   _tool_snapshot_generationr  c                 *    h | ]}|d          d         S r  rR   r  s     r+   r\  z*refresh_agent_mcp_tools.<locals>.<setcomp>  s1     
 
 
 jM&!
 
 
rS   r  _context_engine_tool_names)model_toolsr  r]  rY  r   r  r  _generationr   _reinject_post_build_tools_agent_tools_lockr  rf  r3  rJ  r  r  valid_tool_namesrz  r   )agentr  r  r  r  rY  r  r  snapshot_generationnew_defs	new_namesstaged_engine_namespublished_gen_rawpublished_genr)  engine_namess                   r+   refresh_agent_mcp_toolsr  x  s   R 100000'''''' #'8'D&6&B""PUWikoHpHp(9(E$$7SXZmosKtKt!("*%!3T::5"5t<< #. $&!	
 	
 	
 	
  H :9999I 5UHiPP
 
 # #
 $E+FKK-78I3-O-OW))UW..55# # # # # # # #
 
eWd339r
 
 
  /2-AT.U.UE+55%# # # # # # # #& !*u&BDIIlC(( 	5    3444*-m=P*Q*Q'7"7# # # # # # # # # # # # # # # # # #s    4>G?AGA6GGG
tools_listname_setc                 j   dt           dt          ffd}	 t          | dd          }|rt          |dd          nd}t          |          rQddlm} d	v s |t          | d
d                    r- |            D ]"}t          |t                     r ||           #n,# t          $ r t          	                    dd           Y nw xY wt                      }	 t          | d
d          }	|	du pd|	v }
t          | dd          }|rt          |dd          nd}|
rjt          |          r[ |            D ]P}t          |t                     s|                    dd          } ||          r|r|                    |           Qn,# t          $ r t          	                    dd           Y nw xY w|S )u  Append memory-provider and context-engine tools onto staged locals.

    Mirrors the post-``get_tool_definitions`` injection in ``agent_init`` so a
    snapshot rebuild reconstructs the FULL tool surface, not just the
    registry-derived subset. Operates ONLY on the caller's staged ``tools_list``
    / ``name_set`` (never the live agent attributes) so the rebuild stays atomic.
    Idempotent (skips names already present) and fail-soft.

    Returns the set of context-engine routing names actually appended by THIS
    rebuild — matching ``agent_init``'s dedup behavior (a name already provided
    by a registry/plugin tool is NOT claimed for context-engine routing). The
    caller publishes this into ``agent._context_engine_tool_names`` atomically
    with the snapshot.
    r  r   c                     |                      dd          }|r|v rdS                     d| d                               |           dS )Nr{  r   Fr  r  T)r   r   rB  )r  r{  r  r  s     r+   _addz(_reinject_post_build_tools.<locals>._add  s`    zz&"%% 	tx''5:6BBCCCTtrS   _memory_managerNget_all_tool_schemasr   )memory_provider_tools_enabledmemoryr  z)Memory-provider tool re-injection skippedTr  context_enginecontext_compressorget_tool_schemasr{  r   z(Context-engine tool re-injection skipped)r   r  r   r~  agent.memory_managerr  r  r    r!   r"   r3  r   rB  )r  r  r  r  memory_managerget_mem_schemasr  r  r  r  context_engine_allowed
compressorget_schemasr{  s    ``           r+   r  r    sY   T d       Q (94@@Sak'.2H$OOOgkO$$ 	%JJJJJJ8##'D'DWUTfhlEmEm'n'n#-o// % %F!&$// %V Q Q Q@4PPPPPQ  #uuP%!3T::!(D!O4D4OU$8$??
GQ[gj*<dCCCW[! 		2h{&;&; 		2%+-- 2 2!&$// zz&"-- 4<< 2D 2'++D111 P P P?$OOOOOP s%   BB   &C	C	B+F &F0/F0c                  0   t           5  t          t                                                    ddd           n# 1 swxY w Y   st	                       dS fd} t           5  t
          }ddd           n# 1 swxY w Y   ||                                rnddlm}  | |             |t          d          }|J	 |
                    d           n2# t          $ r%}t                              d	|           Y d}~nd}~ww xY wt	                       dS )
a  Close all MCP server connections and stop the background loop.

    Each server Task is signalled to exit its ``async with`` block so that
    the anyio cancel-scope cleanup happens in the same Task that opened it.
    All servers are shut down in parallel via ``asyncio.gather``.
    Nc                  X  K   t          j        d D             ddi d {V } t          |           D ];\  }}t          |t                    r!t
                              d|j        |           <t          5  t          
                                 d d d            d S # 1 swxY w Y   d S )Nc              3   >   K   | ]}|                                 V  d S r  r  )r   r  s     r+   r  z:shutdown_mcp_servers.<locals>._shutdown.<locals>.<genexpr>D  s,      ??Ffoo??????rS   r  Tz!Error closing MCP server '%s': %s)r  r  ri  r  r    r!   r"   r{  r  r  rz  )rk  r  rO  servers_snapshots      r+   	_shutdownz'shutdown_mcp_servers.<locals>._shutdownB  s     ??.>???
"
 
 
 
 
 
 
 
 ""2G<< 	 	NFF&),, 7f    	 	NN	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   8BB#&B#r   rv  z MCP shutdown: failed to schedulerx  r/  r  zError during MCP shutdown: %s)r  r   r  values_stop_mcp_loopr  r  r{  rw  r!   rO  r2  r"   )r  r  rw  r  r*   r  s        @r+   shutdown_mcp_serversr  3  s    
 3 3 1 1223 3 3 3 3 3 3 3 3 3 3 3 3 3 3       
                DOO-->>>>>>))IKK:
 
 

 Cb))))  C C C<cBBBBBBBBC s9   '<A A %A99A= A=?C 
D D  Dinclude_activec                   	
 ddl }t          5  i }t          D ]}d||<   t                                           | r@|                    t          t                               t                                           d |D             

D ]}t                              |d           	 ddd           n# 1 swxY w Y   |sdS 	 t          j
                    	n# t          t          f$ r d	Y nw xY wdt          dt          dt          ddf	
fd	}|                                D ]3\  }} |||j        |           t"                              d
||           4t'          j        d           t+          |d|j                  }ddlm} |                                D ]:\  }} ||          s ||||           t"                              d||           ;dS )u  Best-effort graceful shutdown of stdio MCP subprocesses to reap orphans.

    Orphans are PIDs that survived their session context exit (SDK teardown
    did not terminate the process — common on Linux when stdio children escape
    the parent cgroup on cancellation). By default only entries in
    ``_orphan_stdio_pids`` are reaped so concurrent cron jobs and live user
    sessions are not disrupted.

    Sends SIGTERM, waits 2 seconds, then escalates to SIGKILL for any
    survivors, avoiding shared-resource collisions when multiple hermes
    processes run on the same host (each has its own ``_stdio_pids`` dict).

    On POSIX, signals are sent via ``os.killpg`` to the spawn-time pgid when
    one is tracked, so reparented grandchildren in the same process group
    (e.g. ``claude mcp serve`` spawned by a stdio MCP wrapper that exited
    first) are reaped alongside the direct child.  Falls back to ``os.kill``
    on Windows and when no pgid is recorded.

    With ``include_active=True`` also kills every PID in ``_stdio_pids`` —
    used only at final shutdown, after the MCP event loop has stopped and no
    sessions can still be in flight.
    r   Norphanc                 <    i | ]}|t           v |t           |         S rR   )r  )r   r  s     r+   r  z/_kill_orphaned_mcp_children.<locals>.<dictcomp>  s*     _ _ _C3R^K^K^l3&7K^K^K^rS   r  sigr-   r   c                                         |           }t          t          dd          }|x|v#|k    rt                              d||           nQ	  |||           dS # t
          t          t          f$ r(}t                              d||||           Y d}~nd}~ww xY w	 t          j	        | |           dS # t
          t          t          f$ r Y dS w xY w)z=SIGTERM/SIGKILL via pgroup on POSIX, fall back to pid signal.r  Nu   MCP server '%s' pgid %d matches gateway pgid; skipping killpg to avoid self-kill and using per-pid kill — any grandchildren in this group may not be reapedzHkillpg(%d, %d) failed for MCP server '%s': %s; falling back to kill(pid))
r   r   r#   r!   r[   r  r  r  r"   kill)r  r  r-   r  r  r*   _my_pgidpgidss         r+   _send_signalz1_kill_orphaned_mcp_children.<locals>._send_signal  s-   yy~~Xt,, 2#(8(8 D  	   	F4%%%F*OWE    LLbc;       	GC"OW= 	 	 	DD	s*   A% %B$<BB$(B? ?CCz,Sent SIGTERM to orphaned MCP process %d (%s)r  SIGKILLr  z6Force-killed MCP process %d (%s) after SIGTERM timeout)signalr  r  rz  r   r   r  r  r  r#   getpgrpr  r  rf  r   r   SIGTERMr!   r"   rw  rT  r   r  r  r[   )r  _signalrU  opidr  r  r-   _sigkillr  r  r  s            @@r+   _kill_orphaned_mcp_childrenr  a  s   . 	 ( (!& 	" 	"D!DJJ  """ 	 KK[))*** !` _4 _ _ _ 	( 	(CS$''''	(( ( ( ( ( ( ( ( ( ( ( ( ( ( (   :<<G$   !# !C !c !d ! ! ! ! ! ! !H !JJLL W W[S'/;777CS+VVVV 	JqMMM w	7?;;H +***** JJLL 
 
[{3 	S(K000D	
 	
 	
 	
	
 
s$   BB44B8;B8C C.-C.c                  "    t          d          S )a  Stop the MCP loop only when no registered server still owns it.

    Probe paths create temporary MCPServerTask instances that are not placed in
    ``_servers``.  They should clean up an otherwise-idle loop, but must not
    tear down the process-global loop when live agent tools are registered on
    it.  Otherwise a dashboard/CLI probe can make later MCP tool calls fail
    with ``MCP event loop is not running``.
    Tonly_if_idle)r  rR   rS   r+   r  r    s     t,,,,rS   r  r  c                    t           5  | r6t          st          r(t                              d           	 ddd           dS t
          }t          }dadaddd           n# 1 swxY w Y   |h|                    |j                   ||	                    d           	 |
                                 n# t          $ r Y nw xY wt          d           dS )z3Stop the background event loop and join its thread.zKLeaving MCP event loop running; active servers are registered or connectingNFrb   r  T)r  )r  r  r	  r!   r"   r  rG  r  rV  r   r}  r    r  )r  r  threads      r+   r  r    sN    
   	X 	); 	LLfggg        	               !!$),,,KKK"""	JJLLLL 	 	 	D	
 	$488884s)   ,AAA#&A#B4 4
C C)rj  r   r   r   )r]  )T)F)r  r  r  concurrent.futuresr  rM   r  rh  rH  r#   r0  r   r%   rf  rw  typingr   r   r   r   r   r   r	   urllib.parser
   	getLoggerr   r!   r  r   __annotations__r2  r   r,   r   r4   rL   r  r  rR  r  r  r:   r  r5   r6   mcp.client.stdior7   mcp.client.streamable_httpr8   r   r9   r  	mcp.typesr"   mcp.client.sser;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   r  rT   rX   r  ri  rj  rk  ERRORrK  r0  r  r  r  r  ru  rt  	frozensetr   r   compile
IGNORECASEr   r  r   r   r   r   r2  r   r   r   r    r   Ir   r   r   r!  r   r   r   rQ   r   ConnectionErrorr  r  r'  rE  rf  rP  rR  r  r  r  r  r3  r	  r
  r  r  rG  r  r  r  r  r  r  r&  r  r:  r<  rA  rD  rE  rF  r  AbstractEventLooprG  rg  r  r  r  r  r  rT  r  ra  ri  rs  r5  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r[  r  r"  r%  r0  r9  r8  r4  r`  rA  rE  ra  r^  r  r  r  r  r  r  r  r  r   r  r  r  r  r  rR   rS   r+   <module>r     s)  P P Pd              				 				  



                  7 7 7 7 7 7 7 7 7 7 7 7 7 7 ! ! ! ! ! !		8	$	$  $ ( %) HSM ( ( (%y~''  "S  "  "  "  "F# $    &     !&  ' >K88888888------N$DDDDDD" $ $ $#$EEEEEE   k5555555 k k kijjjjjkZ------- Z Z Z
XYYYYYZN	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 # N N NLMMMMMNT????????!% T T TRSSSSST	`	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 #' ` ` `^_____` K K K
LLIJJJJJK     "@!?!A!A  `8 `
LL^___      #B"A"C"C 
 ]Ll]]	 	         "         #,) - - - # # B !bj		 M  " 2:.// 
s 
s 
 
 
 
"htn     .7# 7# 7 7 7 7	'- 	'C 	' 	' 	' 	' 'GGGGGGG ' ' ' &'M d    P RZ<bdCC?ARZ&--57RZDbdKKRZ "$''&(RZ3RT::!#RZ:BDAA RZ0"$77%'RZ2BD99 RZ&--!RZ924@@!#' 0s s  QUVYQZ    *t      ,*C ,*d ,*uS$Y7G ,* ,* ,* ,*h;# ;# ; ; ; ;)!S )! )! )! )!b           /   1# 1C 1C 1 1 1 1hFc F4 F F F FR93} 93 93 93 93 93@ *-a    l9 l9 l9 l9 l9 l9 l9 l9ft # #    4Z. Z. Z. Z. Z. Z. Z. Z.BI) I) I) I) I) I) I) I)`$ &($sM!
" ' ' '"suu CH $ $ $)+ S#X + + +& (* d38n ) ) ).0 4U
+ 0 0 0  $ 
BC 
BD 
B 
B 
B 
B5S 5T 5 5 5 5c d    <  5   'u ' ' ' 'T $    &xx	x 	x x x x~# %    E= ET E E E E4PP	P 	P P P Pl "cee  # # # *, S#X + + + 26	8G-. 5 5 5*.Xi&' . . . 		 !T#s(^       #%% C     "d38n ! ! !c    @3 c3h    s  s        F, , ,      >A Au A A A AH#      2DdO S$Y    6$$sDy/ $ $ $ $V T m    (lC lC lu l l l l^7c 7 7 7 7 7t9S 9 9 9 9 9x<C <u < < < <~D# DU D D D DN    It I I I I IX;s ;s ; ; ; ;$  N N N N N N NS t    &E ET
 E E E EP	# 	c 	c#h 	 	 	 	 #      " '$"	  $ " 	  =c = = = = = =4s 4t 4 4 4 46 6m 6T 6VZ[_V` 6 6 6 6r
d3i 
 
 
 
k km kT kdSVi k k k k\c 4 DI    >h"$sDy/ h"d3i h" h" h" h"V.DI . . . .bK K K K K K$MT
 M M M M`?S$u+%5 6 ? ? ? ?N #IN$$ ,$ , , , ," w# w# w#
 w# 	w# w# w# w#t>$ ># ># > > > >B+ + +\i
 i
 i
 i
 i
 i
 i
X	- 	- 	- 	- 	- ,1   D T      s   #G 4B= <G =CG CG C G CG CG "C) (G )DG DG 
D G D0-G /D00G 4E	 G 	E&#G %E&&G *
E5 4G 5FG FG F% $G %G?G GG G#"G#K KK