Skip to main content
Glama

handle_get_table_definition

Retrieve the DDL statement for a specific table in Redshift schema via SQL script. Returns CREATE TABLE statement on success or error details if retrieval fails.

Instructions

Retrieves the DDL (Data Definition Language) statement for a specific table.

Executes a SQL script designed to generate or retrieve the CREATE TABLE
statement for the given table.

Args:
    ctx: The MCP context object.
    schema_name: The schema name of the table.
    table_name: The name of the table.

Returns:
    A dictionary conforming to GetTableDefinitionResult structure:
    - On success: {"status": "success", "ddl": "<CREATE TABLE statement>"}
    - On table not found or DDL retrieval error:
      {"status": "error", "error_message": "...", "error_type": "..."}

Raises:
    TableNotFound: If the specified table is not found.
    DataApiError: If a critical, unexpected error occurs during execution.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
schema_nameYes
table_nameYes

Implementation Reference

  • Core handler function decorated with @mcp.tool(). Executes 'SHOW TABLE' via Data API to retrieve table DDL, parses result, handles errors like TableNotFound.
    @mcp.tool()
    async def handle_get_table_definition(
        ctx: Context, schema_name: str, table_name: str
    ) -> str:
        """Retrieves the DDL (Data Definition Language) statement for a specific table.
    
        Executes a SQL script designed to generate or retrieve the CREATE TABLE
        statement for the given table.
    
        Args:
            ctx: The MCP context object.
            schema_name: The schema name of the table.
            table_name: The name of the table.
    
        Returns:
            A dictionary conforming to GetTableDefinitionResult structure:
            - On success: {"status": "success", "ddl": "<CREATE TABLE statement>"}
            - On table not found or DDL retrieval error:
              {"status": "error", "error_message": "...", "error_type": "..."}
    
        Raises:
            TableNotFound: If the specified table is not found.
            DataApiError: If a critical, unexpected error occurs during execution.
        """
        ctx.info(f"Starting DDL retrieval for: {schema_name}.{table_name}...")
    
        sql: str = f"SHOW TABLE {schema_name}.{table_name}"
        ctx.debug(f"Executing command: {sql}")
        try:
            config: DataApiConfig = get_data_api_config()
            ddl_rows: List[Dict[str, Any]] = await execute_sql(
                config=config, sql=sql, params=None
            )
    
            if not ddl_rows:
                ctx.warning(
                    f"Table '{schema_name}.{table_name}' not found or DDL could not be retrieved."
                )
                raise TableNotFound(
                    f"Table '{schema_name}.{table_name}' not found or DDL could not be retrieved."
                )
    
            ctx.debug(f"Parsing DDL result for {schema_name}.{table_name}")
            first_row = ddl_rows[0]
            ddl_string: Optional[str] = list(first_row.values())[0] if first_row else None
            if not isinstance(ddl_string, str) or not ddl_string.strip().upper().startswith(
                "CREATE TABLE"
            ):
                ctx.error(
                    f"DDL column missing or null in result for {schema_name}.{table_name}"
                )
    
                raise DataApiError(
                    f"Could not extract DDL string for table '{schema_name}.{table_name}'. Query returned no DDL column."
                )
    
            ctx.info(f"DDL for {schema_name}.{table_name} retrieved successfully.")
    
            return ddl_string
    
        except TableNotFound as e:
    
            raise e
        except (
            SqlScriptNotFoundError,
            DataApiError,
            SqlExecutionError,
            ClientError,
        ) as e:
            ctx.error(
                f"SQL execution failed while retrieving DDL for {schema_name}.{table_name}: {e}",
                exc_info=True,
            )
            raise
        except Exception as e:
            ctx.error(f"Unexpected error getting DDL for {schema_name}.{table_name}: {e}")
            raise DataApiError(
                f"An unexpected server error occurred while retrieving DDL: {e}"
            )
  • Output schema definitions using TypedDict for success (status, ddl) and error (status, error_message, error_type) cases, unioned as GetTableDefinitionResult.
    class GetTableDefinitionSuccessResult(TypedDict):
        status: str
        ddl: str
    
    
    class GetTableDefinitionErrorResult(TypedDict):
        status: str
        error_message: str
        error_type: str
    
    
    GetTableDefinitionResult = Union[
        GetTableDefinitionSuccessResult, GetTableDefinitionErrorResult
    ]
  • Imports tool handlers from tools/handlers package into the FastMCP server module, including get_table_definition (alias for handle_get_table_definition), which triggers registration via decorators.
    from .tools.handlers import (  # noqa: E402
        check_cluster_health,
        diagnose_locks,
        diagnose_query_performance,
        execute_ad_hoc_query,
        get_table_definition,
        inspect_table,
        monitor_workload,
    )
  • References all imported handlers in a discarded tuple to ensure they are loaded and registered by FastMCP decorators.
    _ = (
        check_cluster_health,
        diagnose_locks,
        diagnose_query_performance,
        execute_ad_hoc_query,
        get_table_definition,
        inspect_table,
        monitor_workload,
        resource_handlers,
        prompt_handlers,
    )
  • Re-exports handle_get_table_definition from its module and includes in __all__ for convenient import in server.py.
    from .get_table_definition import handle_get_table_definition
    from .inspect_table import handle_inspect_table
    from .monitor_workload import handle_monitor_workload
    
    __all__ = [
        "handle_check_cluster_health",
        "handle_diagnose_locks",
        "handle_diagnose_query_performance",
        "handle_execute_ad_hoc_query",
        "handle_get_table_definition",
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by detailing success/error return structures, specific exception types (TableNotFound, DataApiError), and the SQL script execution behavior. However, it doesn't mention performance characteristics, rate limits, or authentication requirements that would be helpful for a database tool.

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

Conciseness5/5

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

The description is well-structured with clear sections (purpose, execution details, Args, Returns, Raises) and every sentence adds value. It's appropriately sized for a tool with 2 parameters and complex return behavior, with no redundant information.

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 excellent coverage of parameters, return values, and exceptions. The main gap is lack of guidance on when to use versus sibling tools, but otherwise it's quite complete for the tool's complexity level.

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?

The description provides explicit parameter documentation in the Args section, clearly explaining what schema_name and table_name represent. With 0% schema description coverage, this comprehensive parameter documentation fully compensates and adds significant value beyond the bare input 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 ('Retrieves the DDL statement') and resource ('for a specific table'), distinguishing it from sibling tools like handle_execute_ad_hoc_query or handle_inspect_table. It explicitly mentions the SQL script execution aspect, providing precise functional context.

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 when needing table DDL, but doesn't explicitly state when to use this tool versus alternatives like handle_inspect_table or handle_execute_ad_hoc_query. No guidance is provided on prerequisites, error handling expectations, or specific scenarios where this tool is preferred over siblings.

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

Related 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/vinodismyname/redshift-utils-mcp'

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