How to Turn a SQL Database into a REST API and an MCP Server

Three ways to put a REST API and an MCP server in front of an existing SQL database: hand-written code, a config-driven generator (PostgREST, Data API builder), or Faucet. Includes a captured end-to-end transcript.

Key takeaways

  • There are three ways to do it: write the API and MCP tools yourself, run a config-driven generator (PostgREST plus an MCP wrapper, or Microsoft Data API builder), or run Faucet, which serves REST, MCP and OpenAPI from one binary.
  • Whichever you pick, start with a least-privilege database user. The API layer is your second line of defense, not your first.
  • In our captured run on SQLite, Faucet needed four CLI commands to reach an authenticated REST call. A GET-only API key blocked 0/9 write attempts over REST and MCP.
  • Whatever you run, put it behind TLS, scope every client to the tables it needs, and work through the database MCP server security checklist before production.
  • Pick Data API builder for Microsoft-stack APIs with GraphQL and row-level database policies. Pick PostgREST for Postgres-native authorization. Hand-write it when every endpoint carries business logic.

You have an existing SQL database and need two front doors: REST for apps and MCP for AI agents, with one set of rules for who may do what.

How do you turn a SQL database into a REST API and an MCP server?

To turn a SQL database into a REST API and an MCP server, create a least-privilege database user, put one API layer in front of it, and give each client a scoped credential that governs both REST and MCP. Hand-writing that layer with FastAPI or Express plus an MCP SDK is best for custom business logic. PostgREST plus an MCP wrapper is best for Postgres-native authorization, and Microsoft Data API builder is best for Microsoft stacks that also want GraphQL. Faucet, the open-source database-to-REST-API and MCP server, is best for REST, OpenAPI and MCP across seven SQL engines from one binary.

The three approaches compared at a glance

ApproachBest forDatabasesWork to first endpointAuth and rolesMCPOpenAPIOngoing maintenanceLicense / pricing model
1. Hand-written (FastAPI or Express + MCP SDK)Custom logic per endpointAny your driver supportsWrite every route and toolWhatever you buildYou write the toolsFastAPI generates it; Express needs extra workCode changes for every schema changeYour code; FastAPI and the MCP Python SDK are MIT
2a. PostgREST + @supabase/mcp-server-postgrestPostgres-native authorizationPostgreSQL onlySQL roles and grants, a config file, then the wrapper (from docs)JWT mapped to PostgreSQL roles; grants and RLS applySeparate wrapper processOpenAPI 2.0 (Swagger) on the root path, filtered by role by defaultSQL grants and policies, plus a second processPostgREST MIT; wrapper Apache-2.0 (v0.2.0); free
2b. Microsoft Data API builderMicrosoft stacks, curated entities, GraphQLREST: SQL Server, Azure SQL, PostgreSQL, MySQL. Cosmos DB: GraphQL and MCP onlydab init, dab add per entity (or dab auto-config patterns on SQL Server), dab start (from docs)Unauthenticated (2.0 default), Entra ID, custom JWT, App Service, OBO on SQL Server; per-entity roles, field rules, database policiesBuilt in (1.7+), Streamable HTTP and stdioOpenAPI 3.0.1, permission-aware (2.0+)dab add per new entity, except auto-config on SQL ServerMIT, free
3. FaucetSeven engines, REST and MCP togetherPostgreSQL, MySQL, MariaDB, SQL Server, Oracle, Snowflake, SQLitedb add, role create, key create, serve (4 commands, measured)API keys with roles scoped by service, table and verb; admin JWTBuilt in at /mcp, plus stdioOpenAPI 3.1Picks up schema changes; you run the TLS proxyMIT, free

How we evaluated

On 2026-10-16 we reviewed every approach against the same questions: databases served, work to a first authenticated request, how clients are authenticated and scoped, whether MCP is built in, and what OpenAPI it publishes.

