
    `gj҉                       d Z ddlm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mZ ddlmZ ddlmZ ddlmZmZmZ  ej(                  d      Zd	Z	 dd
lmZ dZddZd ZddZd dZddZddZddZ 	 	 	 	 	 	 	 	 d!dZ!d"dZ"d#dZ#dZ$dZ%e G d d             Z& G d d      Z'd$d%dZ(d&d'dZ)y# e$ r dZY `w xY w)(uA  
Hermes MCP Server — expose messaging conversations as MCP tools.

Starts a stdio MCP server that lets any MCP client (Claude Code, Cursor, Codex,
etc.) list conversations, read message history, send messages, poll for live
events, and manage approval requests across all connected platforms.

Matches OpenClaw's 9-tool MCP channel bridge surface:
  conversations_list, conversation_get, messages_read, attachments_fetch,
  events_poll, events_wait, messages_send, permissions_list_open,
  permissions_respond

Plus: channels_list (Hermes-specific extra)

Usage:
    hermes mcp serve
    hermes mcp serve --verbose

MCP client config (e.g. claude_desktop_config.json):
    {
        "mcpServers": {
            "hermes": {
                "command": "hermes",
                "args": ["mcp", "serve"]
            }
        }
    }
    )annotationsN)	dataclassfielddatetime)Path)DictListOptionalzhermes.mcp_serveF)FastMCPTc                     	 ddl m}   |        dz  S # t        $ rD t        t        j
                  j                  dt        j                         dz              dz  cY S w xY w)z0Return the sessions directory using HERMES_HOME.r   get_hermes_homesessionsHERMES_HOME.hermes)hermes_constantsr   ImportErrorr   osenvirongethomer   s    </root/.hermes/venv/lib/python3.12/site-packages/mcp_serve.py_get_sessions_dirr   ?   sT    Y4 :-- YBJJNN=$))+	2IJKjXXYs    A
AAc                 v    	 ddl m}   |        S # t        $ r }t        j	                  d|       Y d}~yd}~ww xY w)z9Get a SessionDB instance for reading message transcripts.r   )	SessionDBzSessionDB unavailable: %sN)hermes_stater   	Exceptionloggerdebug)r   es     r   _get_session_dbr"   H   s4    *{ 0!4s    	838c                 2    t               } | r| S t               S )a  Load the gateway session routing index.

    Returns a dict of session_key -> entry_dict with platform routing info.

    state.db is the primary source (#9006): gateway sessions persist their
    routing metadata (session_key, chat/thread ids, display_name, origin) on
    the durable session row, so a single database read replaces the old
    dual-file sessions.json dependency.  Falls back to sessions.json for
    pre-migration databases where no gateway rows carry a session_key yet.
    )_load_sessions_index_from_db_load_sessions_index_from_json)entriess    r   _load_sessions_indexr'   R   s     +,G)++    c                t   i }| j                  d      }|r(	 t        j                  |      }t        |t              r|}|sT| j                  dd      | j                  d      | j                  d      | j                  d      | j                  d      d}dd	}t        | j                  d
      xs d      }t        | j                  d      xs d      }t        | j                  dd            | j                  dd      | j                  dd      | j                  d      xs |j                  dd      | j                  d      xs |j                  d      xs d| || j                  d             || j                  d      xs | j                  d            ||||z   dS # t
        t        f$ r Y xw xY w)zHConvert a state.db gateway session row to the sessions.json entry shape.origin_jsonsource chat_id	chat_type	thread_iduser_id)platformr-   r.   r/   r0   c                    	 | r,t        j                  t        |             j                         S dS # t        t
        t        f$ r Y yw xY w)Nr,   )r   fromtimestampfloat	isoformat	TypeError
