Skip to main content
Glama
biocontext-ai

BioContextAI Knowledgebase MCP

Official

bc_count_drugs_by_field

Count unique values in FDA-approved drug fields for statistical analysis. Specify a field like 'sponsor_name' or 'dosage_form' to get term frequencies.

Instructions

Count unique values in a field across FDA-approved drugs. Useful for statistical analysis.

Returns: dict: Results array with term and count for each unique value or error message.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fieldYesField to count (e.g., 'sponsor_name', 'products.dosage_form', 'products.route', 'openfda.pharm_class_epc')
search_filterNoOptional search filter to apply before counting
limitNoMaximum number of count results to return

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The primary handler function for the bc_count_drugs_by_field tool. It uses the @core_mcp.tool() decorator for registration and includes inline Pydantic schema validation via Annotated Fields. Queries the OpenFDA API to count unique values in specified drug fields.
    @core_mcp.tool()
    def count_drugs_by_field(
        field: Annotated[
            str,
            Field(
                description="Field to count (e.g., 'sponsor_name', 'products.dosage_form', 'products.route', 'openfda.pharm_class_epc')"
            ),
        ],
        search_filter: Annotated[
            Optional[str], Field(description="Optional search filter to apply before counting")
        ] = None,
        limit: Annotated[int, Field(description="Maximum number of count results to return", ge=1, le=1000)] = 100,
    ) -> dict:
        """Count unique values in a field across FDA-approved drugs. Useful for statistical analysis.
    
        Returns:
            dict: Results array with term and count for each unique value or error message.
        """
        # If field is an array, use .exact for correct counting
        array_fields = [
            "openfda.brand_name",
            "openfda.generic_name",
            "openfda.manufacturer_name",
            "openfda.pharm_class_epc",
            "openfda.pharm_class_moa",
            "openfda.pharm_class_pe",
            "openfda.pharm_class_cs",
            "products.brand_name",
        ]
        count_field = field + ".exact" if field in array_fields and not field.endswith(".exact") else field
        url_params = {"count": count_field, "limit": limit}
    
        # Add search filter if provided
        if search_filter:
            url_params["search"] = search_filter
    
        # Build the complete URL
        base_url = "https://api.fda.gov/drug/drugsfda.json"
    
        try:
            response = requests.get(base_url, params=url_params)  # type: ignore
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {"error": f"Failed to fetch FDA drug count data: {e!s}"}
  • Registers the core_mcp server (containing the tool) into the main BioContextAI MCP application under the prefixed namespace 'bc' (from slugify('BC')), making the tool available as 'bc_count_drugs_by_field'.
    for mcp in [core_mcp, *(await get_openapi_mcps())]:
        await mcp_app.import_server(
            mcp,
            slugify(mcp.name),
        )
  • Defines the core_mcp FastMCP instance named 'BC' where individual tools like count_drugs_by_field are registered via decorators. This MCP is later imported into the main app with 'bc' prefix.
    core_mcp = FastMCP(  # type: ignore
        "BC",
        instructions="Provides access to biomedical knowledge bases.",
    )
  • Imports the openfda module, which triggers the loading and decorator-based registration of the count_drugs_by_field tool into core_mcp.
    from .openfda import *
  • Exposes the count_drugs_by_field function for import, facilitating its registration when the openfda module is imported.
    from ._count_drugs import count_drugs_by_field, get_drug_statistics
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. It mentions the return type ('dict: Results array with term and count for each unique value or error message'), which adds some context beyond the input schema, but it lacks details on permissions, rate limits, error conditions, or data freshness. For a tool with no annotations, this is insufficient to fully inform the agent about behavioral traits.

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 and front-loaded: the first sentence states the core purpose clearly, and the second sentence adds usage context and return details. There's no wasted text, but the structure could be slightly improved by integrating the return info more seamlessly, hence not a perfect score.

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 context: the tool has 3 parameters with 100% schema coverage and an output schema (implied by 'Returns: dict'), the description is reasonably complete. It explains the purpose and return format, which complements the structured data. However, it could benefit from more behavioral details (e.g., error handling or limits) to be fully comprehensive, especially with no annotations provided.

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?

The schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description doesn't add any additional meaning or examples beyond what's in the schema (e.g., it doesn't elaborate on 'field' options or 'search_filter' usage). According to the rules, with high schema coverage, the baseline is 3 even without param info in the description, which fits here.

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: 'Count unique values in a field across FDA-approved drugs.' It specifies the verb ('count'), resource ('FDA-approved drugs'), and scope ('unique values in a field'), which is specific and actionable. However, it doesn't explicitly differentiate from sibling tools like 'bc_get_drug_statistics' or 'bc_search_drugs_fda', which might also involve drug data analysis, so it doesn't reach the highest score.

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

Usage Guidelines2/5

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

The description provides minimal usage guidance: 'Useful for statistical analysis' is a general benefit statement that implies context but doesn't specify when to use this tool versus alternatives. There's no explicit mention of when-not-to-use or named alternatives among the many sibling tools, leaving the agent with little practical direction for tool selection.

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