We make Faucet, and only Faucet went through our comparison harness. It was built from source at commit 2327d63 (v0.1.15 plus 4 commits), on an 8 vCPU Linux machine, against the Chinook 1.4.5 SQLite sample database, with a fresh copy of the database for each test. To decide whether a write landed, we read the file back over a separate read-only SQLite connection instead of trusting the server’s reply. We also ran the hand-written sketch once to check that it works. The PostgREST and Data API builder sections come from each project’s own docs and repositories, listed in the sources. We did not run them. MCP-only servers from the same harness are compared in the best MCP servers for databases. Drafting was AI-assisted; every vendor fact and test number was checked against the sources and raw results.

1. Hand-written: FastAPI or Express plus an MCP SDK — Best for custom business logic

Best for: teams whose endpoints carry real business rules, not just table CRUD.

You write the routes, the SQL and the MCP tools yourself. In Python, FastAPI (MIT) handles the REST side and generates OpenAPI docs for you. The official MCP Python SDK (MIT, mcp 2.3.0 on PyPI) handles the agent side, and one shared function can back both:

import sqlite3
from contextlib import closing
from fastapi import FastAPI, Query
from mcp.server import MCPServer

DB = "file:chinook.db?mode=ro"   # read-only, enforced by SQLite
mcp = MCPServer("chinook")
app = FastAPI(lifespan=lambda _: mcp.session_manager.run())

def long_tracks(min_ms: int, limit: int) -> list[dict]:
    with closing(sqlite3.connect(DB, uri=True)) as conn:
        conn.row_factory = sqlite3.Row
        rows = conn.execute(
            "SELECT TrackId, Name, Milliseconds FROM Track "
            "WHERE Milliseconds > ? ORDER BY Milliseconds DESC LIMIT ?",
            (min_ms, min(limit, 100)),
        ).fetchall()
    return [dict(r) for r in rows]

@app.get("/tracks")
def get_tracks(min_ms: int = 0, limit: int = Query(25, le=100)):
    return long_tracks(min_ms, limit)

@mcp.tool()
def find_long_tracks(min_ms: int, limit: int = 25) -> list[dict]:
    """Longest tracks above a duration in milliseconds."""
    return long_tracks(min_ms, limit)

# Serve MCP (Streamable HTTP) on the same app, at /mcp/
app.mount("/mcp", mcp.streamable_http_app(streamable_http_path="/"))

We ran it under uvicorn with mcp 2.3.0 and FastAPI 0.143.3. GET /tracks and a tools/call to find_long_tracks returned the same rows.

Strengths

  • You control every query, response shape and tool description.
  • Business rules, validation and side effects live next to the data access.
  • The tool surface stays small, because you write only the tools an agent needs.

Things to know

  • Each table needs its own route and tool. Every new table or column means new code, tests and a deploy.
  • Nothing in the sketch authenticates anyone. Keys, roles, rate limits and audit logs are all yours to build.
  • You own SQL-injection safety, row caps and pagination on both surfaces.
  • MCP SDKs change quickly: the Python SDK’s 2.x line uses MCPServer, and the TypeScript SDK’s v2 line ships as @modelcontextprotocol/server.

Who should choose it

Product teams exposing a handful of curated operations, such as “refund an order”, where a generic CRUD API is the wrong abstraction.

2. Config-driven generators: PostgREST or Data API builder — Best for single-ecosystem teams

Best for: teams standardized on PostgreSQL, or on Microsoft’s data stack.

PostgREST plus an MCP wrapper

PostgREST (MIT, v16.4 released 2026-09-24) serves a REST API from an existing PostgreSQL database, with an OpenAPI 2.0 (Swagger) description on its root path. Authorization lives in the database: an authenticator role switches to the role named in the request’s JWT, and the grants and row-level security policies you write in SQL decide what each caller can see and change.

