SQL Injection in Claude MCP Skills: ORM Escape Hatches, ORDER BY Injection, and Second-Order Attacks
Using Prisma or Sequelize in your MCP skill does not make you immune to SQL injection. ORMs provide safe defaults, but every ORM ships escape hatches — raw query APIs designed for edge cases — and developers reach for them more often than they should. This post documents four mcp skill sql injection orm patterns, from classic string concatenation to the subtle second-order attack that bites teams months after the vulnerable code was written.
Contents
Why ORMs don't eliminate SQL injection
The conventional wisdom — "use an ORM and you won't get SQL injection" — is directionally correct but dangerously incomplete for MCP skill development. ORMs like Prisma and Sequelize are safe by default: their standard CRUD methods (findMany, create, update, destroy) use parameterized queries internally. The database driver receives the SQL template and the data values as separate arguments, and the DBMS engine never sees user input mixed into the query string. That is the correct model.
The problem is escape hatches. Every production ORM exposes at least one raw query API because there are legitimate things you cannot express through the ORM's abstraction layer: complex window functions, recursive CTEs, database-specific syntax, full-text search configurations, and — the case that bites most MCP skills — dynamic ORDER BY columns. When a developer reaches for Prisma.$queryRaw, Sequelize.literal(), or the pg client's query() directly, they step outside the ORM's safety net entirely. The parameterization guarantees disappear, and all the SQL injection risk returns.
MCP skills are particularly prone to this pattern because they frequently need to expose flexible query interfaces: "show me audits sorted by severity", "search skills by repository URL", "filter results by tag". These features require dynamic SQL fragments that the ORM's type-safe API cannot express, and so developers resort to raw queries. When they do, they often carry over the template literal habit from the ORM API — and that is where the injection happens.
SA-SKL-SQLINJ in scope: SQLINJ-001 (string concatenation), SQLINJ-002 (ORM raw query escape hatch), SQLINJ-003 (ORDER BY injection), SQLINJ-004 (second-order injection). All four patterns are detected by SkillAudit's static analysis rules during skill audits. See the SA-SKL-SQLINJ reference page for the full detection rule catalogue.
SQLINJ-001 — Classic string concatenation in raw queries
The most straightforward form of SQL injection in MCP skills occurs when a developer uses a template literal or string concatenation to build a SQL query that includes user-supplied input. Despite being a well-understood vulnerability, it appears repeatedly in skill codebases because the template literal syntax feels natural and the ORM's raw query API accepts any string without validation.
In the context of a SkillAudit MCP skill, a typical pattern is a tool that takes a repository URL from the Claude model's tool call arguments and queries the audit database for results. The developer writes a quick raw query to get it working and forgets to parameterize it before shipping.
// VULNERABLE — SQLINJ-001: template literal builds query with user input
import { db } from '../db';
export async function getAuditsByRepo(repoUrl: string) {
// Attacker supplies: ' OR '1'='1
// Full query becomes: SELECT * FROM audits WHERE repo = '' OR '1'='1'
// Returns all audits across all organizations
const rows = await db.query(
`SELECT * FROM audits WHERE repo = '${repoUrl}'`
);
return rows;
}
// FIXED — SQLINJ-001: parameterized query separates SQL from data
import { db } from '../db';
export async function getAuditsByRepo(repoUrl: string) {
// The DB driver sends the query template and the value separately
// No amount of SQL syntax in repoUrl can escape the parameter binding
const rows = await db.query(
`SELECT * FROM audits WHERE repo = $1`,
[repoUrl]
);
return rows;
}
The fix is always the same: replace the interpolated value with a positional parameter ($1 for PostgreSQL, ? for MySQL/SQLite) and pass the value in the parameters array. The database driver handles quoting, escaping, and type binding — your code never constructs a SQL string that includes user data.
Prisma equivalent: If you use Prisma's standard API (prisma.audits.findMany({ where: { repo: repoUrl } })), parameterization is automatic. SQLINJ-001 only appears when you bypass this in favour of a raw query. If you find yourself writing raw queries for simple WHERE filters, that is a signal to use the ORM's typed API instead.
SQLINJ-002 — ORM raw query escape hatch with user input interpolation
Both Prisma and Sequelize expose raw query APIs that many developers use incorrectly. The unsafe pattern looks almost identical to the safe one — the difference is whether user input is interpolated into the template string or passed as a bound parameter. This subtlety makes SQLINJ-002 harder to spot in code review than classic string concatenation.
Prisma's $queryRaw escape hatch: Prisma's raw query API has two call signatures. When called as a tagged template literal (prisma.$queryRaw`...${value}...`), Prisma automatically extracts the values and passes them as parameters — this is safe. When called as a regular function (prisma.$queryRaw(`...${value}...`)), the string is fully constructed before Prisma sees it, and the interpolated value is part of the SQL string — this is vulnerable. The two syntaxes look nearly identical, and developers who learned Prisma from examples that use the tagged template form sometimes copy the function-call form from Stack Overflow answers without realising the security difference.
// VULNERABLE — Prisma $queryRaw called as function (string fully assembled before Prisma sees it)
import { prisma } from '../prisma';
export async function searchAudits(skillName: string) {
// Function call syntax — skillName is already in the string
// Attacker: "'; DROP TABLE audits; --"
const results = await prisma.$queryRaw(
`SELECT * FROM audits WHERE skill_name ILIKE '%${skillName}%'`
);
return results;
}
// FIXED — Prisma $queryRaw as tagged template literal (Prisma parameterizes automatically)
import { prisma } from '../prisma';
import { Prisma } from '@prisma/client';
export async function searchAudits(skillName: string) {
// Tagged template literal syntax — Prisma extracts the value as a parameter
const pattern = `%${skillName}%`;
const results = await prisma.$queryRaw<AuditRow[]>`
SELECT * FROM audits WHERE skill_name ILIKE ${pattern}
`;
return results;
}
Sequelize's literal() abuse: Sequelize's literal() function is designed to pass a raw SQL fragment to the query builder without escaping. It exists for cases like literal('NOW()') or literal('CURRENT_DATE') where you need a SQL expression, not a value. When developers use it to pass user input — where: { name: literal(`'${userInput}'`) } — the input is treated as raw SQL, completely bypassing Sequelize's parameterization.
// VULNERABLE — Sequelize literal() wraps user input in raw SQL
import { Op, literal } from 'sequelize';
export async function getSkillsByTag(tag: string) {
// literal() tells Sequelize: treat this as raw SQL, do not escape
// Attacker: "' OR 1=1 --"
return Skill.findAll({
where: literal(`tags @> ARRAY['${tag}']::text[]`)
});
}
// FIXED — Sequelize replacements object for parameterized raw query
import { QueryTypes } from 'sequelize';
import { sequelize } from '../sequelize';
export async function getSkillsByTag(tag: string) {
// Use replacements: Sequelize substitutes :tag with a properly escaped value
return sequelize.query(
`SELECT * FROM skills WHERE tags @> ARRAY[:tag]::text[]`,
{
replacements: { tag },
type: QueryTypes.SELECT,
}
);
}
SQLINJ-003 — ORDER BY clause injection
ORDER BY injection is the most underappreciated SQL injection vector in MCP skill development, because it is a problem that parameterized queries cannot solve. SQL parameter binding works by substituting a placeholder with a quoted string or numeric value — but column names and sort directions in ORDER BY are SQL identifiers, not values. If you write ORDER BY $1, the database treats $1 as a string value, not as a column name, and the query either errors or returns results sorted by a literal string rather than a column. This forces developers to interpolate the sort column directly into the query string — which creates the injection surface.
The attack is not limited to column enumeration. Because the ORDER BY clause can contain expressions, an attacker can inject 1 UNION SELECT username, password_hash, null FROM users-- as the sort parameter, turning a benign list endpoint into a data exfiltration vector. Even without a UNION attack, injecting (SELECT CASE WHEN (1=1) THEN created_at ELSE id END) allows boolean-based blind SQL injection through the sort parameter alone.
// VULNERABLE — SQLINJ-003: sort column interpolated directly into ORDER BY
import { db } from '../db';
export async function listAudits(orgId: string, sortColumn: string, sortDir: string) {
// Attacker supplies sortColumn: "1 UNION SELECT username,password_hash,null FROM users--"
const rows = await db.query(
`SELECT id, skill_name, severity, created_at
FROM audits
WHERE org_id = $1
ORDER BY ${sortColumn} ${sortDir}`,
[orgId]
);
return rows;
}
// FIXED — SQLINJ-003: explicit column allowlist for ORDER BY
import { db } from '../db';
type SortDir = 'ASC' | 'DESC';
const ALLOWED_SORT_COLUMNS = new Set([
'id', 'skill_name', 'severity', 'created_at', 'updated_at',
]);
const ALLOWED_SORT_DIRS = new Set<string>(['ASC', 'DESC', 'asc', 'desc']);
export async function listAudits(orgId: string, sortColumn: string, sortDir: string) {
// Reject anything not in the explicit allowlist
if (!ALLOWED_SORT_COLUMNS.has(sortColumn)) {
throw new Error(`Invalid sort column: ${sortColumn}`);
}
if (!ALLOWED_SORT_DIRS.has(sortDir)) {
throw new Error(`Invalid sort direction: ${sortDir}`);
}
// Safe to interpolate because we validated against an explicit Set
const dir: SortDir = sortDir.toUpperCase() as SortDir;
const rows = await db.query(
`SELECT id, skill_name, severity, created_at
FROM audits
WHERE org_id = $1
ORDER BY ${sortColumn} ${dir}`,
[orgId]
);
return rows;
}
The key insight is that the allowlist must be a Set or equivalent structure containing only the exact column names present in the table, not a regex. A regex like /^[a-z_]+$/ validates that the input looks like a column name but does not verify it matches an actual column — an attacker can supply a valid-looking identifier that happens to be a SQL keyword or a column from a different table reachable via a UNION.
Never validate ORDER BY input with a regex alone. /^[a-z_]+$/ blocks obvious payloads but allows inputs like null, true, case, or single-word SQL keywords that can still alter query semantics. Use an explicit Set of known-safe column names from the specific table being queried.
SQLINJ-004 — Second-order SQL injection from stored values
Second-order SQL injection is the hardest of the four patterns to catch because the vulnerable code and the injection point are separated in time and often in codebase location. The sequence is: (1) user supplies malicious input, (2) the input is stored safely using a parameterized query, (3) the stored value is later read back from the database, (4) the retrieved value is used unsafely in a subsequent raw query. The developer who wrote step 4 may have reasoned "this value came from our own database, so it must be safe" — but database origin provides no safety guarantee if the original storage step accepted arbitrary user input.
In a SkillAudit MCP skill, a typical scenario is: a user registers with a username containing SQL payload (admin'--), which is stored safely in step (2). Later, an internal reporting job reads the username from the database and builds an audit log query using that username without re-parameterizing it. The reporting job runs with elevated DB privileges and the attacker's payload executes in that context — potentially days after the malicious registration.
// VULNERABLE — SQLINJ-004: value from DB used unsafely in a later raw query
// Step 1: safe storage (parameterized — looks fine)
export async function registerUser(username: string, email: string) {
await db.query(
`INSERT INTO users (username, email) VALUES ($1, $2)`,
[username, email] // Safe: parameterized
);
}
// Step 2: later retrieval and unsafe use in audit log query
export async function logAuditActivity(userId: string, action: string) {
// Fetch username from DB — developer assumes DB values are safe
const user = await db.query(`SELECT username FROM users WHERE id = $1`, [userId]);
const username = user.rows[0].username;
// VULNERABLE: username came from DB but was originally user-supplied
// If username = "admin'--", this query is broken or exploited
await db.query(
`INSERT INTO audit_log (actor, action, logged_at)
VALUES ('${username}', '${action}', NOW())`
);
}
// FIXED — SQLINJ-004: parameterize all values regardless of source
export async function logAuditActivity(userId: string, action: string) {
const user = await db.query(
`SELECT username FROM users WHERE id = $1`,
[userId]
);
const username = user.rows[0].username;
// Parameterize even values that originated from your own database
// The source of a value is never a safety guarantee
await db.query(
`INSERT INTO audit_log (actor, action, logged_at)
VALUES ($1, $2, NOW())`,
[username, action]
);
}
The rule is simple: parameterize every value interpolated into a SQL string, regardless of where that value came from. It does not matter if the value was read from your own database, computed by your own code, or came from a trusted internal service. Parameterization is not about distrust — it is about maintaining a structural separation between SQL logic and data values that the database engine enforces at execution time.
Complete production implementation combining all fixes
The following TypeScript module shows how all four SA-SKL-SQLINJ patterns are addressed together in a realistic MCP skill query handler. It combines parameterized queries, the Prisma tagged template syntax, an ORDER BY allowlist, and consistent parameterization of all values including those read from the database.
// audit-queries.ts — production implementation with all SQLINJ fixes applied
import { prisma } from './prisma';
import { db } from './db';
import { Prisma } from '@prisma/client';
// --- SQLINJ-003 fix: allowlist for ORDER BY ---
const AUDIT_SORT_COLUMNS = new Set([
'created_at', 'updated_at', 'severity', 'skill_name', 'id',
]);
const SORT_DIRECTIONS = new Set(['ASC', 'DESC']);
type AuditSortColumn = 'created_at' | 'updated_at' | 'severity' | 'skill_name' | 'id';
type SortDirection = 'ASC' | 'DESC';
function validateSortColumn(col: string): AuditSortColumn {
if (!AUDIT_SORT_COLUMNS.has(col)) {
throw new Error(`Invalid sort column: "${col}". Allowed: ${[...AUDIT_SORT_COLUMNS].join(', ')}`);
}
return col as AuditSortColumn;
}
function validateSortDirection(dir: string): SortDirection {
const upper = dir.toUpperCase();
if (!SORT_DIRECTIONS.has(upper)) {
throw new Error(`Invalid sort direction: "${dir}". Use ASC or DESC.`);
}
return upper as SortDirection;
}
// --- SQLINJ-001 + SQLINJ-003 fix: parameterized query with validated ORDER BY ---
export async function listAudits(
orgId: string,
repoUrl: string | null,
sortCol: string,
sortDir: string
) {
const col = validateSortColumn(sortCol);
const dir = validateSortDirection(sortDir);
// repoUrl is a parameterized value ($2); col and dir are allowlist-validated identifiers
const rows = await db.query(
`SELECT id, skill_name, severity, repo_url, created_at
FROM audits
WHERE org_id = $1
AND ($2::text IS NULL OR repo_url = $2)
ORDER BY ${col} ${dir}`,
[orgId, repoUrl]
);
return rows.rows;
}
// --- SQLINJ-002 fix: Prisma $queryRaw as tagged template literal ---
export async function searchAuditsBySkillName(skillName: string) {
const pattern = `%${skillName}%`;
// Tagged template: Prisma parameterizes ${pattern} automatically
return prisma.$queryRaw<{ id: string; skill_name: string; severity: string }[]>`
SELECT id, skill_name, severity
FROM audits
WHERE skill_name ILIKE ${pattern}
LIMIT 50
`;
}
// --- SQLINJ-004 fix: parameterize values from DB, not just from request input ---
export async function logAuditActivity(userId: string, auditId: string, action: string) {
// Fetch display name from DB
const userResult = await db.query(
`SELECT display_name FROM users WHERE id = $1`,
[userId]
);
const displayName = userResult.rows[0]?.display_name ?? 'unknown';
// Parameterize displayName even though it came from our own DB
await db.query(
`INSERT INTO audit_activity_log (user_id, audit_id, actor_name, action, occurred_at)
VALUES ($1, $2, $3, $4, NOW())`,
[userId, auditId, displayName, action]
);
}
Detection summary
SkillAudit's static analysis rules detect all four SA-SKL-SQLINJ patterns during skill audits. The table below summarises what each rule flags and what the minimum fix is. For the full rule specifications, see the SA-SKL-SQLINJ reference page. For related injection vulnerabilities, see SA-SKL-NOSQLINJ (NoSQL injection) and SA-SKL-JSONSCHEMA (input validation bypass).
| Pattern | Severity | What SkillAudit flags | Minimum fix |
|---|---|---|---|
| SQLINJ-001 String concatenation in raw query |
HIGH | Template literals or + concatenation in db.query() / pg.query() first argument where any part of the string derives from function parameters or request body fields |
Replace interpolated values with positional parameters ($1, ?) and pass values array |
| SQLINJ-002 ORM raw query escape hatch |
HIGH | prisma.$queryRaw( called as a function (not tagged template) with user input; Sequelize.literal() or literal() wrapping a template literal containing a variable |
Prisma: use tagged template prisma.$queryRaw`...${val}...`; Sequelize: use replacements object in sequelize.query() |
| SQLINJ-003 ORDER BY clause injection |
HIGH | Template literal interpolation in ORDER BY ${variable} where variable traces to a request parameter, without an intervening Set-based allowlist lookup that throws on mismatch |
Define a Set of allowed column names and throw if the input is not a member; never use regex-only validation for ORDER BY |
| SQLINJ-004 Second-order injection from stored value |
CRITICAL | Variable assigned from a DB query result (rows[0].field, user.name, etc.) subsequently interpolated into a raw SQL string without parameterization in the same or a downstream function |
Parameterize all values in raw queries regardless of source — DB-originated values are not inherently safe |
Practical audit checklist: Search your MCP skill codebase for every occurrence of $queryRaw( (function call, not tagged), literal(, ORDER BY ${, and any raw query(` call that uses a template literal. Each of these is a potential SA-SKL-SQLINJ finding. SkillAudit's automated scan covers all four patterns and reports findings with line-level evidence in the audit report.
SQL injection remains one of the top findings in SkillAudit audits despite ORMs being the standard data layer in modern MCP skills. The root cause is not ignorance of parameterized queries — most developers know the rule — but the ORM's own escape hatches making it easy to bypass parameterization in exactly the places where flexibility is needed. Understanding which ORM APIs are safe by default and which require explicit care is the most important thing you can do to eliminate this vulnerability class from your skill.