query_database
Execute SELECT queries to retrieve data from Turso-hosted LibSQL databases. Use this tool to read database information by providing SQL statements.
Instructions
Execute a SELECT query to read data from the database
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| sql | Yes | SQL query to execute |
Implementation Reference
- src/index.ts:116-128 (handler)The execute handler for the "query_database" tool. It logs the query, calls the `query` helper function with the provided SQL and database client, formats the result as JSON content, or returns an error message if execution fails.execute: async ({ sql }) => { try { logger.info(`Executing query: ${sql}`); const result = await query(sql, db); return content(JSON.stringify(result, null, 2)); } catch (error) { logger.error("Failed to execute query", error); return content( `Error executing query: ${error instanceof Error ? error.message : String(error)}`, true, ); } },
- src/index.ts:110-115 (schema)Zod input schema for the tool, defining a required non-empty string parameter 'sql' for the SQL query.parameters: z.object({ sql: z .string() .describe("SQL query to execute") .min(1, "SQL query is required"), }),
- src/index.ts:107-129 (registration)Registration of the "query_database" tool using FastMCP's server.addTool method, including name, description, input schema, and inline execute handler.server.addTool({ name: "query_database", description: "Execute a SELECT query to read data from the database", parameters: z.object({ sql: z .string() .describe("SQL query to execute") .min(1, "SQL query is required"), }), execute: async ({ sql }) => { try { logger.info(`Executing query: ${sql}`); const result = await query(sql, db); return content(JSON.stringify(result, null, 2)); } catch (error) { logger.error("Failed to execute query", error); return content( `Error executing query: ${error instanceof Error ? error.message : String(error)}`, true, ); } }, });
- src/utils.ts:86-109 (helper)Core helper function `query` that performs the actual database query execution. Validates that the query starts with SELECT, executes it using the libsql client with no args, and returns structured response with columns, rows, and count.export async function query<T = Record<string, unknown>>( sql: string, client: Client, ): Promise<{ columns: string[]; rows: T[]; rowCount: number; }> { const trimmedQuery = sql.trim().toUpperCase(); if (!trimmedQuery.startsWith("SELECT")) { throw new Error("Only SELECT queries are allowed for safety reasons"); } const result = await client.execute({ sql, args: [], }); return { columns: result.columns, rows: result.rows as T[], rowCount: result.rows.length, }; }