ValueErrorOSError)tss    r   _isoz!_row_to_index_entry.<locals>._isox   sE    	DF8))%)4>>@NBN:w/ 		s   -2 2 A	A	input_tokensr   output_tokensidsession_keydisplay_name	chat_name
started_atlast_active)
session_idr>   r1   r.   r?   origin
created_at
updated_atr;   r<   total_tokensreturnstr)	r   jsonloads
isinstancedictr6   r7   intrJ   )rowrD   r*   parsedr:   r;   r<   s          r   _row_to_index_entryrR   c   s   F''-(K	ZZ,F&$'  "-wwy)--wwy)
 sww~.3!4L05A6M#''$+,ww}b1GGHb)WW[)HVZZR-H/P6::k3JPb377<01377=1JSWW\5JK$&$}4 ) :& 		s   'F$ $F76F7c                 &   t               } | i S 	 t        | dd      }t        |      si 	 | j                          S  |d      }i }|D ]$  }|j                  d      }|st        |      ||<   & |	 | j                          S # t        $ r Y S w xY w# t        $ r Y S w xY w# t        $ rB}t        j                  d|       i cY d}~	 | j                          S # t        $ r Y S w xY wd}~ww xY w# 	 | j                          w # t        $ r Y w w xY wxY w)z;Build the routing index from state.db gateway session rows.Nlist_gateway_sessionsT)active_onlyr>   z1Failed to load gateway sessions from state.db: %s)	r"   getattrcallablecloser   r   rR   r   r    )dblisterrowsr&   rP   keyr!   s          r   r$   r$      s   		B	z	4d;	HHJ $' 	4C''-(C.s3GCL		4
 
	HHJ 		y 		  H!L		HHJ 			HHJ 		s   B  B5B  1B	BB	BB 	C+)C& C+C. C	C#"C#&C++C. .D0D D	D
DDDc                    t               dz  } | j                         si S 	 t        | dd      5 }t        j                  |      }ddd       t        t              r?|j                         D ci c]#  \  }}t        |      j                  d      r!||% c}}S i S # 1 sw Y   ZxY wc c}}w # t        $ r"}t        j                  d|       i cY d}~S d}~ww xY w)zLegacy fallback: load the gateway sessions.json index directly.

    Used only for pre-migration databases whose gateway rows don't carry a
    session_key yet.  This avoids importing the full SessionStore which
    needs GatewayConfig.
    zsessions.jsonrutf-8encodingN_z Failed to load sessions.json: %s)r   existsopenrK   loadrM   rN   itemsrJ   
startswithr   r   r    )sessions_filefdatakvr!   s         r   r%   r%      s     &'/9M!	-w7 	 199Q<D	  dD!%)ZZ\PTQQ9J9J39OAqDPP		  	  Q 7;	sL   B0 B+B0 0"B*B*B0 B0 B'#B0 0	C9CCCc                    	 ddl m}   |        dz  }|j                         si S 	 t        |dd      5 }t        j                  |      cd	d	d	       S # t        $ rD t        t        j
                  j                  dt        j                         dz              dz  }Y w xY w# 1 sw Y   y	xY w# t        $ r"}t        j                  d
