list_tables.ts•1.64 kB
import { z } from "zod";
import * as pg from "pg";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export interface ToolProps {
pool: pg.Pool;
}
export function ListTables(server: McpServer, props: ToolProps) {
server.tool(
"list_tables",
"List all tables in the specified schemas",
{
schemas: z
.array(z.string())
.optional()
.describe("List of schema names to include. Defaults to ['public']"),
},
async ({ schemas = ["public"] }) => {
if (!props.pool) {
throw new Error("Database pool not initialized");
}
const client = await props.pool.connect();
try {
const schemaList = schemas.map((_, i) => `$${i + 1}`).join(",");
const query = `
SELECT
schemaname as schema_name,
tablename as table_name,
tableowner as table_owner,
hasindexes as has_indexes,
hasrules as has_rules,
hastriggers as has_triggers,
rowsecurity as row_security
FROM pg_tables
WHERE schemaname = ANY($1::text[])
ORDER BY schemaname, tablename;
`;
const result = await client.query(query, [schemas]);
return {
content: [
{
type: "text",
text: JSON.stringify(
{
schemas: schemas,
tables: result.rows,
count: result.rows.length,
},
null,
2,
),
},
],
};
} catch (error) {
throw new Error(
`Failed to list tables: ${error instanceof Error ? error.message : "Unknown error"}`,
);
} finally {
client.release();
}
},
);
}