Skip to main content
Glama
isdaniel

PostgreSQL-Performance-Tuner-Mcp

server.cpython-310.pyc10.4 kB
o $T%in,�@sUdZddlmZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z ddl mZddlmZmZmZmZz"ddlZddlmZdd lmZdd lmZdd lmZmZd ZWn eyld ZYnwddl m!Z!m"Z"m#Z#m$Z$ddl%m&Z&ddl'm(Z(m)Z)m*Z*m+Z+ddl,m-Z-m.Z.m/Z/m0Z0ddl1m2Z2m3Z3m4Z4ej5ej6dd�e�7d�Z8ed�Z9ia:de;d<da<de;d<dKdd �Z=dLd$d%�Z>dMd'd(�Z?dNd)d*�Z@d d+�dOd1d2�ZAe9�B�dPd4d5��ZBe9�C�dQd9d:��ZCdRd<d=�ZDdNd>d?�ZEd@dA�ZFdSdTdHdI�ZGeHdJk�r e�IeF��dSdS)Uz� pgtuner-mcp: PostgreSQL MCP Performance Tuning Server This server implements a modular, extensible design pattern for PostgreSQL performance tuning with HypoPG support for hypothetical index testing. Supports both stdio and SSE MCP server modes. �)� annotationsN)�Sequence)�Any)�Server)�EmbeddedResource� ImageContent� TextContent�Tool)�SseServerTransport)� Starlette)�Request)�Mount�RouteTF�)� DbConnPool� HypoPGService� IndexAdvisor� SqlDriver)� ToolHandler)�ActiveQueriesToolHandler�DatabaseHealthToolHandler�DatabaseSettingsToolHandler�WaitEventsToolHandler)�ExplainQueryToolHandler�HypoPGToolHandler�IndexAdvisorToolHandler�UnusedIndexesToolHandler)�AnalyzeQueryToolHandler�GetSlowQueriesToolHandler�TableStatsToolHandlerz4%(asctime)s - %(name)s - %(levelname)s - %(message)s)�level�format� pgtuner_mcpzdict[str, ToolHandler]� tool_handlerszDbConnPool | None�db_pool� tool_handlerr�return�NonecCs |t|j<t�d|j���dS)zy Register a tool handler with the server. Args: tool_handler: The tool handler instance to register zRegistered tool handler: N)r#�name�logger�info)r%�r+�5/home/azureuser/pgtuner_mcp/src/pgtuner_mcp/server.py�add_tool_handlerMs r-r(�str�ToolHandler | NonecCs t�|�S)z� Retrieve a tool handler by name. Args: name: The name of the tool handler Returns: The tool handler instance or None if not found )r#�get)r(r+r+r,�get_tool_handlerYs r1rcCstdurtd��tS)z� Get the global database connection pool. Returns: The database connection pool Raises: RuntimeError: If the database pool is not initialized Nz(Database connection pool not initialized)r$� RuntimeErrorr+r+r+r,� get_db_poolfs r3cCs�t�}t|�}t|�}t|�}tt|��tt|��tt|��tt|��tt ||��tt |��tt |��tt |��tt |��tt|��tt|��t�dtt��d��dS)z� Register all available tool handlers. This function serves as the central registry for all tools. New tool handlers should be added here for automatic registration. z Registered z tool handlersN)r3rrrr-rrrrrrrrrrrr)r*�lenr#)�pool� sql_driver�hypopg_service� index_advisorr+r+r,�register_all_toolsvs           r9��debug� mcp_serverrr;�boolr csFtstd��td��d��fdd� }t|td |d �td�jd �gd �S)z� Create a Starlette application that can serve the provided mcp server with SSE. Args: mcp_server: The MCP server instance debug: Whether to enable debug mode Returns: Starlette application instance zKSSE dependencies not available. Install with: pip install starlette uvicornz /messages/�requestr r&r'c �sl���|j|j|j�4IdH�\}}��||����IdHWd�IdHdS1IdHs/wYdS)N)� connect_sse�scope�receive�_send�run�create_initialization_options)r>� read_stream� write_stream�r<�sser+r,� handle_sse�s� � �.�z(create_starlette_app.<locals>.handle_ssez/sse)�endpoint)�app)r;�routesN)r>r r&r')� SSE_AVAILABLEr2r r rr �handle_post_message)r<r;rIr+rGr,�create_starlette_app�s    ��rO� list[Tool]c �s`�zdd�t��D�}t�dt|��d��|WSty/}z t�dt|�����d}~ww)zn List all available tools. Returns: List of Tool objects describing all registered tools cSsg|]}|���qSr+)�get_tool_definition)�.0�handlerr+r+r,� <listcomp>�szlist_tools.<locals>.<listcomp>zListed z available toolszError listing tools: N)r#�valuesr)r*r4� Exception� exceptionr.)�tools�er+r+r,� list_tools�s���rZ� argumentsr�7Sequence[TextContent | ImageContent | EmbeddedResource]c �s��z9t|t�s td��t|�}|std|����t�d|�dt|������|� |�IdH}t�d|�d��|WSt yt}z.t� d|�d t |����t ��}t�d |���td d |�d t |���d�gWYd}~Sd}~ww)a Execute a tool with the provided arguments. Args: name: The name of the tool to execute arguments: The arguments to pass to the tool Returns: Sequence of MCP content objects Raises: RuntimeError: If the tool execution fails zArguments must be a dictionaryzUnknown tool: zExecuting tool: z with arguments: NzTool z executed successfullyzError executing tool z: zFull traceback: �textzError executing tool 'z': )�typer])� isinstance�dictr2r1� ValueErrorr)r*�list�keys�run_toolrVrWr.� traceback� format_exc�errorr)r(r[r%�resultrY�error_tracebackr+r+r,� call_tool�s,� ����rj� database_uric�s&�t|�at��IdHt�d�dS)zm Initialize the database connection pool. Args: database_uri: PostgreSQL connection URI Nz1Database connection pool initialized successfully)rr$�connectr)r*)rkr+r+r,�initialize_db_pool�s�rmc�s.�tdurt��IdHdat�d�dSdS)z0 Clean up the database connection pool. NzDatabase connection pool closed)r$�closer)r*r+r+r+r,�cleanup_db_pools ��roc �s��tjdd�}|jdddgddd�|jdd d d �|jd td dd�|jdddd�|jdddd �|��}|jrHt���tj �t �tj �zvzU|j pRt j �d�}|sft �d�tdtjd�t�d�t|�IdHt�t �d|j�d��t �dtj���t �dtt������t|j|j|j|j�IdHWnty�}z t � d t!|�����d}~wwWt"�IdHdSt"�IdHw)!z} Main entry point for the pgtuner_mcp server. Supports both stdio and SSE modes based on command line arguments. zTpgtuner_mcp: PostgreSQL MCP Performance Tuning Server - supports stdio and SSE modes)� descriptionz--mode�stdiorHz#Server mode: stdio (default) or sse)�choices�default�helpz--host�0.0.0.0z1Host to bind to (SSE mode only, default: 0.0.0.0))rsrtz--port�z0Port to listen on (SSE mode only, default: 8080))r^rsrtz--debug� store_truezEnable debug mode)�actionrtz--database-urlNz7PostgreSQL connection URL (or use DATABASE_URI env var)� DATABASE_URIzUNo database URL provided. Set DATABASE_URI environment variable or use --database-urlz\Error: No database URL provided. Set DATABASE_URI environment variable or use --database-url)�filerzStarting pgtuner_mcp server in z mode...zPython version: zRegistered tools: zFailed to start server: )#�argparse�ArgumentParser� add_argument�int� parse_argsr;�logging� getLogger�setLevel�DEBUGr)� database_url�os�environr0rg�print�sys�stderr�exitrmr9r*�mode�versionrbr#rc� run_server�host�portrVrWr.ro)�parser�argsr�rYr+r+r,�mainsp�������  �  ���r�rurvr�r�r�r~c �s��|dkr>t�d�ddlm}|�4IdH�\}}t�||t���IdHWd�IdHdS1IdHs7wYdS|dkrutsHtd��t�d|�d |�d ��t t|d �}t j ||||rcd nd d�}t � |�} | � �IdHdStd|����)a  Unified server runner that supports both stdio and SSE modes. Args: mode: Server mode ("stdio" or "sse") host: Host to bind to (SSE mode only) port: Port to listen on (SSE mode only) debug: Whether to enable debug mode rqzStarting stdio server...r)� stdio_serverNrHzVSSE mode requires additional dependencies. Install with: pip install starlette uvicornzStarting SSE server on �:z...r:r;r*)rKr�r�� log_levelzUnknown mode: )r)r*�mcp.server.stdior�rKrCrDrMr2rO�uvicorn�Configr�servera) r�r�r�r;r�rErF� starlette_app�config�serverr+r+r,r�^s6�   �.��  � r��__main__)r%rr&r')r(r.r&r/)r&r)r&r')r<rr;r=r&r )r&rP)r(r.r[rr&r\)rkr.r&r')rurvF)r�r.r�r.r�r~r;r=)J�__doc__� __future__rr{�asyncior�r�r�re�collections.abcr�typingr� mcp.serverr� mcp.typesrrrr r��mcp.server.sser �starlette.applicationsr �starlette.requestsr �starlette.routingr rrM� ImportError�servicesrrrr�tools.toolhandlerr�tools.tools_healthrrrr�tools.tools_indexrrrr�tools.tools_performancerrr� basicConfig�INFOr�r)rKr#�__annotations__r$r-r1r3r9rOrZrjrmror�r��__name__rCr+r+r+r,�<module>sf        � �      %   .  K 2�

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/isdaniel/pgtuner-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server