|       i cY d	}~S d	}~ww xY w)z8Load the cached channel directory for available targets.r   r   zchannel_directory.jsonr   r   r^   r_   r`   Nz)Failed to load channel_directory.json: %s)r   r   r   r   r   r   r   r   rc   rd   rK   re   r   r   r    )r   directory_fileri   r!   s       r   _load_channel_directoryro      s    %4(*-EE   "	.#8 	 A99Q<	  	   %JJNN=$))+	*AB
$%%	  	  @!D	sL   A B. B"	B. A
BB"B+'B. +B. .	C7CCCc               t    	 t        |       }t        |t	        ||            S # t        t        f$ r |}Y )w xY w)zCoerce value to int with fallback and clamping.

    Used at MCP tool boundaries to handle invalid types from external clients.
    Returns default if value cannot be converted to int.
    )rO   r6   r7   maxmin)valuedefaultminimummaximumcoerceds        r   _coerce_intrx      sA    e* wGW-.. z" s   # 77c                   | j                  dd      }t        |t              rT|D cg c]8  }t        |t              r&|j                  d      dk(  r|j                  dd      : }}dj	                  |      S |rt        |      S dS c c}w )zAExtract text content from a message, handling multi-part content.contentr,   typetext
)r   rM   listrN   joinrJ   )msgrz   p
text_partss       r   _extract_message_contentr      s    ggi$G'4 '.
"#!T"quuV}'> EE&"

 
 yy$$"3w<**
s   =Bc                   g }| j                  dd      }t        |t              r|D ]  }t        |t              s|j                  dd      }|dk(  r[t        |j                  d      t              r"|j                  di       j                  dd      nd}|sq|j	                  d|d       |dk(  rJ|j                  d|j                  di       j                  dd            }|s|j	                  d|d       |d	vs|j	                  ||d
        t        |       }|rPt        j                  d      }|j                  |      D ]'  }|j                  d      }	|j	                  d|	d       ) |S )zExtract non-text attachments from a message.

    Finds: multi-part image/file content blocks, MEDIA: tags in text,
    image URLs, and file references.
    rz   r,   r{   	image_urlurlimage)r{   r   r+   >   r|   )r{   rj   zMEDIA:\s*(\S+)   media)r{   path)
r   rM   r~   rN   appendr   recompilefinditergroup)
r   attachmentsrz   partptyper   r|   media_patternmatchr   s
             r   _extract_attachmentsr      sh    Kggi$G '4  	BDdD)HHVR(E#BLTXXVaMbdhBidhh{B/33E2>oq&&'DE'!hhudhhx&<&@&@&KL&&'DEi'""E4#@A	B" $C(D

#45"++D1 	@E;;q>D>?	@ r(   i  g?c                  P    e Zd ZU dZded<   ded<   dZded<    ee      Zd	ed
<   y)
QueueEventz)An event in the bridge's in-memory queue.rO   cursorrJ   r{   r,   r>   )default_factoryrN   rj   N)	__name__
__module____qualname____doc____annotations__r>   r   rN   rj    r(   r   r   r   $  s(    3K
IKt,D$,r(   r   c                      e Zd ZdZd Zd Zd Z	 	 	 d	 	 	 	 	 	 	 ddZ	 	 	 d	 	 	 	 	 	 	 ddZddZ	dd	Z
dd
Zd Zd Zy)EventBridgea  Background poller that watches SessionDB for new messages and
    maintains an in-memory event queue with waiter support.

    This is the Hermes equivalent of OpenClaw's WebSocket gateway bridge.
    Instead of WebSocket events, we poll the SQLite database for changes.
    c                    g | _         d| _        t        j                         | _        t        j
                         | _        d| _        d | _        i | _	        i | _
        d| _        i | _        y )Nr   F        )_queue_cursor	threadingLock_lockEvent
_new_event_running_thread_last_poll_timestamps_pending_approvals_state_db_mtime_cached_sessions_indexselfs    r   __init__zEventBridge.__init__5  sZ    (*^^%
#//+3779"35&),.#r(   c                    | j                   ryd| _         t        j                  | j                  d      | _        | j                  j                          t        j                  d       y)z$Start the background polling thread.NT)targetdaemonzEventBridge started)r   r   Thread
_poll_loopr   startr   r    r   s    r   r   zEventBridge.startC  sH    == ''ttL*+r(   c                    d| _         | j                  j                          | j                  r| j                  j	                  d       t
        j                  d       y)z#Stop the background polling thread.F   timeoutzEventBridge stoppedN)r   r   setr   r   r   r    r   s    r   stopzEventBridge.stopL  sB    <<LLa(*+r(   Nc                z   | j                   5  | j                  D cg c]$  }|j                  |kD  r|r|j                  |k(  r|& c}d| }ddd       r|d   j                  n|}|D cg c]2  }|j                  |j                  |j                  d|j
                  4 c}|dS c c}w # 1 sw Y   bxY wc c}w )zEReturn events since after_cursor, optionally filtered by session_key.Nr   r{   r>   )eventsnext_cursor)r   r   r   r>   r{   rj   )r   after_cursorr>   limitr!   r   r   s          r   poll_eventszEventBridge.poll_eventsT  s     ZZ 	;;88l*$(D  u	F	 ,2fRj''|
    88QVV !9129
 '
 	
	 	s"   B,)B'B,*7B8'B,,B5c                x   t        j                         |dz  z   }t        j                         |k  r| j                  5  | j                  D ]^  }|j                  |kD  s|r|j
                  |k(  s%|j                  |j                  |j
                  d|j                  c cddd       S  	 ddd       |t        j                         z
  }|dk  r	 y| j                  j                          | j                  j                  t        |t                     t        j                         |k  ry# 1 sw Y   xY w)z8Block until a matching event arrives or timeout expires.g     @@r   Nr   r   )time	monotonicr   r   r   r>   r{   rj   r   clearwaitrr   POLL_INTERVAL)r   r   r>   
timeout_msdeadliner!   	remainings          r   wait_for_eventzEventBridge.wait_for_eventl  s    >>#zF':;nn)  Axx,.'1==K+G '(hh+,== <=FF    !4>>#33IA~  OO!!#OO  Y)F G nn)" ! s   D0D001D0+D00D9c                    | j                   5  t        | j                  j                         d       cddd       S # 1 sw Y   yxY w)z;List approval requests observed during this bridge session.c                &    | j                  dd      S )NrE   r,   r   )as    r   <lambda>z4EventBridge.list_pending_approvals.<locals>.<lambda>  s    aeeL"5 r(   )r\   N)r   sortedr   valuesr   s    r   list_pending_approvalsz"EventBridge.list_pending_approvals  s;    ZZ 	''..05	 	 	s	   &=Ac           
         | j                   5  | j                  j                  |d      }ddd       sdd| iS | j                  t	        dd|j                  dd      ||d	             d
||dS # 1 sw Y   IxY w)z=Resolve a pending approval (best-effort without gateway IPC).NerrorzApproval not found: r   approval_resolvedr>   r,   )approval_iddecisionr   r{   r>   rj   T)resolvedr   r   )r   r   pop_enqueuer   r   )r   r   r   approvals       r   respond_to_approvalzEventBridge.respond_to_approval  s    ZZ 	F..22;EH	F 3K=ABBj$ ]B7!,(C	
 	 !(SS	F 	Fs   A22A;c                   | j                   5  | xj                  dz  c_        | j                  |_        | j                  j	                  |       t        | j                        t        kD  r8| j                  j                  d       t        | j                        t        kD  r8ddd       | j                  j                          y# 1 sw Y   $xY w)z/Add an event to the queue and wake any waiters.r   r   N)
r   r   r   r   r   lenQUEUE_LIMITr   r   r   )r   events     r   r   zEventBridge._enqueue  s    ZZ 	#LLAL<<ELKKu%dkk"[0" dkk"[0	# 		# 	#s   BCCc                *   t               }|st        j                  d       y| j                  r9	 | j	                  |       t        j                  t               | j                  r8yy# t
        $ r }t        j                  d|       Y d}~Ld}~ww xY w)z1Background loop: poll SessionDB for new messages.z:EventBridge: SessionDB unavailable, event polling disabledNzEventBridge poll error: %s)
r"   r   warningr   
_poll_oncer   r    r   sleepr   )r   rY   r!   s      r   r   zEventBridge._poll_loop  sp    NNWXmm># JJ}% mm  >91==>s   A) )	B2BBc                   	 ddl m}  |       dz  }	 |j                         r|j                         j                  nd}|| j                  k(  ry|| _        t               | _        | j                  }|j                         D ]f  \  }}|j                  dd	      }|s| j                   j                  |d      }		 |j#                  |      }
|
sMdd
}g }|
D ]H  } ||j                  dd            }|j                  dd	      }|dvr2||	kD  s8|j'                  |       J |D ]x  }t)        |      }|s| j+                  t-        dd||j                  dd	      |dd t/        |j                  dd	            t/        |j                  dd	            d             z |
D cg c]  } ||j                  dd             }}|sFt1        |      }||	kD  sX|| j                   |<   i y# t        $ rE t        t        j
                  j                  dt        j                         dz              dz  }Y 'w xY w# t        $ r d}Y w xY w# t$        $ r Y w xY wc c}w )u"  Check for new messages across all sessions.

        Uses a single mtime check on state.db to skip work when nothing
        has changed — makes 200ms polling essentially free.  Since #9006
        the routing index itself lives in state.db (session rows carry
        session_key/origin metadata), so a new conversation and its first
        message land in the SAME file and one mtime check covers both —
        eliminating the old dual-file (sessions.json + state.db) race that
        could drop brand-new conversations (#8925).
        r   r   zstate.dbr   r   r   NrC   r,   c                   t        | t        t        f      rt        |       S t        | t              r| r	 t        |       S y# t        $ r: 	 ddlm}  |j                  |       j                         cY S # t        $ r Y Y yw xY ww xY w)Nr   r   r   )	rM   rO   r4   rJ   r7   r   fromisoformat	timestampr   )r9   r   s     r   	_ts_floatz)EventBridge._poll_once.<locals>._ts_float  s    b3,/ 9$b#&2'$Ry(  & ''9#98#9#9"#=#G#G#II( '#&''s/   
A 	B%A30B3	B <B?B  Br   role>   user	assistantmessagei  r=   )r   rz   r   
message_idr   )rI   r4   )r   r   r   r   r   r   r   r   rc   statst_mtimer8   r   r'   r   rf   r   get_messagesr   r   r   r   r   rJ   rq   )r   rY   r   db_filedb_mtimer&   r>   entryrC   	last_seenmessagesr   new_messagesr   r9   r   rz   mall_tslatests                       r   r   zEventBridge._poll_once  sh   	`8%'*4G	29..2Bw||~..H t+++' ';&<#--")--/ >	EK<4J2266{CHI??:6   L -sww{A67wwvr*44	> '',- $ 237j" + # 3#*4C=%(b)A%B&)#''$*;&<		
 
	" AII1ik1 56IFIVI%>DD..{;}>	E%  	`2::>>-y9PQRU__G	`
  	H	,  b Js;   G, ,H= :I"I,A