PostgREST has no MCP server of its own. The Supabase community package @supabase/mcp-server-postgrest (Apache-2.0, pre-1.0 at 0.2.0) adds one with two tools. postgrestRequest sends a method, path and body to PostgREST, and sqlToRest converts SQL into a PostgREST request.

Microsoft Data API builder

Data API builder (DAB, MIT, 2.1.5 released 2026-10-01) serves REST, GraphQL and MCP from one dab-config.json. Its SQL MCP Server has been part of DAB since version 1.7 and exposes seven DML tools: describe_entities, create_record, read_records, update_record, delete_record, execute_entity and aggregate_records. From 2.0, a stored procedure can also be exposed as its own named MCP tool (--mcp.custom-tool true, SQL Server only). Setup looks like this:

dab init --database-type mssql --connection-string "<your-connection-string>" \
  --auth.provider EntraID --auth.audience "<api-audience>" \
  --auth.issuer "https://login.microsoftonline.com/<tenant-id>/v2.0" \
  --config dab-config.json --host-mode development
dab add Employees --source dbo.Employees --source.type table \
  --permissions "authenticated:read"
dab start

Set --auth.provider explicitly. Since 2.0, dab init defaults to the Unauthenticated provider, under which every request runs as anonymous and authenticated or custom roles are never activated. For a quick local demo you can skip the auth options and grant anonymous:read instead.

Strengths

  • PostgREST pushes authorization into PostgreSQL itself, so grants and row-level security policies are the source of truth.
  • DAB applies the same per-entity roles, field include/exclude rules and database policies (row filters on read, update and delete for SQL Server, PostgreSQL and MySQL) to REST, GraphQL and MCP.
  • DAB on SQL Server supports On-Behalf-Of auth, so row-level security in the database sees the real Entra ID user.
  • DAB 2.0’s dab auto-config exposes tables by include/exclude pattern on SQL Server and picks up new matching tables on each start.
  • DAB’s OpenAPI document (3.0.1) shows only the methods and fields a role can use, from 2.0.
  • DAB has no NL2SQL or raw SQL tool, by design, which keeps agent queries deterministic.

Things to know

  • PostgREST serves PostgreSQL only. Its MCP side is a separate, pre-1.0 process that forwards generic HTTP requests.
  • PostgREST authorization means writing and maintaining SQL roles, grants and policies, which takes real expertise.
  • DAB auto-config works only on Microsoft SQL. On PostgreSQL and MySQL you add each entity with dab add, which is safer but slow for a 200-table schema.
  • DAB does not cover Oracle, Snowflake, MariaDB or SQLite, and serves Cosmos DB over GraphQL and MCP only, not REST.
  • DAB’s CLI needs the .NET 8 runtime or later. Providers other than Unauthenticated, Static Web Apps and Simulator need a JWT audience and issuer, and DAB has no API-key option.
  • DAB has no DDL tools, by design.

Who should choose it

Choose PostgREST if your team already thinks in PostgreSQL roles and policies. Our roundup of PostgREST alternatives covers the other options. Choose DAB if you run on Azure or SQL Server, want GraphQL or row-level policies, and are comfortable with an identity provider. We covered DAB’s MCP launch in our post on Microsoft DAB’s MCP server.

3. Faucet: one binary for REST, OpenAPI and MCP — Best for multi-database APIs without per-table config

Best for: exposing PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, Snowflake or SQLite with one tool and one set of keys and roles.

Faucet is an MIT-licensed Go binary. It introspects the schema at runtime and serves every table under /api/v1/<service>/_table/<table>. It also publishes OpenAPI 3.1 and exposes eight MCP tools at /mcp on the same port. How Faucet turns databases into APIs explains the internals. The walkthrough below was captured by the harness.

Step 1: Create a least-privilege database user

Whichever approach you choose, give the API its own login with only the grants it needs. For a read-only API:

-- PostgreSQL
CREATE ROLE faucet_api LOGIN PASSWORD 'change-me';
GRANT USAGE ON SCHEMA public TO faucet_api;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO faucet_api;

