n1scan
Acts as a PostgreSQL wire-protocol proxy and log analyzer: forwards queries unchanged, detects N+1 query loops, proves parent-child query relationships, runs read-only EXPLAIN for index suggestions, and parses PostgreSQL logs such as csvlog and jsonlog.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
n1scan
Find N+1 queries by watching your app's PostgreSQL traffic (or the server logs you already have), prove which query caused each loop, and fail CI only when a new one appears. One binary, no code changes, any language or ORM.
n1scan is a small local proxy. Point your app at it instead of at Postgres; it forwards every byte unchanged and tells you when the same query shape runs again and again with different values (the N+1 pattern), which query ran just before the loop, and, from a read-only EXPLAIN, which index would make it cheap. Query values never appear in its output unless you ask for them.

On a real app (the Prisma example, PostgreSQL 18):
$ n1scan run -- npm run demo
N+1 03:56:27 conn 1: same query 5+ times in 50.0ms
SELECT COUNT(*) AS "_count$_all" FROM (SELECT "public"."posts"."id" FROM "public"."posts" WHERE "public"."posts"."author_id" = $1 OFFSET $2) AS "sub"
after: SELECT "public"."authors"."id", "public"."authors"."name" FROM "public"."authors" WHERE ?=? ORDER BY "public"."authors"."id" ASC LIMIT $1 OFFSET $2
parent proven: 5/5 values of $1 came from its column "id", in row order
values: 5 distinct so far (hidden; --show-values prints them)
index: CREATE INDEX CONCURRENTLY ON public.posts (author_id);
sequential scan on public.posts (~200000 rows) filtering on author_id, run once per repetition; the index also adds a little work to every write on the table
slow: 50 authors in 738 ms
n1scan summary: 51 queries on 1 connection in 2.40s
1. N+1 50 executions in 1 burst(s), largest 50, 412.6ms spent
select count(*) as "_count$_all" from (select "public"."posts"."id" from "public"."posts" where "public"."posts"."author_id" = ? offset ?) as "sub"
after: SELECT "public"."authors"."id", "public"."authors"."name" FROM "public"."authors" WHERE ?=? ORDER BY "public"."authors"."id" ASC LIMIT $1 OFFSET $2
parent proven: 50/50 values of $1 came from its column "id", in row order
index: CREATE INDEX CONCURRENTLY ON public.posts (author_id);after: is the "1" of the N+1: the query whose rows your code iterates over. n1scan keeps salted hashes of the first rows each query returns and checks whether the loop's parameters came out of them, so when it can, it proves the link instead of guessing: parent proven: 50/50 values of $1 came from its column "id", in row order. That also works when the parent ran on another connection of a pool.
The loop is a prisma.post.count() per author that looks harmless in code. The fixed version (include: { _count: … }) is one query, and n1scan diff confirms it:
$ n1scan run --report before.json -- npm run demo
$ n1scan run --report after.json -- npm run demo:fast
$ n1scan diff --allow-different-command before.json after.json
n1scan diff: 0 new, 0 worse, 1 fixed, 0 unchanged; queries 51 -> 1
FIXED N+1 50 -> 0 executions select count(*) as "_count$_all" from (select ...Why
N+1 queries are individually fast, so slow-query logs and auto_explain never show them on their own (with every statement logged, n1scan logs finds them there: see below). ORM-specific detectors exist (Bullet for Rails, nplusone for Django, debug toolbars), but each one covers one framework and runs inside your process. APM tools catch them in production, after your users did.
n1scan sits on the wire, so it works the same for Prisma, Drizzle, SQLAlchemy, Django, pgx, psycopg, raw SQL, or anything else that speaks the PostgreSQL protocol. In CI it compares each run with a baseline, so a project that already has N+1 queries can adopt it today and only fail on the ones a pull request adds.
Related MCP server: DevBoost MCP Server
Try it in ten seconds
npx n1scan demo # or: uvx n1scan demo, or n1scan demo with a downloaded binaryA small app with an N+1 runs against a simulated PostgreSQL inside the binary (nothing to install, no network): you see the finding, the proven parent query, then the fixed version and the before/after numbers.
Install
Download a binary for Linux, macOS or Windows from the Releases page.
npx n1scanoruvx n1scan(thin launchers that download the release binary and check its SHA-256).With Go 1.25+:
go install github.com/alex00010/n1scan/cmd/n1scan@latest
Use
Wrap a command (easiest)
export DATABASE_URL=postgres://me:secret@localhost:5432/app
n1scan run -- npm test # or: pytest, go test ./..., rails test, ...run starts the proxy, rewrites $DATABASE_URL for the child process so it connects through n1scan, and prints a report when the command exits. Use --env NAME if your app reads another variable. The same connection string is used for the read-only EXPLAIN behind index suggestions. If the command never connects through the proxy, n1scan says so instead of reporting a clean run.
In CI: the GitHub Action
name: n1scan
on: [pull_request]
permissions:
contents: read
pull-requests: write # for the PR comment; without it the report goes to the job summary
jobs:
n1scan:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:18
env:
POSTGRES_PASSWORD: postgres
ports: ["5432:5432"]
options: >-
--health-cmd pg_isready --health-interval 2s --health-timeout 5s --health-retries 20
env:
DATABASE_URL: postgres://postgres:postgres@127.0.0.1:5432/app?sslmode=disable
steps:
- uses: actions/checkout@v4
- run: npm ci
- uses: alex00010/n1scan@v0.6.0
with:
command: npm test
baseline: n1scan.baseline.jsonThe action downloads the release binary for the runner (Linux, macOS or Windows), checks it against the release's checksums.txt, runs the command through n1scan, writes the report to the job summary and keeps one comment on the pull request up to date. On the first run the baseline file does not exist, so it is written from that run: commit it, and from then on only findings that are not in it fail the job. This repository runs the action on its own pull requests (workflow), so any open pull request shows the comment it leaves. Inputs: command, baseline, env, fail-on, fail-kinds, args, comment, version, binary.
In CI: any other system
# fail on any N+1
n1scan run --ci -- npm test
# accept today's findings once (commit the file)
n1scan run --ci --baseline n1scan.baseline.json --update-baseline -- npm test
# from then on, fail only on new ones; n1scan.md is ready for a PR comment
n1scan run --ci --baseline n1scan.baseline.json --report n1scan.md -- npm testExit status: 0 clean; 1 an N+1 was found (with --baseline, one that is not in the baseline); 2 bad usage, or with --ci the command never connected through n1scan, so nothing was measured. If the command itself fails, its own exit status is returned unchanged.
Findings have a stable id derived from the normalised query, so a baseline survives reruns, data changes and refactors that do not change the SQL. --fail-on worse also fails when a known N+1's largest burst grows by more than --allow-growth percent (default 20). Only n+1 findings fail by default; --fail-kinds n+1,batchable adds write loops.
Query budgets a coding agent cannot quietly raise
Query-count assertions in tests (assertNumQueries(4)) live next to the code, so a change, or a coding agent trying to get CI green, can bump the number in the same commit. Put the limits in .n1scan.yaml at the repository root instead, and protect that file with CODEOWNERS:
# .n1scan.yaml
mode: fail # or warn
budgets:
- name: whole test suite
max_queries: 2000
max_unique_queries: 300
max_n1: 0
- route: GET /api/orders # needs sqlcommenter / query-log tags
max_queries: 40
max_burst: 3# .github/CODEOWNERS
/.n1scan.yaml @your-team
/n1scan.baseline.json @your-teamn1scan reads .n1scan.yaml when it exists (or --config FILE), reports every limit in the summary and the PR comment, and with --ci fails when one is exceeded. Unknown keys are an error, so a typo never disables a budget. A useful pattern: seed 50-100 rows in an integration test and set a flat limit, which catches anything that grows with the number of rows without breaking on one extra constant query.
In staging or production: read the server logs
The proxy is for development and CI. Where you can't put one in front of the database, n1scan logs finds the same loops in PostgreSQL's own log, with no proxy and no change to the app:
n1scan logs /var/log/postgresql/postgresql-18-main.log
n1scan logs --format csv --db shop postgresql-*.csv.gz # csvlog, jsonlog and .gz work as they are
kubectl logs db-0 | n1scan logs --ci --report n1.md # stdin; --baseline and budgets work here tooEach query of a loop is fast, which is why the slow-query log never catches it, so the server has to log every statement for a while: log_min_duration_statement = 0 (or log_statement = 'all'), per database if you like (ALTER DATABASE shop SET log_min_duration_statement = 0). Bind parameters are logged by default and tell a loop over different ids from the same query repeated. Statements are grouped per session (%p or %c in log_line_prefix; the default '%m [%p] ' works, %t works with coarser grouping), and --dsn adds index suggestions from a read-only EXPLAIN.
From logs n1scan shows the statement each session ran before the loop, but cannot prove it is the parent: the proof needs the rows, which only the proxy sees. Tested against the real logs of all 13 clients of the matrix, in stderr, csvlog and jsonlog, with both settings (results).
Verify a fix
n1scan run --report before.json -- npm test
# change the code
n1scan run --report after.json -- npm test
n1scan diff before.json after.json # --format md or json for agents and PR commentsdiff exits 0 when nothing new appeared, 1 when the change added a finding, and 2 when the comparison proves nothing: the second run captured no queries, the commands differ, or the command failed.
With a coding agent
n1scan measures; your agent writes the fix. Three ways to wire it in:
Claude Code plugin (skill + MCP server):
claude plugin marketplace add alex00010/n1scan claude plugin install n1scan@n1scanMCP server for any MCP client:
n1scan mcpserves three tools over stdio,n1scan_scan(run a command through n1scan, get the findings, the proven parent and a report path),n1scan_logs(the same from a PostgreSQL log file) andn1scan_diff(compare two reports, say whether the fix is verified). For Claude Code:claude mcp add --transport stdio n1scan -- npx -y n1scan mcp.Skill only: copy
skills/n1scaninto.claude/skills/or.agents/skills/(read by Claude Code, Codex, Cursor and others that supportSKILL.md).
The skill gives the agent one protocol: measure, fix the loop in the ORM, measure again with the same command, and report "verified" only when diff says so; never raise thresholds, edit the baseline or touch .n1scan.yaml to get a green check.
Point to the request and the line of code
The wire does not know which line of your code sent a query. If your app adds a sqlcommenter comment (/*route='%2Fapi%2Forders',traceparent='00-…'*/) or a Rails query-log comment (/*application:Blog,controller:posts,action:index*/, built into Rails 7 with config.active_record.query_log_tags_enabled = true), n1scan reads it:
findings say where they happened:
in GET /api/orders (app/services/orders.rb:42), fromroute/http.method,controller/action,joborn1scan_scope, andsource_location,file/lineor the OpenTelemetrycode.*keys;with a W3C
traceparent, repetitions are grouped per request instead of per connection, so a loop that one request spreads over a pool is one burst, and the same query from many independent requests is never mistaken for one.
Without tags, n1scan falls back to the connection and to lineage.
Live screen

n1scan --dsn postgres://me:secret@localhost:5432/app
# then point the app at 127.0.0.1:5433 with sslmode=disableThe live screen shows findings (worst first), the selected finding's index suggestion, and a stream of recent queries with latency bars. q quits, p pauses, c clears. Without a terminal (or with --log) it prints plain lines instead.
What it reports
Kind | Meaning | Fails |
| one read query shape, run | yes |
| one INSERT/UPDATE/DELETE per row in a loop: use a multi-row INSERT, | no |
| the same query with the same values, again and again (only with | no |
| the same lookup from independent requests overlapping on several connections, with no parent query its values came from (only with | no |
| each execution's value came from the previous execution's rows, as in keyset pagination (only with | no |
The fix, in your ORM's words
Each N+1 in the summary, the JSON report, the PR comment and the MCP tools comes with a fix. When the SQL shows which ORM wrote it, the fix uses that ORM's API:
fix (looks like Prisma): load the relation with the parent query, e.g. findMany({ include: { posts: true } }) (use your relation's name), or run one findMany({ where: { author_id: { in: ids } } }) with the ids from the authors queryRecognised today, each checked against real SQL from the client matrix: Prisma, Django, SQLAlchemy and Drizzle. Other code gets the batched SQL form (WHERE author_id = ANY($1)). Names are taken from the SQL, so the relation name may differ in your schema. Each ORM is one YAML file in internal/hints/rules; adding yours is a small pull request (see CONTRIBUTING.md).
Detection quality
eval/ holds 20 query patterns with a known answer (classic loops, nested and pooled loops, paced and slow loops, batched fixes, independent parallel requests, pagination, test transactions, health checks, traced requests) and runs them through n1scan against PostgreSQL in CI. Current result: precision 1.00, recall 1.00, parent proven in 7 of 7 loops that have one. The scenarios were written by the project, so treat this as a regression gate rather than an independent benchmark; a false positive or a miss you hit is welcome as a new scenario.
Options
Flag | Default | Meaning |
|
| where the proxy listens (loopback only unless |
| from | the real server, |
| connection string of the real server; enables index suggestions | |
| from |
|
|
| repetitions of one query shape that count as N+1 |
|
| longest pause between repetitions in one burst |
|
| group per connection, or |
| off | also report identical queries repeated with identical values |
| off | also report duplicate, parallel and pagination patterns (they never fail |
| regexp on the normalised query; repeatable | |
|
| only suggest indexes on tables at least this big |
| off | never run EXPLAIN |
| off | print literal values and query parameters (hidden by default) |
| off | JSON lines on stdout (findings, suggestions, summary; optionally every query) |
| write a report when done: | |
| off | exit 1 when an N+1 was found, 2 when nothing was measured |
| compare with an earlier report; with | |
| off | write |
|
| with a baseline: |
|
| kinds that can fail: |
|
| percent a known finding's largest burst may grow before it is |
|
| query budgets (see above) |
How it works
Proxy. n1scan answers the client's SSL request with "no", so local clients talk plain text to it, and opens its own connection to the server (with TLS if the server wants it). Every message is forwarded unchanged; decoding happens on a copy. If decoding ever fails, the connection falls back to raw byte copying: n1scan should never be the reason a query fails.
Protocol tracking. Simple queries (
Q, split at top-level semicolons) and the extended protocol (Parse/Bind/Execute/Sync, including pipelining and errors in the middle of a pipeline) are matched with the server'sCommandComplete/ErrorResponse/ReadyForQueryto get each statement's text, parameters and duration.Fingerprints. Literals and
$nplaceholders become?,IN (…)andVALUESlists collapse, comments (including sqlcommenter tags) and whitespace disappear.WHERE id = 1andWHERE id = -42get the same fingerprint. The format is versioned (fingerprint_versionin reports) and frozen: a change that alters fingerprints bumps the version, anddiffrefuses to compare across versions instead of reporting everything as new.Bursts. When one fingerprint runs
--thresholdtimes on the same connection with no pause longer than--gap, and with more than one distinct set of values, it is an N+1 (orbatchablefor writes). A burst stays open while its connection is still running a statement, so loops of slow queries are caught too; it also survives pauses of up to 10 s while each new value keeps coming from the same parent column, so loops that do work between queries are caught. AROLLBACKends it, so lookups in separate tests that each roll back are not merged into one.Lineage. The first 500 rows of every result are hashed (salted, in memory, values up to 64 bytes; text and binary forms compare equal). A loop whose values are found in one column of an earlier result, on its connection or on any other, gets that query as its proven parent. A burst with no such parent that overlapped the same query on other connections is independent traffic (
parallel), not an N+1. Without lineage,after:falls back to the statement that ran on the connection right before the burst, skipping sibling loop bodies (posts and comments fetched per author), and no "parent proven" line is printed.Suggestions. n1scan opens a separate connection, starts a
READ ONLYtransaction with a 2 sstatement_timeout, and runsEXPLAIN (FORMAT JSON, VERBOSE)(parameterised queries:GENERIC_PLANon PostgreSQL 16+,PREPAREwith a forced generic plan on 12-15; neverANALYZE, so the query is not executed). A sequential scan with an equality/range filter, or alower(col)/upper(col)filter, on a big table without a matching index becomes aCREATE INDEX CONCURRENTLYsuggestion.
Overhead, measured with pgbench -S on a Windows laptop with server and proxy on the same machine (details): +35 to +54 µs per query for one client, zero failed transactions in simple, extended and prepared modes; a query over a real network takes 1-5 ms. With 16 busy clients latency through the proxy roughly doubles (as it did in v0.1.0). A profile shows why: a build that forwards bytes with no analysis at all costs the same, more than half the CPU goes to socket writes, and n1scan's own analysis is about 5%. The proxy belongs in development and CI, not in front of production traffic; for production, read the logs instead.
Tested clients
Every client runs an N+1 loop and a fixed version, straight to Postgres and through n1scan run --json; results must be identical, the loop must be reported with the right index, and the fixed version must not be reported. Both with plain-text and TLS upstream connections (results, TLS):
Go | Node | Python | Other |
pgx, database/sql + pgx, lib/pq | node-postgres, postgres.js, Prisma 6 (Rust engine), Prisma 7 (adapter-pg), Drizzle | psycopg 3, SQLAlchemy 2, asyncpg, Django | psql (libpq) |
Run it yourself: node clients/matrix.mjs (see CONTRIBUTING.md).
Compared with
Works for any stack | No code changes | Finds N+1 | Suggests index | CI baseline / diff | Windows | |
n1scan | yes (PostgreSQL wire) | yes | yes, with the parent query | yes | yes, plus a GitHub Action | yes |
yes (PostgreSQL, MySQL, TiDB wire) | yes | yes | no |
| no | |
ORM-specific detectors (Bullet, nplusone, debug toolbars) | one framework each | add a library | yes | no | varies | yes |
| yes | server extension | shows totals, not bursts | no | no | yes |
| yes | server config | no (each query is fast) | no | no | yes |
APM N+1 detection | per-language SDK | add an SDK | yes | varies | no | yes |
sql-tap is the closest tool: also a wire proxy, with MySQL and TiDB support and a live web UI, which n1scan does not have. A side-by-side run on nine query patterns, with the script and the cases where each tool wins or fails, is in bench/vs-sql-tap.
Limitations
PostgreSQL only (MySQL is a wanted contribution).
n1scan logsneeds every statement in the log for the period you analyse (log_min_duration_statement = 0costs log volume on a busy server), groups by session rather than by request, and cannot prove the parent query (no rows in a log).The app must connect to n1scan without TLS (
sslmode=disable;rundoes this for you). The leg to the server can use TLS, but SCRAM channel binding (SCRAM-SHA-256-PLUS) cannot work across a proxy, so n1scan removes it from the server's offer; a client configured withchannel_binding=requirewill refuse to connect.Unix-socket connections are not supported; use TCP.
Index suggestions cover sequential scans filtered on columns (equality columns first, then ranges) and on
lower(col)/upper(col); other expressions are skipped. They are proposals: nothing is created, and the cost before/after is not measured.Parameterised queries are explained with
EXPLAIN (GENERIC_PLAN)on PostgreSQL 16+, and withPREPAREplus a forced generic plan on PostgreSQL 12-15.Loops spread over many pooled connections are grouped per connection by default; use
--scope globalif your app's loop hops between connections.Without lineage (the parent's rows never crossed the wire, for example ids from a cache), detection falls back to timing and repetition: a loop that pauses longer than
--gapis then missed, and a loop spread over a pool in parallel is reported asparallel.Lineage compares values, not meaning: a loop over small consecutive integers can match an unrelated result that holds the same integers.
Redaction hides string, number and dollar-quoted literals, bound parameters and quoted parts of server errors. Identifiers and comments (such as sqlcommenter tags) are kept.
Security
n1scan sees every query and parameter, so by default it refuses to listen on anything but loopback, and it replaces literal values and bound parameters with ? before anything is printed or written to a report (--show-values turns that off for local debugging). EXPLAIN runs in a read-only transaction with a timeout and only for single SELECT/WITH statements without data-modifying parts. Nothing is sent anywhere; there is no telemetry.
Contributing
n1scan is young and contributions are very welcome: pick a good first issue, add your ORM or framework to the client matrix, or tell us which client it misses in Discussions. docker compose up starts the Postgres the tests expect; see CONTRIBUTING.md for the rest. Issues and pull requests get an answer within two days.
License
MIT
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Database intelligence, AST SQL injection auditing, query optimization & schema guards.
Benchmark SQL queries, rewrites and indexes on real Postgres, MySQL and SQL Server at scale.
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Hosted MCP server for PostgreSQL diagnostics: slow queries, missing indexes, connection pressure.
Related MCP Servers
- AlicenseNot gradedqualityNot gradedmaintenanceAnalyzes SQL queries for performance issues, provides optimization suggestions with automated rewriting, and recommends indexes across multiple database dialects (PostgreSQL, MySQL, Oracle, SQL Server).1MIT
- FlicenseNot gradedqualityDmaintenanceProvides tools for local development environment management and PostgreSQL optimization, including version checking, port process termination, SQL query analysis, and index suggestions.5-
- AlicenseAqualityCmaintenanceEnables AI agents to explore PostgreSQL schemas, run read-only queries, inspect execution plans, and receive evidence-backed SQL diagnostics with reproducible optimization benchmarks over local stdio.51MIT
- AlicenseAqualityBmaintenanceOffline PostgreSQL diagnostics: reviews SQL, risky migrations, candidate indexes and EXPLAIN JSON plans without database credentials or executing statements.590 npmMIT