H:9H:=II	IIr   N   )r   rO   r>   Optional[str]r   rO   rI   rN   r   N0u  )r   rO   r>   r  r   rO   rI   zOptional[dict])rI   
List[dict])r   rJ   r   rJ   rI   rN   )r   r   rI   None)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r(   r   r   r   -  s    /,, %)	

 #
 	

 

4 %)	 # 	
 
8T"	&^Er(   r   c                   t         st        dt        j                   d      t	        dd      }| xs
 t               |j                         	 	 	 d	 	 	 	 	 	 	 dd       }|j                         dd       }|j                         	 d	 	 	 	 	 dd       }|j                         	 	 	 	 	 	 dd	       }|j                         	 	 	 d	 	 	 	 	 	 	 dfd
       }|j                         	 	 	 d	 	 	 	 	 	 	 dfd       }|j                         	 	 	 	 	 	 dd       }|j                         ddd       }	|j                         dfd       }
|j                         	 	 	 	 	 	 dfd       }|S )zBCreate and return the Hermes MCP server with all tools registered.z5MCP server requires the 'mcp' package. Install with:  -m pip install 'mcp'hermeszHermes Agent messaging bridge. Use these tools to interact with conversations across Telegram, Discord, Slack, WhatsApp, Signal, Matrix, and other connected platforms.)instructionsc                H   t        |ddd      }t               }g }|j                         D ]8  \  }}|j                  di       }|j                  d      xs |j                  dd      }| r"|j	                         | j	                         k7  rb|j                  dd      }	|j                  d	d      }
|rG|j	                         }||	j	                         vr%||
j	                         vr||j	                         vr|j                  ||j                  d
d      ||j                  d|j                  dd            |	|
|j                  dd      |j                  dd      d       ; |j                  d d       |d| }t        j                  t        |      |dd      S )a  List active messaging conversations across connected platforms.

        Returns conversations with their session keys (needed for messages_read),
        platform, chat type, display name, and last activity time.

        Args:
            platform: Filter by platform name (telegram, discord, slack, etc.)
            limit: Maximum number of conversations to return (default 50)
            search: Optional text to filter conversations by name
        2   r      rt   ru   rv   rD   r1   r,   r?   r@   rC   r.   	user_namerF   )r>   rC   r1   r.   r?   r@   r  rF   c                &    | j                  dd      S )NrF   r,   r   )cs    r   r   z?create_mcp_server.<locals>.conversations_list.<locals>.<lambda>c  s    |R)@ r(   T)r\   reverseN)countconversations   indent)
