query_data
Execute SQL SELECT queries on an SQLite database via the MCP server. Retrieve specific data with optional row limits for efficient results handling.
Instructions
Execute a SELECT query on the database
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | Maximum number of rows to return | |
| query | Yes | SQL SELECT query to execute |
Implementation Reference
- src/index.ts:289-340 (handler)The main handler function for the 'query_data' tool. Validates that the query is a SELECT statement, applies an optional LIMIT, executes the query using better-sqlite3's .all(), formats the results as a pipe-separated table, and returns as CallToolResult.private async queryData(args: { query: string; limit?: number }): Promise<CallToolResult> { if (!this.db) { throw new Error("No database connected. Use connect_database first."); } try { // Ensure it's a SELECT query const trimmedQuery = args.query.trim().toLowerCase(); if (!trimmedQuery.startsWith("select")) { throw new Error("Only SELECT queries are allowed with query_data. Use execute_query for other operations."); } const limit = args.limit || 100; const queryWithLimit = args.query.toLowerCase().includes("limit") ? args.query : `${args.query} LIMIT ${limit}`; const results = this.db.prepare(queryWithLimit).all(); if (results.length === 0) { return { content: [ { type: "text", text: "Query executed successfully. No rows returned.", } satisfies TextContent, ], }; } // Format results as a table const headers = Object.keys(results[0] as Record<string, unknown>); const rows = results.map((row) => headers.map(header => String((row as Record<string, unknown>)[header] ?? "NULL")).join(" | ") ); const headerRow = headers.join(" | "); const separator = headers.map(h => "-".repeat(h.length)).join("-|-"); const table = [headerRow, separator, ...rows].join("\n"); return { content: [ { type: "text", text: `Query results (${results.length} rows):\n\n${table}`, } satisfies TextContent, ], }; } catch (error) { throw new Error(`Query failed: ${error instanceof Error ? error.message : String(error)}`); } }
- src/index.ts:100-118 (schema)The input schema definition for the 'query_data' tool, specifying the expected arguments: query (string, required) and optional limit (number).{ name: "query_data", description: "Execute a SELECT query on the database", inputSchema: { type: "object", properties: { query: { type: "string", description: "SQL SELECT query to execute", }, limit: { type: "number", description: "Maximum number of rows to return", default: 100, }, }, required: ["query"], }, },
- src/index.ts:171-173 (registration)The switch case in the CallToolRequest handler that registers and dispatches 'query_data' tool calls to the queryData method.case "query_data": return await this.queryData(args as { query: string; limit?: number });