Skip to main content
Glama
biocontext-ai

BioContextAI Knowledgebase MCP

Official

bc_query_kegg

Query the KEGG database to retrieve biological pathway, gene, compound, disease, and drug information for research analysis.

Instructions

Execute flexible KEGG API queries across pathways, genes, compounds, diseases, drugs. Use get_kegg_id_by_gene_symbol() first.

Returns: str or dict: Raw text response from KEGG API with requested data (pathways, genes, compounds, etc.) or error dict.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
operationYesinfo, list, find, get, conv, link, or ddi
databaseNopathway, compound, genes, organism code (hsa, mmu, etc.), or other DB
target_dbNoTarget DB for conversion/linking operations
source_dbNoSource DB for conversion/linking operations
queryNoQuery string for FIND/LIST, or organism code for LIST
optionNoaaseq, ntseq, mol, formula, exact_mass, mol_weight, etc.
entriesNoKEGG entry IDs (e.g., ['hsa:7157', 'hsa00010'])

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main handler function for the 'bc_query_kegg' tool. Decorated with @core_mcp.tool(), constructs KeggConfig from inputs, validates, and executes the KEGG API query.
    @core_mcp.tool()
    def query_kegg(
        operation: Annotated[KeggOperation, Field(description="info, list, find, get, conv, link, or ddi")],
        database: Annotated[
            Optional[Union[KeggDatabase, KeggOutsideDb, str]],
            Field(description="pathway, compound, genes, organism code (hsa, mmu, etc.), or other DB"),
        ] = None,
        target_db: Annotated[
            Optional[Union[KeggDatabase, KeggOutsideDb, str]],
            Field(description="Target DB for conversion/linking operations"),
        ] = None,
        source_db: Annotated[
            Optional[Union[KeggDatabase, KeggOutsideDb, str]],
            Field(description="Source DB for conversion/linking operations"),
        ] = None,
        query: Annotated[Optional[str], Field(description="Query string for FIND/LIST, or organism code for LIST")] = None,
        option: Annotated[
            Optional[Union[KeggOption, KeggFindOption, KeggRdfFormat]],
            Field(description="aaseq, ntseq, mol, formula, exact_mass, mol_weight, etc."),
        ] = None,
        entries: Annotated[
            Optional[List[str]], Field(description="KEGG entry IDs (e.g., ['hsa:7157', 'hsa00010'])")
        ] = None,
    ) -> str | dict:
        """Execute flexible KEGG API queries across pathways, genes, compounds, diseases, drugs. Use get_kegg_id_by_gene_symbol() first.
    
        Returns:
            str or dict: Raw text response from KEGG API with requested data (pathways, genes, compounds, etc.) or error dict.
        """
        config = KeggConfig(
            operation=operation,
            database=database,
            target_db=target_db,
            source_db=source_db,
            query=query,
            option=option,
            entries=entries or [],
        )
        try:
            KeggConfig.model_validate(config)
        except ValueError as e:
            return {"error": f"Invalid configuration: {e}"}
    
        try:
            return config.execute()
        except Exception as e:
            return {"error": f"Failed to execute KEGG query: {e}"}
  • Pydantic model KeggConfig and its methods for validating inputs, building API paths, and executing queries. Includes field validators for databases. Used by the handler for schema validation.
    class KeggConfig(BaseModel):
        """Configuration for KEGG API queries.
    
        This model encapsulates the parameters needed to construct a valid KEGG API request.
        The parameters required depend on the operation being performed.
        """
    
        operation: KeggOperation
        database: Optional[Union[KeggDatabase, KeggOutsideDb, str]] = None
        target_db: Optional[Union[KeggDatabase, KeggOutsideDb, str]] = None
        source_db: Optional[Union[KeggDatabase, KeggOutsideDb, str]] = None
        query: Optional[str] = None
        option: Optional[Union[KeggOption, KeggFindOption, KeggRdfFormat]] = None
        entries: Optional[List[str]] = Field(default_factory=lambda: [])
    
        @field_validator("database", "target_db", "source_db", mode="before")
        @classmethod
        def validate_db(cls, v):
            """Allow organism codes as database values.
    
            This validator handles KEGG organism codes (like 'hsa' for human) as valid database values.
            """
            if v is None:
                return v
            # Check if value is in one of the enums
            try:
                return KeggDatabase(v)
            except ValueError:
                try:
                    return KeggOutsideDb(v)
                except ValueError:
                    # Assume it's an organism code or custom string
                    return v
    
        def build_path(self) -> str:
            """Build the API path based on the configuration.
    
            This method constructs the URL path for the KEGG API request based on the
            operation and parameters provided.
            """
            path_parts = [self.operation.value.lower()]
    
            if self.operation == KeggOperation.INFO:
                if self.database:
                    path_parts.append(str(self.database.value if isinstance(self.database, Enum) else self.database))
    
            elif self.operation == KeggOperation.LIST:
                if self.database:
                    path_parts.append(str(self.database.value if isinstance(self.database, Enum) else self.database))
                    # Special case for pathway/organism
                    if self.database == KeggDatabase.PATHWAY and self.query:
                        path_parts.append(self.query)
                    # Special case for brite/option
                    elif self.database == KeggDatabase.BRITE and self.option:
                        path_parts.append(str(self.option.value if isinstance(self.option, Enum) else self.option))
                elif self.entries:
                    path_parts.append("+".join(self.entries))
    
            elif self.operation == KeggOperation.FIND:
                if self.database and self.query:
                    path_parts.append(str(self.database.value if isinstance(self.database, Enum) else self.database))
                    path_parts.append(self.query)
                    if self.option:
                        path_parts.append(str(self.option.value if isinstance(self.option, Enum) else self.option))
    
            elif self.operation == KeggOperation.GET:
                if self.entries or self.query:
                    if self.entries:
                        path_parts.append("+".join(self.entries))
                    elif self.query:
                        path_parts.append(self.query)
    
                    if self.option:
                        path_parts.append(str(self.option.value if isinstance(self.option, Enum) else self.option))
    
            elif self.operation == KeggOperation.CONV:
                if self.target_db and self.source_db:
                    path_parts.append(str(self.target_db.value if isinstance(self.target_db, Enum) else self.target_db))
                    path_parts.append(str(self.source_db.value if isinstance(self.source_db, Enum) else self.source_db))
                elif self.target_db and self.entries:
                    path_parts.append(str(self.target_db.value if isinstance(self.target_db, Enum) else self.target_db))
                    path_parts.append("+".join(self.entries))
    
            elif self.operation == KeggOperation.LINK:
                if self.target_db and self.source_db:
                    path_parts.append(str(self.target_db.value if isinstance(self.target_db, Enum) else self.target_db))
                    path_parts.append(str(self.source_db.value if isinstance(self.source_db, Enum) else self.source_db))
                    if self.option:
                        path_parts.append(str(self.option.value if isinstance(self.option, Enum) else self.option))
                elif self.target_db and self.entries:
                    path_parts.append(str(self.target_db.value if isinstance(self.target_db, Enum) else self.target_db))
                    path_parts.append("+".join(self.entries))
                    if self.option:
                        path_parts.append(str(self.option.value if isinstance(self.option, Enum) else self.option))
    
            elif self.operation == KeggOperation.DDI and self.entries:
                path_parts.append("+".join(self.entries))
    
            return "/".join(path_parts)
    
        def execute(self) -> str:
            """Execute the API query based on the configuration.
    
            Performs the actual HTTP request to the KEGG API.
            """
            path = self.build_path()
            return execute_kegg_query(path)
  • Registers the core_mcp server (named 'BC', slugged to 'bc') into the main FastMCP app, prefixing its tools (e.g., 'query_kegg' becomes 'bc_query_kegg').
    for mcp in [core_mcp, *(await get_openapi_mcps())]:
        await mcp_app.import_server(
            mcp,
            slugify(mcp.name),
        )
  • Helper function that performs the actual HTTP GET request to the KEGG REST API endpoint.
    import requests
    
    
    def execute_kegg_query(path: str) -> str:
        """Internal helper - executes the HTTP GET and returns raw text."""
        base = "https://rest.kegg.jp"
        url = f"{base}/{path.lstrip('/')}"
        r = requests.get(url, timeout=30.0)
        r.raise_for_status()
        return r.text
  • Imports the query_kegg function, triggering its registration via the @core_mcp.tool() decorator when the module is imported.
    from ._get_kegg_id_by_gene_symbol import get_kegg_id_by_gene_symbol
    from ._query_kegg import query_kegg
    
    __all__ = [
        "get_kegg_id_by_gene_symbol",
        "query_kegg",
    ]
  • Defines the core_mcp FastMCP server instance named 'BC', to which tools like query_kegg are attached via decorators.
    from fastmcp import FastMCP
    
    core_mcp = FastMCP(  # type: ignore
        "BC",
        instructions="Provides access to biomedical knowledge bases.",
    )
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses the return type ('str or dict: Raw text response from KEGG API') and error handling ('or error dict'), which is valuable. However, it doesn't mention rate limits, authentication requirements, pagination behavior, or whether queries are read-only versus mutating operations.

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 states the purpose and scope, while the second describes the return values. Both sentences earn their place, though the structure could be slightly improved by front-loading the most critical information about when to use the tool.

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

Completeness4/5

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

Given the tool's complexity (7 parameters, 100% schema coverage, output schema exists), the description provides reasonable completeness. It explains the tool's purpose, mentions a prerequisite tool, and describes return values. The existence of an output schema means the description doesn't need to detail return formats. However, for a flexible query tool with no annotations, more behavioral context would be beneficial.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already documents all 7 parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema. The baseline score of 3 is appropriate when the schema does the heavy lifting for parameter documentation.

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: 'Execute flexible KEGG API queries across pathways, genes, compounds, diseases, drugs.' It specifies the verb ('execute') and resources ('KEGG API queries'), but doesn't explicitly differentiate from sibling tools like bc_get_kegg_id_by_gene_symbol, which is mentioned as a prerequisite rather than an alternative.

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

Usage Guidelines4/5

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

The description provides clear usage guidance: 'Use get_kegg_id_by_gene_symbol() first.' This indicates a prerequisite relationship with a sibling tool. However, it doesn't specify when to use this tool versus alternatives or provide explicit exclusion criteria for different query scenarios.

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/biocontext-ai/knowledgebase-mcp'

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