rx   r'   rf   r   lowerr   sortrK   dumpsr   )r1   r   searchr&   r  r\   r   rD   entry_platformr?   r@   search_lowers               r   conversations_listz-create_mcp_server.<locals>.conversations_list4  s     E2q#F&(!--/ 	JCYYx,F"YYz2PfjjR6PNN002hnn6FF 99^R8L

;3I%||~ (:(:(<<(	0AA(		;  "#iib9*"YY{FJJ{B4OP ,&#ZZR8#iib9	" 	!	6 	@$O%fu-zz'*
  	r(   c                   t               }|j                  |       }|st        j                  dd|  i      S |j                  di       }t        j                  | |j                  dd      |j                  d      xs |j                  dd      |j                  d|j                  dd            |j                  dd      |j                  d	d      |j                  d
d      |j                  dd      |j                  d      |j                  dd      |j                  dd      |j                  dd      |j                  dd      |j                  dd      dd      S )zGet detailed info about one conversation by its session key.

        Args:
            session_key: The session key from conversations_list
        r   Conversation not found: rD   rC   r,   r1   r.   r?   r  r@   r-   r/   rF   rE   r;   r   r<   rG   )r>   rC   r1   r.   r?   r  r@   r-   r/   rF   rE   r;   r<   rG   r  r  )r'   r   rK   r  )r>   r&   r   rD   s       r   conversation_getz+create_mcp_server.<locals>.conversation_getm  s4    '(K(::w*B;-(PQRR8R(zz&))L"5		*-KJ1K;

;0KL!IInb9K4K4zz)R0K0))L"5))L"5!IIna8"YY:!IIna8
  	r(   c           
        t        |ddd      }t               }|j                  |       }|st        j                  dd|  i      S |j                  dd      }|st        j                  dd	i      S t               }|st        j                  dd
