跪拜 Guibai
← Back to the summary

How a Read-Only MCP Server Cut CRUD Development From 1.5 Days to 20 Minutes

I handed 12 CRUD interfaces inside the company to an AI Agent, and saved two weeks

Not a clickbait title. This is a real landing process record: from "AI only writes demos" to "AI operates production databases directly", what lies in between.

Bottom line first

Three numbers:

Metric Before After
Time to add a standard CRUD module 1.5 days 20 minutes
Duplicate code in the interface layer ~8000 lines ~1200 lines (configuration only)
Integration rework count (last 3 months) 2.3 times per week 0.4 times per week

The core isn't making AI write code faster; it's letting it read your table schema directly, generate according to your conventions, and run verification by itself. The key technology behind this is MCP.

1. Why "throwing the requirement at ChatGPT" doesn't work

We tried the simplest approach: paste the table creation statement into the dialog and let it generate the Service layer.

It consistently failed on three things:

  1. It can't see the real data. It doesn't know whether the status field stores 0/1 or ENABLED/DISABLED; guessing wrong means a production bug.
  2. It doesn't know project conventions. Our return body must be wrapped in {code, message, data}, but it returns bare entities by default.
  3. It can't verify itself after generation. Code looks right, but running it throws Column 'create_time' cannot be null, forcing three more rounds of manual back-and-forth.

The problem isn't model capability; it's that the context is static while the engineering environment is alive.

MCP (Model Context Protocol) addresses exactly this: it gives the model a standardized set of "hands and eyes" so it can actively query table schemas, read example code, and run SQL validation within a controlled scope.

2. Build a minimal usable MCP Server in ten minutes

No framework needed; the official Python SDK is enough. The whole file is under 80 lines.

# server.py
import asyncio
import json
from contextlib import asynccontextmanager

import aiomysql
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("db-inspector")

# Read-only connection, this is the first security red line
READONLY_DSN = dict(
    host="127.0.0.1", port=3306, user="ai_reader",
    password="***", db="your_db", autocommit=True,
)


@asynccontextmanager
async def conn():
    c = await aiomysql.connect(**READONLY_DSN)
    try:
        yield c
    finally:
        c.close()


@mcp.tool()
async def list_tables(keyword: str = "") -> str:
    """List database tables, optionally fuzzy-filter by keyword."""
    async with conn() as c:
        async with c.cursor() as cur:
            await cur.execute(
                "SELECT table_name, table_comment FROM information_schema.tables "
                "WHERE table_schema = DATABASE() AND table_name LIKE %s "
                "ORDER BY table_name LIMIT 200",
                (f"%{keyword}%",),
            )
            rows = await cur.fetchall()
    return "\n".join(f"{name}\t{comment or ''}" for name, comment in rows)


@mcp.tool()
async def describe_table(table: str) -> str:
    """View a table's full column definition, including type, nullability, default, comment."""
    async with conn() as c:
        async with c.cursor() as cur:
            await cur.execute(f"SHOW FULL COLUMNS FROM `{table}`")
            cols = await cur.fetchall()
            await cur.execute(f"SHOW INDEX FROM `{table}`")
            idx = await cur.fetchall()
    out = ["field\ttype\tnull\tdefault\tcomment"]
    for f, t, _, null, _, default, _, _, comment, *_ in cols:
        out.append(f"{f}\t{t}\t{null}\t{default}\t{comment or ''}")
    out.append("\nIndexes:")
    for row in idx:
        out.append(f"{row[2]}\tcol order {row[3]}\tunique={not row[1]}")
    return "\n".join(out)


@mcp.tool()
async def sample_rows(table: str, limit: int = 3) -> str:
    """Sample a few real rows to infer field value conventions (masked fields should be handled at the SQL layer)."""
    limit = max(1, min(limit, 10))
    async with conn() as c:
        async with c.cursor(aiomysql.DictCursor) as cur:
            await cur.execute(f"SELECT * FROM `{table}` LIMIT {limit}")
            return json.dumps(await cur.fetchall(), ensure_ascii=False, default=str)


if __name__ == "__main__":
    mcp.run()

Client integration is one line of config:

{
  "mcpServers": {
    "db-inspector": {
      "command": "python",
      "args": ["/path/to/server.py"]
    }
  }
}

At this point, the model can answer questions like "What fields does this table have" and "What does status actually store". Note that sample_rows is the tool it calls most often, because field semantics almost always hide in real data.

3. The real efficiency gain: turning project conventions into tools

A second step many people miss. Simply letting the model see the database still produces code that "doesn't look like our project".

So I added two read-only tools:

Then I put a CLAUDE.md-style specification file in the repository root:

