Skip to main content
Glama
blitzstermayank

Teradata MCP Server

base_tableAffinity

Analyze table usage patterns to identify relationships between database tables, supporting SQL query generation and metadata extraction for Teradata databases.

Instructions

Get tables commonly used together by database users, this is helpful to infer relationships between tables via SQLAlchemy, bind parameters if provided (prepared SQL), and return the fully rendered SQL (with literals) in metadata.

Arguments: database_name - Database name object_name - table or view name

Returns: ResponseType: formatted response with query results + metadata

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
database_nameYes
obj_nameYes

Implementation Reference

  • The handler function implementing the 'base_tableAffinity' tool. It executes a SQL query against DBC.DBQLObjTbl to identify tables frequently queried together with the specified database and object, providing affinity information including query counts and timestamps.
    def handle_base_tableAffinity(conn: TeradataConnection, database_name: str, obj_name: str, *args, **kwargs):
        """
        Get tables commonly used together by database users, this is helpful to infer relationships between tables via SQLAlchemy, bind parameters if provided (prepared SQL), and return the fully rendered SQL (with literals) in metadata.
    
        Arguments:
          database_name - Database name
          object_name - table or view name
    
        Returns:
          ResponseType: formatted response with query results + metadata
        """
        logger.debug(f"Tool: handle_base_tableAffinity: Args: database_name: {database_name}, obj_name: {obj_name}")
        table_affiity_sql="""
        LOCKING ROW for ACCESS
        SELECT   TRIM(QTU2.DatabaseName)  AS "DatabaseName"
                , TRIM(QTU2.TableName)  AS "TableName"
                , COUNT(DISTINCT QTU1.QueryID) AS "QueryCount"
                , (current_timestamp - min(QTU2.CollectTimeStamp)) day(4) as "FirstQueryDaysAgo"
                , (current_timestamp - max(QTU2.CollectTimeStamp)) day(4) as "LastQueryDaysAgo"
        FROM    (
                            SELECT   objectdatabasename AS DatabaseName
                                , ObjectTableName AS TableName
                                , QueryId
                            FROM DBC.DBQLObjTbl /* for DBC */
                            WHERE Objecttype in ('Tab', 'Viw')
                            AND ObjectTableName = '{table_name}'
                            AND objectdatabasename = '{database_name}'
                            AND ObjectTableName IS NOT NULL
                            AND ObjectColumnName IS NULL
                            -- AND LogDate BETWEEN '2017-01-01' AND '2017-08-01' /* uncomment for PDCR */
                            --	AND LogDate BETWEEN current_date - 90 AND current_date - 1 /* uncomment for PDCR */
                            GROUP BY 1,2,3
                        ) AS QTU1
                        INNER JOIN
                        (
                            SELECT   objectdatabasename AS DatabaseName
                                , ObjectTableName AS TableName
                                , QueryId
                                , CollectTimeStamp
                            FROM DBC.DBQLObjTbl /* for DBC */
                            WHERE Objecttype in ('Tab', 'Viw')
                            AND ObjectTableName IS NOT NULL
                            AND ObjectColumnName IS NULL
                            GROUP BY 1,2,3, 4
                        ) AS QTU2
                        ON QTU1.QueryID=QTU2.QueryID
                        INNER JOIN DBC.DBQLogTbl QU /* uncomment for DBC */
                        -- INNER JOIN DBC.DBQLogTbl QU /* uncomment for PDCR */
                        ON QTU1.QueryID=QU.QueryID
        WHERE (TRIM(QTU2.TableName) <> TRIM(QTU1.TableName) OR  TRIM(QTU2.DatabaseName) <> TRIM(QTU1.DatabaseName))
        AND (QU.AMPCPUTime + QU.ParserCPUTime) > 0
        GROUP BY 1,2
        ORDER BY 3 DESC, 5 DESC
    --    having "QueryCount">10
        ;
    
        """
        with conn.cursor() as cur:
            rows = cur.execute(table_affiity_sql.format(table_name=obj_name, database_name=database_name))
            data = rows_to_json(cur.description, rows.fetchall())
        if len(data):
            affinity_info=f'This data contains the list of tables most commonly queried alongside object {database_name}.{obj_name}'
        else:
            affinity_info=f'Object {database_name}.{obj_name} is not often queried with any other table or queried at all, try other ways to infer its relationships.'
        metadata = {
            "tool_name": "handle_base_tableAffinity",
            "database": database_name,
            "object": obj_name,
            "table_count": len(data),
            "comment": affinity_info
        }
        logger.debug(f"Tool: handle_base_tableAffinity: metadata: {metadata}")
        return create_response(data, metadata)

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.3/5.0
Behavior3/5

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

With no annotations, the description carries the full burden of behavioral disclosure. It discloses that the tool can bind parameters (if provided) and return fully rendered SQL with literals. It also specifies the return type as 'formatted response with query results + metadata'. However, it lacks details on side effects, permissions, performance implications, or how 'commonly used together' is determined (e.g., threshold). The description partially compensates for missing annotations but leaves significant gaps.

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 concise, with the main purpose in the first sentence. It uses a bullet list for arguments and returns, which aids readability. However, there is slight redundancy: 'bind parameters if provided (prepared SQL), and return the fully rendered SQL (with literals) in metadata' could be tightened. Overall, it is efficient and front-loaded with minimal waste.

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 tool's complexity (inferring table relationships), the description covers the purpose, parameters, and return type but lacks completeness. It does not specify the output format beyond 'formatted response with query results + metadata', nor does it provide examples or clarify if data is real-time or cached. It also omits error handling, prerequisites (e.g., database must exist), and how the affinity is computed. With no output schema, more detail is needed for an agent to invoke it confidently.

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?

Schema description coverage is 0%, so the description must compensate. It adds meaning by explaining 'database_name' and 'object_name' (though the schema uses 'obj_name', not 'object_name'). However, there is a mismatch: the description says 'object_name' while the schema defines 'obj_name'. This inconsistency could confuse the agent. The description does not provide constraints, formats, or examples beyond basic identification. Given low coverage and the naming discrepancy, the added value is limited.

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 tool's purpose: 'Get tables commonly used together by database users'. It specifies the verb 'Get' and the resource 'tables commonly used together', and explains how it helps infer relationships. This distinguishes it from sibling tools like base_tableUsage or base_tablePreview, which focus on different aspects (usage statistics, row preview).

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 does not provide explicit guidance on when to use this tool versus alternatives. It says 'this is helpful to infer relationships between tables', but does not mention when not to use it or compare it to sibling tools like base_tableDDL, base_tablePreview, or base_tableUsage. No exclusion criteria or prerequisites are stated.

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