-- MySQL / MariaDB
CREATE USER 'faucet_api'@'%' IDENTIFIED BY 'change-me';
GRANT SELECT ON shop.* TO 'faucet_api'@'%';

-- SQL Server (run in the target database)
CREATE LOGIN faucet_api WITH PASSWORD = 'change-me';
CREATE USER faucet_api FOR LOGIN faucet_api;
ALTER ROLE db_datareader ADD MEMBER faucet_api;

SQLite has no users, so in our run the API layer did all the scoping.

Step 2: Expose the database as a REST API with a read-only key

Install Faucet with npx @faucetdb/faucet, Homebrew, Docker or a release binary (see Getting started). Then run three commands. Below is the captured output, with the database path shortened and the key redacted:

$ faucet db add --name chinook --driver sqlite --path chinook.db
Added service "chinook" (driver=sqlite, id=1)

$ faucet role create --name readonly --verbs GET --description read-only
Created role "readonly" (id=1)
  description: read-only
  access: GET on */*

$ faucet key create --role readonly --label harness
API Key created:

  Key:   faucet_<redacted>
  Role:  readonly
  Label: harness

  Save this key now - it cannot be retrieved again.

The three commands took about 0.07 s in total. For PostgreSQL or SQL Server, pass --host, --user, --database and --password-prompt instead of --path; --password-prompt keeps the password out of shell history, and --ssl-mode encrypts the database connection. The PostgreSQL REST API guide and SQL Server REST API guide cover the engine-specific options.

Step 3: Start the server and make an authenticated REST call

faucet serve --foreground --host 127.0.0.1 -p 8080

Passing --host 127.0.0.1 keeps it local while you test. (The harness used a random free port; we show 8080 here.) Over five runs, the median time from launch to the first successful query was 0.045 s. Next, a filtered, sorted query with a total count:

curl -s "http://127.0.0.1:8080/api/v1/chinook/_table/Track?filter=Milliseconds%20%3E%20300000%20AND%20GenreId%20%3D%201&fields=TrackId,Name,Milliseconds&order=Milliseconds%20DESC&limit=3&include_count=true" \
  -H "X-API-Key: $FAUCET_KEY"
{
  "resource": [
    { "Milliseconds": 1612329, "Name": "Dazed And Confused", "TrackId": 1666 },
    { "Milliseconds": 1196094, "Name": "Space Truckin'", "TrackId": 620 },
    { "Milliseconds": 1116734, "Name": "Dazed And Confused", "TrackId": 1581 }
  ],
  "meta": { "count": 3, "total": 407, "limit": 3, "offset": 0, "took_ms": 3.074 }
}

The filter syntax supports AND/OR, IN, BETWEEN, LIKE and more, and every value is sent as a bound parameter. Without a limit, responses return 25 rows, and limit=5000 was clamped to 1,000. Without a key, the same URL returns:

{"error":{"code":401,"message":"Authentication required. Provide X-API-Key header or Bearer token."}}

Step 4: Lock it down and test the write paths

The GET-only key is your main control. We sent nine write attempts with it: insert, update and delete through the MCP CRUD tools, the same three through faucet_raw_sql, and REST POST, PATCH and DELETE. 0/9 landed. REST returned 403:

{"error":{"code":403,"message":"Role \"readonly\" does not permit POST on chinook/_table/Artist","context":{"component":"_table/Artist","role":"readonly","service":"chinook","verb":"POST"}}}

You can narrow roles to one service or a table pattern; see the RBAC docs. The key does not cover two cases:

  • Admins bypass roles, by design. With service defaults, an admin session could insert, update and delete (3/3). Raw SQL was still refused, because it is off by default.
  • The service read_only flag blocks writes from everyone, admins included. We set it through the admin API:
curl -X PUT http://127.0.0.1:8080/api/v1/system/service/chinook \
  -H "Authorization: Bearer $ADMIN_TOKEN" -H "Content-Type: application/json" \
  -d '{"read_only": true, "raw_sql_allowed": true}'

We turned raw SQL on in the same call to prove that read_only takes precedence. Over HTTP as admin, 0/9 writes landed, with errors such as Service "chinook" is read-only. Raw SQL is not permitted. Over stdio, 0/6 landed. For the full pattern, see how to give an AI agent read-only database access.

Step 5: Turn the database into an MCP server for AI agents

The MCP endpoint is on the same port and takes the same key. Test it with an initialize call:

curl -sS -X POST http://127.0.0.1:8080/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H "X-API-Key: $FAUCET_KEY" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1.0"}}}'
{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18","capabilities":{"resources":{"subscribe":true},"tools":{"listChanged":true}},"serverInfo":{"name":"Faucet Database API","version":"dev"}}}

The version reads dev because of the source build. Without a key, /mcp returns 401. tools/list returned eight tools: faucet_list_services, faucet_list_tables, faucet_describe_table, faucet_query, faucet_insert, faucet_update, faucet_delete and faucet_raw_sql. Then register the endpoint with your client:

claude mcp add --transport http faucet http://127.0.0.1:8080/mcp \
  --header "X-API-Key: $FAUCET_KEY"

Client-specific setup is in Connect Claude to your database, Connect ChatGPT to your database and the MCP server docs.

Step 6: Publish the OpenAPI document

GET /openapi.json returned an OpenAPI 3.1.0 document with 11 paths (41,453 bytes), which client generators and Custom GPT Actions can import. The per-service copy is at /api/v1/chinook/_doc.

Strengths

  • One binary covers seven engines, with no per-table configuration.
  • REST and MCP enforce the same key and role rules on every call.
  • Raw SQL is off by default, bulk updates and deletes require a filter, and every filter value is a bound parameter.
  • A read-only key takes three CLI commands, and the service-level read_only flag is one setting.

Things to know

  • It is a newer project than PostgREST or Data API builder, with a smaller community.
  • It covers SQL databases only, and serves REST rather than GraphQL; REST has no join or related-record expansion.
  • Clients authenticate with API keys rather than OAuth or an identity provider, and there is no row- or column-level security.
  • Serve it behind a TLS reverse proxy; see the deployment docs.
  • Release builds send anonymous usage telemetry (counts, driver types, OS; no data or names). Disable it with FAUCET_TELEMETRY=0 or faucet config set telemetry.enabled false.

Who should choose it

Teams that want a REST API and an MCP server on an existing database today, especially across more than one engine or on Oracle, Snowflake, MariaDB or SQLite. Put a TLS proxy in front for production.

Faucet vs Data API builder

Both are MIT-licensed and serve REST and MCP from one process with shared roles. Choose DAB when you want GraphQL, Entra ID or On-Behalf-Of auth, row-level database policies, field-level include/exclude rules, permission-aware OpenAPI, stored procedures as named MCP tools, and an explicit list of exposed entities (or auto-config patterns on SQL Server). Choose Faucet when you want every table on any of seven engines without per-table config, API keys instead of an identity provider, raw SQL as an opt-in, or an engine DAB does not cover (Oracle, Snowflake, MariaDB or SQLite).

Faucet vs PostgREST plus an MCP wrapper

On PostgreSQL, PostgREST is stronger on authorization: because it runs requests as database roles, PostgreSQL’s own grants and row-level security policies apply, and Faucet has no row-level security. Faucet is simpler to set up. You run one process instead of two, use built-in API keys instead of JWT plumbing, get typed MCP tools instead of a generic request forwarder, and can use the same tool for MySQL or SQL Server. Our Faucet vs PostgREST comparison covers filtering, embedding and deployment in detail.

Other options

Supabase runs PostgREST for its REST API and offers an official hosted MCP server with a read-only mode, which suits teams whose Postgres already lives on Supabase. Oracle REST Data Services (ORDS), Oracle’s own REST layer, added MCP support in 26.2 (July 2026), so Oracle shops should evaluate it alongside Faucet. For the wider field, including commercial platforms, see the best database-to-REST-API tools.

What can go wrong

  • The agent reaches an admin path. Admin sessions bypass roles in most API layers, so give agents scoped API keys only.
  • The schema leaks through the docs. Generated OpenAPI documents list table and column names, so keep them off the public internet.
  • Reads are unbounded. Hand-written endpoints need their own caps. Faucet caps REST and faucet_query reads at 1,000 rows (default 25); the opt-in faucet_raw_sql tool allows up to 10,000.
  • Traffic is plain HTTP. Put a TLS proxy in front of Faucet and restrict who can reach it.
  • A client runs away. Set rate and request-size limits for every API layer, at the proxy if not in the tool.

Before you go to production, work through the database MCP server security checklist.

Which approach should you pick?

If your endpoints are business operations, hand-write them. If your team lives in PostgreSQL roles or the Microsoft stack, PostgREST or Data API builder fits that world. If you want a REST API and an MCP server on an existing database, on any of seven engines, try Faucet: in our run, four commands took a SQLite database to an authenticated REST and MCP endpoint. Start with the quickstart.

Frequently asked questions

Can I get a REST API and an MCP server from one tool?

Yes. Faucet serves REST, an OpenAPI 3.1 document and an MCP endpoint at /mcp from one binary, with one set of API keys and roles. Microsoft Data API builder serves REST, GraphQL and MCP from one dab-config.json for SQL Server, Azure SQL, PostgreSQL and MySQL; Cosmos DB gets GraphQL and MCP but no REST. PostgREST serves REST only, so you add an MCP wrapper such as @supabase/mcp-server-postgrest.

Can I generate an MCP server from my database schema automatically?

Yes. Faucet and Data API builder build MCP tools from the schema rather than from code you write. Faucet introspects the live schema and exposes eight generic tools: list services, list tables, describe, query, insert, update, delete and an opt-in raw SQL tool. Data API builder exposes seven tools over the entities in its config. PostgREST needs a separate MCP wrapper.

Do I need to change my database schema?

No, not for any of the three approaches. Faucet and PostgREST introspect the existing schema at runtime. Data API builder reads the tables, views and procedures you list as entities in its config. What you should change is access: create a dedicated database user with only the grants the API needs, instead of reusing an application or admin login.

How do I keep an AI agent read-only?

Use two layers. In the database, give the API's login SELECT-only grants. In the API layer, give the agent a key that cannot write: in Faucet, a role created with --verbs GET, plus the service read_only flag if admins also connect. In our harness a GET-only key blocked 0/9 writes. See how to give an AI agent read-only database access.

Does this work with an on-prem database?

Yes. All three approaches are self-hosted, so the API runs next to the database on your own network. Faucet serves plain HTTP, so put it behind a reverse proxy for TLS. Faucet release builds send anonymous usage telemetry (counts, driver types, OS; no data or names). For air-gapped setups, turn it off with FAUCET_TELEMETRY=0 or faucet config set telemetry.enabled false.

Is the OpenAPI document safe to publish?

Treat it as internal. A generated OpenAPI document lists table and column names, so keep it on a private network or behind auth. From version 2.0, Data API builder's OpenAPI document is permission-aware. By default, PostgREST's output depends on the requesting role. Faucet serves a per-service document at /api/v1/{service}/_doc that requires an API key.

Should I use stdio or HTTP for the MCP server?

Use Streamable HTTP with an API key for anything shared, because the key's role then applies to every tool call. Keep stdio for a single developer's own machine. Data API builder's stdio mode (dab start --mcp-stdio) takes an optional role:<name> argument, defaults to anonymous and uses its simulator auth provider.

Sources

Last reviewed