Skip to main content
Glama

getSubgraphSchema

Fetch the GraphQL schema of a specified subgraph using introspection. Retrieve schema structure as JSON or GraphQL text format to understand available queries and data types.

Instructions

Fetch the schema of a specified subgraph using GraphQL introspection.

Args: subgraphId (str): The ID of the subgraph to query. asText (bool): If True, return schema as GraphQL text; otherwise, return JSON.

Returns: str: Schema in JSON or GraphQL text format, or an error message.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
subgraphIdYes
asTextNo

Implementation Reference

  • main.py:40-88 (handler)
    The handler function decorated with @mcp.tool(), implementing the core logic: performs GraphQL introspection query on TheGraph API for the given subgraphId, optionally converts JSON schema to GraphQL text using helper, handles errors.
    @mcp.tool()
    async def getSubgraphSchema(subgraphId: str, asText: bool = False) -> str:
        """Fetch the schema of a specified subgraph using GraphQL introspection.
    
        Args:
            subgraphId (str): The ID of the subgraph to query.
            asText (bool): If True, return schema as GraphQL text; otherwise, return JSON.
    
        Returns:
            str: Schema in JSON or GraphQL text format, or an error message.
        """
        if not API_KEY:
            return "API key is required. Set THEGRAPH_API_KEY in your .env file."
        
        async with httpx.AsyncClient() as client:
            url = f"{THEGRAPH_API_BASE_URL}{API_KEY}/subgraphs/id/{subgraphId}"
            introspection_query = """
            query IntrospectionQuery {
              __schema {
                types {
                  name
                  kind
                  fields {
                    name
                    type {
                      name
                      kind
                      ofType {
                        name
                        kind
                      }
                    }
                  }
                }
              }
            }
            """
            try:
                response = await client.post(url, json={"query": introspection_query}, timeout=10)
                response.raise_for_status()
                schema_data = response.json()
                if "data" in schema_data and "__schema" in schema_data["data"]:
                    schema = schema_data["data"]["__schema"]
                    return json_to_graphql_schema(schema) if asText else json.dumps(schema)
                else:
                    return f"Failed to fetch schema for {subgraphId}"
            except httpx.HTTPError as e:
                return f"Error fetching schema: {str(e)}"
  • main.py:19-38 (helper)
    Supporting utility function called by the handler when asText=True to convert the introspection JSON schema into human-readable GraphQL Schema Definition Language (SDL) text.
    def json_to_graphql_schema(schema_json):
        """Convert JSON schema from introspection to GraphQL text format."""
        types = schema_json["types"]
        schema_text = ""
        
        for t in types:
            if t["kind"] == "OBJECT" and not t["name"].startswith("__"):
                schema_text += f"type {t['name']} {{\n"
                if t["fields"]:
                    for f in t["fields"]:
                        field_type = f["type"]
                        type_name = field_type["name"]
                        if field_type["kind"] == "NON_NULL":
                            type_name = f"{field_type['ofType']['name']}!"
                        elif field_type["kind"] == "LIST":
                            type_name = f"[{field_type['ofType']['name']}]"
                        schema_text += f"  {f['name']}: {type_name}\n"
                schema_text += "}\n\n"
        
        return schema_text.strip()
  • main.py:40-40 (registration)
    The @mcp.tool() decorator registers the getSubgraphSchema function as an MCP tool.
    @mcp.tool()
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 format options (JSON or GraphQL text) and mentions error messages, but lacks details about authentication requirements, rate limits, or what happens with invalid subgraph IDs.

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 well-structured with a clear purpose statement followed by Args and Returns sections. It's appropriately sized, though the 'Args' and 'Returns' labels could be more integrated with the flow rather than section headers.

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?

For a tool with 2 parameters, no annotations, and no output schema, the description provides good coverage of purpose, parameters, and return behavior. It could be more complete by addressing authentication or error scenarios, but covers the essentials adequately.

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

Parameters5/5

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

With 0% schema description coverage, the description fully compensates by clearly explaining both parameters: 'subgraphId' specifies which subgraph to query, and 'asText' controls the return format (text vs JSON). This adds essential meaning beyond the bare schema.

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

Purpose5/5

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

The description clearly states the specific action ('Fetch the schema') and resource ('specified subgraph using GraphQL introspection'), distinguishing it from the sibling 'querySubgraph' which presumably executes queries rather than fetching schema metadata.

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

Usage Guidelines3/5

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

The description implies usage for obtaining schema information via introspection, but does not explicitly state when to use this tool versus the sibling 'querySubgraph' or provide any exclusions or prerequisites for usage.

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/kukapay/thegraph-mcp'

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