i      S 	 |j                  |      }g }|D ]i  }	|	j                  dd      }
|
dv st        |	      }|s(|j                  t        |	j                  dd            |
|dd |	j                  dd      d       k || d }t        j                  | t        |      t        |      |dd      S # t        $ r$}t        j                  dd| i      cY d}~S d}~ww xY w)aL  Read recent messages from a conversation.

        Returns the message history in chronological order with role, content,
        and timestamp for each message.

        Args:
            session_key: The session key from conversations_list
            limit: Maximum number of messages to return (default 50, most recent)
        r  r   r  r  r   r#  rC   r,   #No session ID for this conversationSession database unavailableFailed to read messages: Nr   >   r   r   r=   i  r   )r=   r   rz   r   )r>   r  total_in_sessionr   r  r  )rx   r'   r   rK   r  r"   r   r   r   r   rJ   r   )r>   r   r&   r   rC   rY   all_messagesr!   filteredr   r   rz   r   s                r   messages_readz(create_mcp_server.<locals>.messages_read  s    E2q#F&(K(::w*B;-(PQRRYY|R0
::w(MNOO::w(FGHH	J??:6L  
	C7762&D,,237OO!#''$"34 $#*5D>%(WW["%=	% 
	 UFG$zz&] #H 	

  	%  	J::w*CA3(GHII	Js   E 	E8E3-E83E8c                |   t               }|j                  |       }|st        j                  dd|  i      S |j                  dd      }|st        j                  ddi      S t	               }|st        j                  ddi      S 	 |j                  |      }d}|D ]$  }	t        |	j                  d	d            |k(  s"|	} n |st        j                  dd
| i      S t        |      }
t        j                  |t        |
      |
dd      S # t        $ r$}t        j                  dd| i      cY d}~S d}~ww xY w)a:  List non-text attachments for a message in a conversation.

        Extracts images, media files, and other non-text content blocks
        from the specified message.

        Args:
            session_key: The session key from conversations_list
            message_id: The message ID from messages_read
        r   r#  rC   r,   r&  r'  r(  Nr=   zMessage not found: )r   r  r   r  r  )
r'   r   rK   r  r"   r   r   rJ   r   r   )r>   r   r&   r   rC   rY   r*  r!   
target_msgr   r   s              r   attachments_fetchz,create_mcp_server.<locals>.attachments_fetch  sO    '(K(::w*B;-(PQRRYY|R0
::w(MNOO::w(FGHH	J??:6L
 
 	C3774$%3 
	
 ::w*=j\(JKLL*:6zz$%&
 	 	  	J::w*CA3(GHII	Js   D 	D;D60D;6D;c                    t        | ddd      } t        |ddd      }j                  | ||      }t        j                  |d	      S )
