<?php
/**
* Execute a custom SELECT query on the database.
*
* @param string $query The string SELECT query to execute (Required, MUST be a SELECT statement, start from SELECT)
* @param array $params Optional parameters for prepared statement (default: [])
* @param int $limit Optional limit on number of rows to return (default: 100)
* @return array Query results or error message
*/
#[McpTool(name: 'execute_select_query')]
public function executeSelectQuery(string $query, array $params = [], int $limit = 100): array
{
if(!is_array($params)) {
return [
'error' => 'Params must be an array.'
];
}
try {
// Validate that query is a SELECT statement
$trimmedQuery = trim($query);
if (!preg_match('/^SELECT\s+/i', $trimmedQuery)) {
$errorMsg = 'Only SELECT queries are allowed. Query must start with SELECT.';
$this->logError('execute_select_query', $errorMsg, ['query' => $query]);
return [
'error' => $errorMsg
];
}
// Check for dangerous keywords that could be used for data modification
$dangerousPatterns = [
'/\bINTO\s+OUTFILE\b/i',
'/\bINTO\s+DUMPFILE\b/i',
'/\bLOAD_FILE\b/i',
'/\bINSERT\b/i',
'/\bUPDATE\b/i',
'/\bDELETE\b/i',
'/\bDROP\b/i',
'/\bCREATE\b/i',
'/\bALTER\b/i',
'/\bTRUNCATE\b/i',
'/\bREPLACE\b/i',
'/\bEXEC\b/i',
'/\bEXECUTE\b/i'
];
foreach ($dangerousPatterns as $pattern) {
if (preg_match($pattern, $trimmedQuery)) {
$errorMsg = 'Query contains forbidden keywords. Only safe SELECT queries are allowed.';
$this->logError('execute_select_query', $errorMsg, ['query' => $query]);
return [
'error' => $errorMsg
];
}
}
// Apply limit if not already present in query
if (!preg_match('/\bLIMIT\s+\d+/i', $trimmedQuery)) {
$trimmedQuery = rtrim($trimmedQuery, ';') . " LIMIT {$limit}";
}
// Execute query
if (!empty($params)) {
$stmt = $this->connection->prepare($trimmedQuery);
$stmt->execute($params);
} else {
$stmt = $this->connection->query($trimmedQuery);
}
$results = $stmt->fetchAll();
return [
'success' => true,
'rows' => $results,
'count' => count($results),
];
} catch (PDOException $e) {
$errorMsg = 'Query execution failed: ' . $e->getMessage();
return [
'error' => $errorMsg,
'query' => $query
];
}
}
?>
Describe the bug
I have created a simple mysql db interaction tool and it have three parameters. but vscode throw the error when try to use the tool.
error:
To Reproduce
Steps to reproduce the behavior:
Expected behavior
validated method that usable by AI agent
Additional context
If i use single parameter it worked.