Skip to main content
Glama
andyWang1688

sql-query-mcp

list_tables

List all tables and views in a database or schema using a connection ID.

Instructions

List tables and views for a resolved schema or database.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connection_idYes
schemaNo
databaseNo

Implementation Reference

  • MCP tool registration for 'list_tables' — decorates the function with @mcp.tool(), defines input params (connection_id, schema, database), and delegates to metadata.list_tables() via _run_tool.
    @mcp.tool()
    def list_tables(
        connection_id: str,
        schema: Optional[str] = None,
        database: Optional[str] = None,
    ) -> dict:
        """List tables and views for a resolved schema or database."""
    
        return _run_tool(lambda: metadata.list_tables(connection_id, schema, database))
  • MetadataService.list_tables — core handler that resolves namespace, opens connection via registry, applies statement timeout, calls adapter.list_tables(), audits success/failure, and returns the result dict.
    def list_tables(
        self,
        connection_id: str,
        schema: Optional[str] = None,
        database: Optional[str] = None,
    ) -> Dict[str, object]:
        started = time.perf_counter()
        config = None
        try:
            config = self._registry.get_connection_config(connection_id)
            namespace = resolve_namespace(config, schema=schema, database=database)
            with self._registry.connection_from_config(config) as (conn, adapter):
                _apply_statement_timeout(
                    adapter, conn, self._settings.statement_timeout_ms
                )
                tables = adapter.list_tables(conn, namespace.value)
            duration_ms = _elapsed_ms(started)
            self._audit.log(
                tool="list_tables",
                connection_id=connection_id,
                success=True,
                duration_ms=duration_ms,
                row_count=len(tables),
                extra={"engine": config.engine, namespace.field_name: namespace.value},
            )
            return {
                "connection_id": connection_id,
                "engine": config.engine,
                namespace.field_name: namespace.value,
                "tables": tables,
            }
        except Exception as exc:
            duration_ms = _elapsed_ms(started)
            sanitized = sanitize_error_message(str(exc))
            self._audit.log(
                tool="list_tables",
                connection_id=connection_id,
                success=False,
                duration_ms=duration_ms,
                error=sanitized,
                extra=_build_audit_extra(config, schema=schema, database=database),
            )
            raise QueryExecutionError(sanitized) from exc
  • resolve_namespace — helper that determines whether to use 'schema' (postgres) or 'database' (mysql/hive) based on engine config, with validation.
    def resolve_namespace(
        config: ConnectionConfig,
        *,
        schema: Optional[str] = None,
        database: Optional[str] = None,
    ) -> NamespaceSelection:
        if schema and database:
            raise SecurityError("schema 和 database 不能同时传入。")
    
        if config.engine == "postgres":
            if database:
                raise SecurityError("PostgreSQL 连接不接受 database 参数。")
            resolved = schema or config.default_schema
            if not resolved:
                raise SecurityError("PostgreSQL 连接必须显式传 schema,或在配置中设置 default_schema。")
            return NamespaceSelection(field_name="schema", value=resolved)
    
        if config.engine == "mysql":
            if schema:
                raise SecurityError("MySQL 连接不接受 schema 参数。")
            resolved = database or config.default_database
            if not resolved:
                raise SecurityError("MySQL 连接必须显式传 database,或在配置中设置 default_database。")
            return NamespaceSelection(field_name="database", value=resolved)
    
        if config.engine == "hive":
            if schema:
                raise SecurityError("Hive 连接不接受 schema 参数。")
            resolved = database or config.default_database
            if not resolved:
                raise SecurityError("Hive 连接必须显式传 database,或在配置中设置 default_database。")
            return NamespaceSelection(field_name="database", value=resolved)
    
        raise SecurityError(f"未知 engine: {config.engine}")
  • PostgresAdapter.list_tables — executes SQL query on information_schema.tables filtered by schema, returns rows with schema, table_name, table_type.
    def list_tables(self, conn: object, schema: str):
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT table_schema AS schema, table_name, table_type
                FROM information_schema.tables
                WHERE table_schema = %s
                ORDER BY table_name
                """,
                (schema,),
            )
            return cur.fetchall()
  • MySQLAdapter.list_tables — executes SQL query on information_schema.tables filtered by database, returns rows with database_name, table_name, table_type.
    def list_tables(self, conn: object, database: str):
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT table_schema AS database_name, table_name, table_type
                FROM information_schema.tables
                WHERE table_schema = %s
                ORDER BY table_name
                """,
                (database,),
            )
            return cur.fetchall()
Behavior2/5

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

No annotations are provided, so the description must cover behavioral traits. It does not disclose idempotency, side effects, or return format. The agent lacks safety information for this read-like operation.

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 a single sentence, concise and front-loaded with the action. It could add detail without losing brevity, but efficiency is maintained.

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

Completeness2/5

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

With no output schema and no behavioral hints, the description fails to inform about return values, pagination, or limitations. Given moderate complexity (3 params, 1 required), this is insufficient.

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

Parameters1/5

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

Schema description coverage is 0%. The description does not explain any parameter (connection_id, schema, database) beyond vague reference to 'resolved schema or database'. No added meaning beyond the 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 action (list) and resource (tables and views) for a resolved schema or database, distinguishing it from sibling tools like describe_table or list_schemas.

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 when to use (for a schema or database) but provides no explicit exclusions, alternatives, or prerequisites (e.g., needing a connection). The context of sibling tools helps, but guidance is minimal.

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/andyWang1688/sql-query-mcp'

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