a  Poll for new conversation events since a cursor position.

        Returns events that have occurred since the given cursor. Use the
        returned next_cursor value for subsequent polls.

        Event types: message, approval_requested, approval_resolved

        Args:
            after_cursor: Return events after this cursor (0 for all)
            session_key: Optional filter to one conversation
            limit: Maximum events to return (default 20)
        r        NZor  r  r   r  )r   r>   r   r  r  )rx   r   rK   r  )r   r>   r   resultbridges       r   events_pollz&create_mcp_server.<locals>.events_poll  sV    $ #<AvVE2q#F##%# $ 

 zz&++r(   c                    t        | ddd      } t        |ddd      }j                  | ||      }|rt        j                  d|id	      S t        j                  d
ddd	      S )a  Wait for the next conversation event (long-poll).

        Blocks until a matching event arrives or the timeout expires.
        Use this for near-real-time event delivery without polling.

        Args:
            after_cursor: Wait for events after this cursor
            session_key: Optional filter to one conversation
            timeout_ms: Maximum wait time in milliseconds (default 30000)
        r   r1  r  r  i )r   r>   r   r   r  r  Nr   )r   reason)rx   r   rK   r  )r   r>   r   r   r3  s       r   events_waitz&create_mcp_server.<locals>.events_wait  s|      #<AvV 	

 %%%#! & 

 ::w.q99zzDI>qIIr(   c                   | r|st        j                  ddi      S 	 ddlm}  |d| |d      }|S # t        $ r t        j                  ddi      cY S t
        $ r$}t        j                  dd| i      cY d	}~S d	}~ww xY w)
u  Send a message to a platform conversation.

        The target format is "platform:chat_id" — same format used by the
        channels_list tool. You can also use human-friendly channel names
        that will be resolved automatically.

        Examples:
            target="telegram:6308981865"
            target="discord:#general"
            target="slack:#engineering"

        Args:
            target: Platform target in "platform:identifier" format
            message: The message text to send
        r   z$Both target and message are requiredr   )send_message_toolsend)actionr   r   zSend message tool not availablezSend failed: N)rK   r  tools.send_message_toolr9  r   r   )r   r   r9  
result_strr!   s        r   messages_sendz(create_mcp_server.<locals>.messages_send:  s    ( W::w(NOPP		>A*!VHJ  	L::w(IJKK 	>::w-s(;<==	>s!   1  A?A?A:4A?:A?c                   t               }|s9t               }g }t               }|j                         D ]  \  }}|j	                  di       }|j	                  d      xs |j	                  dd      }|j	                  dd      }	|r|	sT| r"|j                         | j                         k7  rx| d|	 }
|
|v r|j                  |
       |j                  |
||j	                  d      xs |j	                  dd      |j	                  d|j	                  dd            d	        t        j                  t        |      |d
d      S g }|j	                  di       j                         D ]  \  }}| r"|j                         | j                         k7  r*t        |t              s;|D ]  }t        |t              s|j	                  d|j	                  dd            }	|j                  |	r| d|	 n|||j	                  d|j	                  dd            |j	                  dd      d	         t        j                  t        |      |d
d      S )a:  List available messaging channels and targets across platforms.

        Returns channels that you can send messages to. The target strings
        returned here can be used directly with the messages_send tool.

        Args:
            platform: Filter by platform name (telegram, discord, slack, etc.)
        rD   r1   r,   r-   :r?   r@   r.   )r   r1   namer.   )r  channelsr  r  	platformsr=   rA  r{   )ro   r'   r   rf   r   r  addr   rK   r  r   rM   r~   rN   )r1   	directoryr&   targetsseenr\   r   rD   r   r-   