## Code conventions (must follow)
1. Controller always returns Result<T>; no bare entities.
2. Paginated queries use PageQuery input + PageResult output.
3. Create/update operations must explicitly set createTime / updateTime.
4. Enum fields must not hardcode numbers; use XxxEnum.
5. Generated code must pass `mvn -q compile`.

After this, output quality changed qualitatively. Because the model no longer generates "by feel"; it first reads two similar modules, then writes accordingly.

4. Security boundaries: don't let "efficiency" become an "incident"

This has to be explicit; it's where I've stepped on traps.

Rule one: the AI's database account must be read-only.

CREATE USER 'ai_reader'@'%' IDENTIFIED BY '...';
GRANT SELECT ON your_db.* TO 'ai_reader'@'%';

Don't give it ALL for convenience. Let it query, let it look, but never give it write permission. Write operations are always executed after human review.

Rule two: file tools must validate paths.

ALLOWED_ROOT = Path("/Users/me/work/project").resolve()

def safe_path(p: str) -> Path:
    target = (ALLOWED_ROOT / p).resolve()
    if not str(target).startswith(str(ALLOWED_ROOT)):
        raise ValueError("path out of bounds")
    return target

Rule three: generated code must pass CI.

We added a hard rule: AI-produced PRs must pass compile + checkstyle + unit tests before entering human review. This is more effective than any "prompt technique" — use engineering measures to backstop, not trust the model.

5. What the 20-minute full flow looks like

Adding a "contract attachment" module now looks like this conversation:

Me: Add contract attachment module, table t_contract_attachment, need
    upload record, query by contract ID list, logical delete three endpoints.

AI: (automatically calls list_tables to confirm the table exists)
    (calls describe_table to get fields)
    (calls sample_rows to see actual values of file_type)
    (calls list_java_files to read 2 similar modules)
    Generated 9 files...
    (runs mvn compile, passes)

Me: field file_size uses Long, unit is bytes, don't use int.
AI: Adjusted, recompiled, passes.

20 minutes, acceptance passed. The remaining time would have been spent writing DTO, Mapper, Service boilerplate, and debugging field types in integration.

6. A few honest reminders

  1. It won't make business decisions for you. How the state machine flows, how permissions are validated, still need human thought.
  2. It will write complex queries wrong. Multi-table joins plus window functions still need a human.
  3. Upfront investment is significant. Building the MCP Server, writing the spec file, configuring the read-only account takes about 1-2 days. We only started to break even after the 5th module.
  4. Don't open all permissions at once. Start with read-only database, then add file reading, and only consider reading logs/monitoring later. For each layer added, ask yourself: what's the worst case?

Finally

The real value isn't "saving a few days of work"; it's driving the marginal cost of repetitive work close to zero. When you find that adding a standard module takes just 20 minutes, you start to be willing to fill in features you've been avoiding — that's the compounding effect.

All the code above is runnable. If you're doing something similar, feel free to discuss in the comments how you draw your security boundaries.

If this was useful, give it a like so I know. Later I'll write about: how to make the MCP Server support a write-approval flow (human review before writing to the database), and how to promote this spec within a team without causing resistance.

Comments

Top 4 from juejin.cn, machine-translated. The original thread is authoritative.

badhope

The trio of read-only account, schema query, and CI backup is spot on. I'd add one more: make the Agent's write operations a 'draft', first run them on a shadow table or test database, then have a human click confirm. That way no matter how diligent it is, it can only leave mistakes in the draft.

ElaineP

Seeing the line 'use engineering means to back up, not rely on trusting the model' resonates a lot. I'm not a CS major; I've been vibe coding an English synonym graph. A recent incident was almost isomorphic: I asked to 'discard edges that don't form pairs', the AI dropped the edges, but also deleted the words. A whole sense of a common word became a blank page. You guys have CI and unit tests as backup; I can't run either (I can't read those two thousand lines). My current crude methods: ① each delivery, let the AI self-report 'what you did on your own that I didn't ask for'; ② the interface must show numbers that can be reconciled (locally annotated X/Y, online added Z), and I catch its secret deletions by number changes. I'd like to ask specifically: if acceptance changes from 'reading code' to 'reading metrics', what other low-cost checkpoints are worth adding?

用户573468752399

On MCP I've stepped on this: once read-only server is on, table structures, field comments, GET results all get dumped into context. One request over two thousand tokens, multi-round grows to tens of thousands, more expensive than writing code yourself. Later I only give the few tables used, truncate results by row count, store long content in DB and only return ids, and set a call count cap for tools. The bill became controllable immediately. Several domestic models use one key for all calls, enterprise channel pricing, usage can be exported broken down by tool call, reconciliation is also easy. Details in DM.

用户55568270537

The read-only account plus CI backup idea is right. Field value details can't be caught by prompts alone; one wrong guess by the model is an online bug. Section 6's 'use engineering means to back up, not rely on trusting the model' hits the point.