Skip to main content
Glama
longevity-genie

OpenGenes MCP Server

opengenes_db_query

Query aging and longevity research data from the OpenGenes database to access gene information, lifespan experiments, and aging-related changes across organisms using SQL.

Instructions

Query the Opengenes database that contains data about genes involved in longevity, lifespan extension experiments on model organisms, and changes in human and other organisms with aging. Before caling this tool the first time, always check tools that provide schema information and example queries.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
rowsYesQuery result rows
countYesNumber of rows returned
queryYesThe SQL query that was executed

Implementation Reference

  • The handler function for the opengenes_db_query tool. Executes the provided SQL query using the DatabaseManager and returns the QueryResult.
    def db_query(self, sql: str) -> QueryResult:
        """
        Execute a read-only SQL query against the OpenGenes database.
        
        SECURITY: This tool uses SQLite's built-in read-only mode to enforce data protection.
        The database connection is opened in read-only mode, preventing any write operations
        at the database level. Any attempt to modify data will be automatically rejected by SQLite.
        
        The OpenGenes database contains aging and lifespan research data across 4 tables:
        - lifespan_change: Experimental data on gene modifications and lifespan effects
        - gene_criteria: Aging-related criteria classifications for genes  
        - gene_hallmarks: Links genes to hallmarks of aging (multi-value field)
        - longevity_associations: Population genetics data on gene variants and longevity
        
        All tables are linked by HGNC gene symbols for cross-table analysis.
        
        CRITICAL REMINDERS:
        - Use LIKE queries with wildcards for multi-value fields (gene_hallmarks."hallmarks of aging", 
          lifespan_change.intervention_improves, lifespan_change.intervention_deteriorates)
        - Order lifespan results by magnitude: DESC for increases, ASC for decreases
        - IMPORTANT: When user asks about "lifespan effects" without specifying mean vs max, 
          show both lifespan_percent_change_mean AND lifespan_percent_change_max
        - Use COALESCE(lifespan_percent_change_mean, lifespan_percent_change_max) for ordering both metrics
        - COMPREHENSIVE AGING EVIDENCE: When users ask about "evidence of aging", "link to aging/longevity", 
          or "aging associations" for a gene, query ALL 4 tables (gene_criteria, gene_hallmarks, 
          lifespan_change, longevity_associations) for complete scientific evidence
        
        For detailed schema information, use get_schema_info().
        For query examples and patterns, use get_example_queries().
        
        Args:
            sql: The SQL query to execute (database enforces read-only access)
            
        Returns:
            QueryResult: Contains the query results, row count, and executed query
        """
        with start_action(action_type="db_query_tool", sql=sql) as action:
            result = self.db_manager.execute_query(sql)
            return result
  • Registers the opengenes_db_query tool using FastMCP's tool decorator with name constructed from prefix + 'db_query' and binds it to the db_query handler.
    def _register_opengenes_tools(self):
        """Register OpenGenes-specific tools."""
        self.tool(name=f"{self.prefix}get_schema_info", description="Get information about the database schema")(self.get_schema_info)
        self.tool(name=f"{self.prefix}example_queries", description="Get a list of example SQL queries")(self.get_example_queries)
        description = "Query the Opengenes database that contains data about genes involved in longevity, lifespan extension experiments on model organisms, and changes in human and other organisms with aging."
        if self.huge_query_tool:
            # Load and concatenate the prompt from package data
            prompt_content = get_prompt_content().strip()
            if prompt_content:
                description = description + "\n\n" + prompt_content
            self.tool(name=f"{self.prefix}db_query", description=description)(self.db_query)
        else:
            description = description + " Before caling this tool the first time, always check tools that provide schema information and example queries."
            self.tool(name=f"{self.prefix}db_query", description=description)(self.db_query)
  • Pydantic model defining the output schema for the db_query tool response.
    class QueryResult(BaseModel):
        """Result from a database query."""
        rows: List[Dict[str, Any]] = Field(description="Query result rows")
        count: int = Field(description="Number of rows returned")
        query: str = Field(description="The SQL query that was executed")
  • DatabaseManager.execute_query: Core helper that performs the actual SQL execution in read-only mode, used by the db_query handler.
    def execute_query(self, sql: str, params: Optional[tuple] = None) -> QueryResult:
        """Execute a read-only SQL query and return results."""
        with start_action(action_type="execute_query", sql=sql, params=params) as action:
            # Execute query using read-only connection - SQLite will enforce read-only at database level
            # Using URI format with mode=ro for true read-only access
            readonly_uri = f"file:{self.db_path}?mode=ro"
            
            try:
                with sqlite3.connect(readonly_uri, uri=True) as conn:
                    conn.row_factory = sqlite3.Row  # This allows dict-like access to rows
                    cursor = conn.cursor()
                    
                    if params:
                        cursor.execute(sql, params)
                    else:
                        cursor.execute(sql)
                    
                    rows = cursor.fetchall()
                    # Convert sqlite3.Row objects to dictionaries
                    rows_dicts = [dict(row) for row in rows]
                    
                    result = QueryResult(
                        rows=rows_dicts,
                        count=len(rows_dicts),
                        query=sql
                    )
                    
                    action.add_success_fields(rows_count=len(rows_dicts))
                    return result
            except sqlite3.OperationalError as e:
                if "readonly database" in str(e).lower():
                    error_msg = f"Write operation attempted on read-only database. Rejected query: {sql}"
                    action.log(message_type="query_rejected", error=error_msg, rejected_query=sql)
                    raise ValueError(error_msg) from e
                else:
                    # Re-raise other operational errors
                    raise
  • OpenGenesMCP.__init__: Initializes the server, sets the tool prefix to 'opengenes_', and calls _register_opengenes_tools() to register the tools.
    def __init__(
        self, 
        name: str = "OpenGenes MCP Server",
        db_path: Path = DB_PATH,
        prefix: str = "opengenes_",
        huge_query_tool: bool = False,
        **kwargs
    ):
        """Initialize the OpenGenes tools with a database manager and FastMCP functionality."""
        # Initialize FastMCP with the provided name and any additional kwargs
        super().__init__(name=name, **kwargs)
        
        # Initialize our database manager
        self.db_manager = DatabaseManager(db_path)
        
        self.prefix = prefix
        self.huge_query_tool = huge_query_tool
        # Register our tools and resources
        self._register_opengenes_tools()
        self._register_opengenes_resources()
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. While it mentions the database content and query action, it lacks critical behavioral details: what type of queries are supported (e.g., SELECT only?), authentication requirements, rate limits, error handling, or what the output looks like (though an output schema exists). The description adds some context but is insufficient for a mutation-like tool (querying a database).

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized with two sentences. The first sentence clearly states the purpose, and the second provides critical usage guidance. Both sentences earn their place, though it could be slightly more front-loaded by leading with the action (query) more explicitly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (database query tool), no annotations, and 0% schema coverage, the description is moderately complete. It covers purpose and usage guidelines well, and an output schema exists to handle return values. However, it lacks details on parameter semantics and behavioral transparency, leaving gaps for the agent to infer how to use the tool effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description provides no information about the single parameter 'sql', and schema description coverage is 0%. It doesn't explain what SQL syntax is expected, valid query types, or any constraints (e.g., read-only queries). The baseline would be lower, but the usage guideline indirectly hints at checking schema tools for parameter details, offering minimal compensation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: to query a specific database (Opengenes) containing gene data related to longevity and aging. It specifies the database content (genes involved in longevity, lifespan experiments, aging changes) and the action (query). However, it doesn't explicitly differentiate from its siblings (opengenes_example_queries, opengenes_get_schema_info) beyond the query action.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit usage guidance: 'Before calling this tool the first time, always check tools that provide schema information and example queries.' This directly references the sibling tools (opengenes_example_queries, opengenes_get_schema_info) as prerequisites, giving clear when-to-use instructions and alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/longevity-genie/opengenes-mcp'

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