# FastAPI Pre-Deploy Gatekeeper

> Low-noise pre-PR/pre-deploy gate for FastAPI and async Python: catches only blocking calls in async code, ORM N+1 queries, missing or unsafe env vars and breaking API changes vs your base branch. Proves each finding with a pytest test, proposes a minimal fix, returns PASS/WARN/BLOCK.

FastAPI Pre-Deploy Gatekeeper is a free AI agent skill on Agensi by finance_kim. It loads into your AI agent through the Agensi MCP server, always in its latest approved version.

- Price: Free
- Creator: [finance_kim](https://www.agensi.io/creators/creator-1335)
- Version: 1.0
- Last updated: 2026-11-26
- Security: scan passed (2026-11-26); every new listing is also reviewed by a person
- Listing: https://www.agensi.io/skills/fastapi-pre-deploy-gatekeeper
- Tags: code-quality-review, apis-backend, testing-debugging

## About this skill

Most AI code reviews bury the one bug that takes production down under fifty style comments. This skill does the opposite: it checks only four things that break FastAPI services or their clients, confirms every candidate by reading the code, proves it with a failing pytest test, proposes the smallest fix, and ends with a clear verdict - **PASS**, **PASS WITH WARNINGS** or **BLOCK**.

### What it catches
- **Blocking calls inside `async def`** - `time.sleep`, `requests`, sync `httpx.Client`, psycopg2/sqlite3/pymysql, a sync SQLAlchemy `Session` in an async route (the most common FastAPI bug), `open()`, `subprocess.run`, bcrypt/passlib password hashing, boto3, smtplib - directly or through a sync helper function. Sync `def` endpoints, awaited calls and `asyncio.to_thread` / `run_in_threadpool` are correctly left alone.
- **ORM N+1 queries** - lazy relationships read in loops or comprehensions, queries executed per iteration, and response models that serialize lazy relationships. SQLAlchemy 1.4/2.0 (sync and AsyncSession, where a lazy load is a 500), SQLModel, Django ORM and Tortoise. Knows `selectinload`, `joinedload`, `select_related`, `prefetch_related` and `lazy="selectin"`.
- **Environment variables** - read in code (os.environ, getenv, pydantic BaseSettings with env_prefix and aliases, Starlette Config, decouple) but missing from `.env.example`, docker-compose, Kubernetes manifests or docs; `int(os.getenv("X"))` crashes; secrets with hard-coded defaults; required variables the compose file never sets. Real `.env` files are never read.
- **API backward compatibility** - removed or renamed routes, removed response fields, new required request fields or query params, type changes, removed enum values and changed status codes, compared against your base branch straight from git (the app is never imported or run) or between two exported openapi.json files. Additive changes are not reported.

### How it works
1. Detects your layout: app entry, router prefixes, ORM, settings style, env templates, manifests, test fixtures.
2. Runs a static scanner (one Python file, standard library only) that lists candidates with rule id, severity, confidence, file:line, evidence and fix.
3. The agent reads each candidate and confirms or dismisses it with a reason - the scanner suggests, the agent decides.
4. Writes one pytest test per confirmed finding from ready templates: an event-loop lag probe, a SQL statement counter (2 rows vs 8 rows), env var presence tests, and an OpenAPI snapshot compatibility test.
5. Proposes a minimal diff per finding and, if you ask, applies it and re-runs the tests.
6. Reports in a fixed format: verdict, findings table with proof, dismissed candidates, pre-existing issues, and what was not verified.

### Why trust it
- 68 unit tests, including false-positive guards (sync endpoints, awaited clients, thread offloading, eager loading, documented variables, additive API changes) and git-based API diffs.
- The test templates were run against the bundled sample service: they fail before each fix and pass after it.
- Never crashes on syntax errors, non-UTF-8 files or large repositories; skips virtualenvs, node_modules and migrations.

### Requirements
Python 3.9+ and git. Nothing to install, no API keys, no network access. Proof tests use your project's own pytest setup.

## Requires

- Python 3.9+
- Git

## Known limitations

Static analysis only. Blocking calls hidden behind dynamic dispatch, class methods or more than one helper level, and third-party SDKs outside the built-in list, can be missed. N+1 through templates, properties or validators outside the route is not traced. Routes registered with add_api_route, mounted sub-apps and generic response models are compared only through the exported openapi.json diff. Custom env wrappers and nested settings models are not followed. Every finding is a candidate the agent confirms before reporting.

## How to use this skill

1. Connect your AI agent to Agensi once: add the MCP server https://mcp.agensi.io/mcp/auth and sign in with your Agensi account (OAuth, no API key). Steps for Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and other agents: https://www.agensi.io/docs/mcp-setup
2. Ask your agent: "Use the FastAPI Pre-Deploy Gatekeeper skill from Agensi" and describe your task.
3. Your agent loads the skill from Agensi when it needs it. Nothing is downloaded.

## Frequently asked questions

### Does it run or import my application?

No. The scanner parses source code with Python's ast module and reads the base branch with git; it never imports, installs or executes your project and makes no network calls. Only the proof tests run, inside your own test setup, when you allow it.

### How is this different from a general AI code review?

It ignores style, naming and refactoring suggestions and reports only four high-impact problem classes. Every finding is confirmed by reading the code and backed by a failing test, so the report stays short and actionable.

### Will it flag my sync def endpoints that use requests or a sync Session?

No. FastAPI runs sync def endpoints and dependencies in a threadpool, so the skill only looks inside async def code. Awaited calls and work passed to asyncio.to_thread, run_in_threadpool or run_in_executor are also not flagged.

### Which ORMs are supported for N+1 detection?

SQLAlchemy 1.4 and 2.0 (sync and async), SQLModel, Django ORM and Tortoise ORM. Eager loading via selectinload, joinedload, select_related, prefetch_related or lazy=selectin on the relationship suppresses the finding.

### How does the API compatibility check work without running the app?

It extracts routes, router prefixes, pydantic models, enums and status codes from the source at your base ref (read with git) and from the working tree, then compares them. If your routes are built dynamically, export openapi.json for both versions and use the OpenAPI diff instead.

### Can I use it in CI?

Yes. Run the scanner with --fail-on high to get a non-zero exit code when a high-severity candidate is found, and --format json for machine-readable output. Reviewed false positives can be silenced with a gatekeeper ignore comment on the line.

### Does it read my secrets?

No. Real .env files are never opened; only templates such as .env.example, manifests and docs are searched for variable names, and reports refer to variables by name only.

---

Source: [Agensi](https://www.agensi.io), the marketplace of skills for AI agents. Any MCP-compatible agent (Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and more) connects at https://mcp.agensi.io/mcp/auth and signs in with an Agensi account; setup for every agent: https://www.agensi.io/docs/mcp-setup. Append .md to any skill, guide or docs address on agensi.io for its markdown version.