target_strrB  platentries_listchs                  r   channels_listz(create_mcp_server.<locals>.channels_list^  s    ,-	*,GG5D%mmo 
U8R0IIj)GVZZ
B-G **Y3	X^^-= = !s!G9-
%$( !!IIn5TKQS9T!&;

;PR8S!T	  $ ::G'JSTUU"+--R"@"F"F"H 	D,DJJLHNN,<<,-& B!"d+"$&&rvvi/D"E =Day&9$(,$&FF6266."3M$N)+);	) 		 zzCMxHQRSSr(   c                 j    j                         } t        j                  t        |       | dd      S )u!  List pending approval requests observed during this bridge session.

        Returns exec and plugin approval requests that the bridge has seen
        since it started. Approvals are live-session only — older approvals
        from before the bridge connected are not included.
        )r  	approvalsr  r  )r   rK   r  r   )rN  r3  s    r   permissions_list_openz0create_mcp_server.<locals>.permissions_list_open  s8     113	zz^"
  	r(   c                    |dvrt        j                  dd| di      S j                  | |      }t        j                  |d      S )zRespond to a pending approval request.

        Args:
            id: The approval ID from permissions_list_open
            decision: One of "allow-once", "allow-always", or "deny"
        >   
allow-onceallow-alwaysdenyr   zInvalid decision: z+. Must be allow-once, allow-always, or denyr  r  )rK   r  r   )r=   r   r2  r3  s      r   permissions_respondz.create_mcp_server.<locals>.permissions_respond  s_     AA::-hZ 8E F  
 ++B9zz&++r(   )Nr  N)r1   r  r   rO   r  r  rI   rJ   )r>   rJ   rI   rJ   )r  )r>   rJ   r   rO   rI   rJ   )r>   rJ   r   rJ   rI   rJ   r  )r   rO   r>   r  r   rO   rI   rJ   r  )r   rO   r>   r  r   rO   rI   rJ   )r   rJ   r   rJ   rI   rJ   N)r1   r  rI   rJ   rH   )r=   rJ   r   rJ   rI   rJ   )_MCP_SERVER_AVAILABLEr   sys
executabler   r   tool)event_bridgemcpr!  r$  r,  r/  r4  r7  r>  rL  rO  rT  r3  s               @r   create_mcp_serverr\    s[     ^^,,AC
 	

 5C *[]F 	XXZ"& $444 4 
	4 4p 	XXZ @ 	XXZ 444 
4 4p 	XXZ/// 
/ /f 	XXZ%),,", , 
	, ,8 	XXZ%)JJ"J J 
	J JB 	XXZ>>> 
> >F 	XXZ1T 1Tj 	XXZ  	XXZ,,, 
, ,& Jr(   c                6   t         sBt        dt        j                   dt        j                         t        j
                  d       | r4t        j                  t        j                  t        j                         n3t        j                  t        j                  t        j                         t               j                          t              ddl}fd	}	 |j                   |              y# t        $ r j!                          Y yw xY w)
z%Start the Hermes MCP server on stdio.z<Error: MCP server requires the 'mcp' package.
Install with: r  )filer   )levelstream)rZ  r   Nc                    K   	 j                          d {     j                          y 7 #  j                          w xY wwrU  )run_stdio_asyncr   )r3  servers   r   _runzrun_mcp_server.<locals>._run  s6     	((***KKM +KKMs%   A0 .0 A0 AA)rV  printrW  rX  stderrexitloggingbasicConfigDEBUGWARNINGr   r   r\  asynciorunKeyboardInterruptr   )verboserl  rd  r3  rc  s      @@r   run_mcp_serverrp    s      ^^,,AC	

 	'--

C'//#**E]F
LLNF3FDF s   %C< <DD)rI   r   )rI   rN   )rP   rN   rI   rN   )rt   rO   ru   rO   rv   rO   rI   rO   )r   rN   rI   rJ   )r   rN   rI   r  rU  )rZ  zOptional[EventBridge]rI   z	'FastMCP')F)ro  boolrI   r	  )*r   
__future__r   rK   rh  r   r   rW  r   r   dataclassesr   r   r   pathlibr   typingr	   r
   r   	getLoggerr   rV  mcp.server.fastmcpr   r   r   r"   r'   rR   r$   r%   ro   rx   r   r   r   r   r   r   r\  rp  r   r(   r   <module>rx     s  : #   	 	 
   (   ' '			-	.  * Y,")X62(/ / 	/
 / 	/&	+#T  - - -kE kEdY@Q  Gs   B7 7C C