|
| 1 | +import { tool } from 'ai'; |
| 2 | +import { z } from 'zod'; |
| 3 | +import { log } from '../../config/logging.js'; |
| 4 | +import { getSystemClient, getPoolStats } from '../../db/poolManager.js'; |
| 5 | +import { resolveIsAdmin } from '../../utils/adminCheck.js'; |
| 6 | +import { ERRORS, formatZodError } from './errors.js'; |
| 7 | +import { formatSuccess } from './formatting.js'; |
| 8 | + |
| 9 | +const inspectSchemaInput = z.object({ |
| 10 | + table: z.string().min(1).describe('Name of the database table to inspect'), |
| 11 | +}); |
| 12 | + |
| 13 | +const emptyInput = z.object({}); |
| 14 | + |
| 15 | +// Defense-in-depth gate re-checked on every call (the route already gates |
| 16 | +// registration). Re-verifies the env flag and admin role via the DB lookup, |
| 17 | +// since the handler closes over only a userId. Returns an ERRORS.* string when |
| 18 | +// denied, null when allowed. |
| 19 | +async function assertDevAccess(userId: string): Promise<string | null> { |
| 20 | + if (process.env.DEV_TOOLS_ENABLED !== 'true') { |
| 21 | + return ERRORS.FORBIDDEN('Dev tools are disabled'); |
| 22 | + } |
| 23 | + if (!(await resolveIsAdmin(undefined, userId))) { |
| 24 | + return ERRORS.FORBIDDEN('Admin access required'); |
| 25 | + } |
| 26 | + return null; |
| 27 | +} |
| 28 | + |
| 29 | +// The 4 admin/debug tools, kept out of buildChatbotTools so the chatbot never |
| 30 | +// sees them; registered only for an admin when DEV_TOOLS_ENABLED=true. Each |
| 31 | +// execute() returns a plain string — registerToolMap does the MCP wrapping. |
| 32 | +export function buildDevTools(userId: string) { |
| 33 | + return { |
| 34 | + sparky_inspect_schema: tool({ |
| 35 | + description: |
| 36 | + 'Inspect the database schema to understand available tables and columns. Requires admin access and DEV_TOOLS_ENABLED=true.', |
| 37 | + inputSchema: inspectSchemaInput, |
| 38 | + execute: async (rawArgs) => { |
| 39 | + const denied = await assertDevAccess(userId); |
| 40 | + if (denied) return denied; |
| 41 | + |
| 42 | + const parsed = inspectSchemaInput.safeParse(rawArgs); |
| 43 | + if (!parsed.success) { |
| 44 | + return formatZodError(parsed.error); |
| 45 | + } |
| 46 | + const { table } = parsed.data; |
| 47 | + |
| 48 | + const client = await getSystemClient(); |
| 49 | + try { |
| 50 | + let schema = 'public'; |
| 51 | + let tableName = table; |
| 52 | + if (table.includes('.')) { |
| 53 | + const parts = table.split('.'); |
| 54 | + schema = parts[0]; |
| 55 | + tableName = parts[1]; |
| 56 | + } |
| 57 | + |
| 58 | + const result = await client.query( |
| 59 | + `SELECT column_name, data_type, is_nullable, column_default, table_schema |
| 60 | + FROM information_schema.columns |
| 61 | + WHERE table_name = $1 AND table_schema = $2 |
| 62 | + ORDER BY ordinal_position`, |
| 63 | + [tableName, schema] |
| 64 | + ); |
| 65 | + |
| 66 | + if (result.rows.length === 0) { |
| 67 | + return ERRORS.NOT_FOUND('Table', table); |
| 68 | + } |
| 69 | + |
| 70 | + const columns = result.rows.map((row: any) => ({ |
| 71 | + column: row.column_name, |
| 72 | + type: row.data_type, |
| 73 | + nullable: row.is_nullable === 'YES', |
| 74 | + default: row.column_default, |
| 75 | + })); |
| 76 | + |
| 77 | + return formatSuccess( |
| 78 | + { table, columns, column_count: columns.length }, |
| 79 | + `Schema: ${table}` |
| 80 | + ); |
| 81 | + } catch (error) { |
| 82 | + log('error', '[Dev Tool] inspectSchema error:', error); |
| 83 | + return ERRORS.DB_ERROR(); |
| 84 | + } finally { |
| 85 | + client.release(); |
| 86 | + } |
| 87 | + }, |
| 88 | + }), |
| 89 | + |
| 90 | + sparky_get_user_info: tool({ |
| 91 | + description: |
| 92 | + 'Get information about the current authenticated user. Requires admin access and DEV_TOOLS_ENABLED=true.', |
| 93 | + inputSchema: emptyInput, |
| 94 | + execute: async () => { |
| 95 | + const denied = await assertDevAccess(userId); |
| 96 | + if (denied) return denied; |
| 97 | + |
| 98 | + const client = await getSystemClient(); |
| 99 | + try { |
| 100 | + const result = await client.query( |
| 101 | + `SELECT id, name, email, role, created_at, updated_at |
| 102 | + FROM "user" |
| 103 | + WHERE id = $1`, |
| 104 | + [userId] |
| 105 | + ); |
| 106 | + |
| 107 | + if (result.rows.length === 0) { |
| 108 | + return ERRORS.NOT_FOUND('User', userId); |
| 109 | + } |
| 110 | + |
| 111 | + const user = result.rows[0]; |
| 112 | + return formatSuccess( |
| 113 | + { user_id: userId, ...user }, |
| 114 | + 'Current User Info' |
| 115 | + ); |
| 116 | + } catch (error) { |
| 117 | + log('error', '[Dev Tool] getUserInfo error:', error); |
| 118 | + return ERRORS.DB_ERROR(); |
| 119 | + } finally { |
| 120 | + client.release(); |
| 121 | + } |
| 122 | + }, |
| 123 | + }), |
| 124 | + |
| 125 | + sparky_get_db_stats: tool({ |
| 126 | + description: |
| 127 | + 'Get current database connection pool statistics. Requires admin access and DEV_TOOLS_ENABLED=true.', |
| 128 | + inputSchema: emptyInput, |
| 129 | + execute: async () => { |
| 130 | + const denied = await assertDevAccess(userId); |
| 131 | + if (denied) return denied; |
| 132 | + |
| 133 | + try { |
| 134 | + return formatSuccess(getPoolStats(), 'Database Pool Stats'); |
| 135 | + } catch (error) { |
| 136 | + log('error', '[Dev Tool] getDbStats error:', error); |
| 137 | + return ERRORS.DB_ERROR(); |
| 138 | + } |
| 139 | + }, |
| 140 | + }), |
| 141 | + |
| 142 | + sparky_run_project_tests: tool({ |
| 143 | + description: |
| 144 | + "Run the project's test suite to verify nutrition and fitness logic. Requires admin access and DEV_TOOLS_ENABLED=true.", |
| 145 | + inputSchema: emptyInput, |
| 146 | + execute: async () => { |
| 147 | + const denied = await assertDevAccess(userId); |
| 148 | + if (denied) return denied; |
| 149 | + |
| 150 | + return formatSuccess( |
| 151 | + { |
| 152 | + status: 'scheduled', |
| 153 | + message: |
| 154 | + 'Tests would be executed via child_process in a real environment.', |
| 155 | + }, |
| 156 | + 'Project Tests' |
| 157 | + ); |
| 158 | + }, |
| 159 | + }), |
| 160 | + }; |
| 161 | +} |
0 commit comments