Model Context Protocol (MCP) Integration
Add an mcp-tool: block to an endpoint file and the endpoint becomes a tool an AI agent can call. MCP (the Model Context Protocol) is the JSON-RPC 2.0 protocol that agents such as Claude use to discover tools and call them. flAPI serves it on the same port as the REST API, at POST /mcp/jsonrpc. You need no second implementation and no second server.
By the end of this page you will have:
- a tool with a typed input schema, generated from your validators,
- results that are small enough for an agent's context,
- resources, prompts and long-running tasks,
- an MCP server protected with its own
mcp.auth, per-tool roles and rate limits.
mcp.authAn endpoint's REST auth: block does not protect its MCP tool, and the global rate_limit: does not cover /mcp/jsonrpc. See Protect it.
Why MCP + flAPI?
Without flAPI you would build a REST API for applications, separate tool definitions for agents, and duplicate the validation for both. With flAPI:
- One YAML file produces both a REST endpoint and an MCP tool.
- Your validators become the tool's input schema, so the agent sees types, ranges and enums.
- Caching applies to both. An agent that calls a cached tool fifty times runs zero warehouse queries.
MCP Client (Claude Code, Claude Desktop, Cursor, an SDK)
│ JSON-RPC 2.0 over HTTP
▼
POST /mcp/jsonrpc ◄── one route, same port as REST
│
├──► Tools (mcp-tool blocks)
├──► Resources (mcp-resource blocks)
├──► Prompts (mcp-prompt blocks)
└──► Config tools (flapi_*, only with --config-service)
│
▼
DuckDB / cache tables / connected sources
GET /mcp/health is a plain HTTP probe next to it; it reports tools_count.
Step 1: Set Up the Project
The examples use the TPC-H customer table: 1500 customers with key, name, market segment, phone and account balance.
mkdir mcp-demo && cd mcp-demo
mkdir -p data sqls
curl -L -o data/customers.parquet \
https://github.com/DataZooDE/flapi/raw/main/examples/data/customers.parquet
project-name: customer-agent
template:
path: ./sqls # endpoint files and SQL templates
connections:
customers:
properties:
path: ./data/customers.parquet
Step 2: Make an Endpoint a Tool
This file defines a REST endpoint and an MCP tool at the same time:
url-path: /customers # the REST endpoint...
mcp-tool: # ...and the MCP tool, from one file
name: find_customers
description: >
Look up customers of the wholesale business by key, market segment or
minimum account balance. Returns one row per customer with key, name,
segment and balance in USD. Returns every match: pass limit and offset
(integers) to page through large results.
request:
- field-name: id
field-in: query
description: Customer key (c_custkey), a positive integer
validators:
- type: int
min: 1
- field-name: segment
field-in: query
description: Market segment
validators:
- type: enum
allowedValues: [AUTOMOBILE, BUILDING, FURNITURE, HOUSEHOLD, MACHINERY]
- field-name: min_balance
field-in: query
description: Only customers whose account balance is at least this many USD
validators:
- type: number
min: -1000
template-source: customers.sql
connection: [customers]
SELECT c_custkey, c_name, c_mktsegment, c_acctbal
FROM read_parquet('{{{ conn.path }}}')
WHERE 1=1
{{#params.id}}
AND c_custkey = {{ params.id }}
{{/params.id}}
{{#params.segment}}
AND c_mktsegment = '{{{ params.segment }}}'
{{/params.segment}}
{{#params.min_balance}}
AND c_acctbal >= {{ params.min_balance }}
{{/params.min_balance}}
ORDER BY c_custkey
Start the server and leave it running; use a second terminal for the commands that follow:
flapi -c flapi.yaml # or: uvx --from flapi-io flapi -c flapi.yaml
# port 8080 taken? add -p 8081 and use that port below
mcp-tool.nameandmcp-tool.descriptionare required. Tool names must be unique: if two files declare the same name, the load fails and the error names both files.- The
request:fields become the tool's arguments. Their validators run on every call, just as they do for REST. - MCP is on by default (
mcp.enabled: true). A server with tools and nomcp.authprints theMCP_UNAUTHENTICATED_TOOLSsecurity warning at startup. That is fine on a laptop.
flAPI reads sqls/ at startup. When you add or edit a file by hand, restart the server. If it runs with --config-service, you can load the file without a restart: flapii endpoints reload --file sqls/contacts.yaml. Endpoints created or changed through the config service update tools/list at once. flAPI sends no list_changed notification (it advertises listChanged: false), so clients must list the tools again to see a change.
Every mcp-tool key
| Key | Default | Meaning |
|---|---|---|
name | required | Tool name, unique across the project |
description | required | What the agent reads to decide whether and how to call the tool |
result-mime-type | application/json | MIME type of the result |
allowed-roles | none | Roles that may call the tool. Required under mcp.auth: without it every call is denied |
response.max-rows | no cap | Rows after this many are dropped, silently |
response.redact-columns | none | Columns whose values become "<redacted>" |
response.sample | false | Return {columns, row_count, sampled: true} and no rows |
rate-limit (enabled, max, interval) | max: 100, interval: 60 when the block is present | Per-tool budget, counted per authenticated user |
async | false | Run as a task for clients that support the Tasks extension |
async-after-ms | 0 | Answer inline if done within this many ms, else return a task |
tracing.capture | the global tracing.capture | Per-tool tracing tier: off, metadata or payload. A global capture: off still wins. See Observability |
The input schema is not a key: it is generated from request:.
Step 3: Call It
curl -s http://localhost:8080/mcp/jsonrpc -H 'Content-Type: application/json' -d '{
"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'
curl -s http://localhost:8080/mcp/jsonrpc -H 'Content-Type: application/json' -d '{
"jsonrpc": "2.0", "id": 2, "method": "tools/call",
"params": {"name": "find_customers", "arguments": {"id": 3}}}'
curl -s http://localhost:8080/customers?id=3 # the same SQL over REST
curl -s http://localhost:8080/mcp/health # plain HTTP probe; reports tools_count
Tool inputs go under arguments, not parameters. A full client sends initialize first, and flAPI agrees on the highest protocol version both sides support (the default is 2025-11-25). flAPI returns an Mcp-Session-Id HTTP header, which a client may echo back. Nothing depends on the session, because authentication is checked on every request.
flAPI also serves the stateless MCP 2026-07-28 revision on the same URL. A modern client sends no initialize, gets no session, and repeats the method in HTTP headers. Clients do this for you; the details are in the Protocol Reference.
The rest of this page uses a small shell function:
mcp() { curl -s http://localhost:8080/mcp/jsonrpc -H 'Content-Type: application/json' "${@:2}" -d "$1"; echo; }
To connect Claude Code, Claude Desktop, Cursor or an SDK, see Claude & Client Integration.
Step 4: Write Tools That Agents Use Well
An agent decides whether to call a tool, and with what, from three things: the description, the input schema and the first results it gets back.
Descriptions
The description is the only documentation the agent reads. Say:
- what the tool returns: one row per what, which columns, and in which units;
- when to use it, compared with your other tools;
- how to get less: which filters narrow the result, and that
limitandoffsetpage through it.
Give every request: field a description too; it becomes the property's description in the input schema. Keep a description under 2048 bytes (description hygiene).
Typed inputs, from your validators
flAPI builds the inputSchema from the validators, so the agent sees types and limits rather than bare strings. tools/list shows find_customers as:
{"name": "find_customers",
"description": "Look up customers of the wholesale business by key, ...",
"inputSchema": {"type": "object", "properties": {
"id": {"type": "integer", "minimum": 1, "description": "Customer key (c_custkey), a positive integer"},
"segment": {"type": "string", "enum": ["AUTOMOBILE", "BUILDING", "FURNITURE", "HOUSEHOLD", "MACHINERY"], "description": "Market segment"},
"min_balance": {"type": "number", "minimum": -1000, "description": "Only customers whose account balance is at least this many USD"}}}}
| Validator | Schema |
|---|---|
int | "type": "integer" with minimum / maximum |
number (alias double, float) | "type": "number" with minimum / maximum |
string | "type": "string" with minLength / maxLength; a regex adds pattern |
enum | "enum": [...] (type string unless another validator sets one) |
date, time, uuid, email | "type": "string" with that format |
boolean | "type": "boolean" |
| none | "type": "string" |
required: true lists the field in required. A field's default becomes the schema's default. field-in makes no difference over MCP, because arguments are one flat object. flAPI rejects arguments the tool does not declare: a typo such as segmnt must not silently drop a filter.
Results: structuredContent and a learned outputSchema
A successful call returns the rows twice: a text block for clients that read text, and structuredContent for clients that want JSON:
{"content": [{"type": "text", "text": "[{\"c_custkey\":3,\"c_name\":\"Customer#000000003\",...}]"}],
"structuredContent": {"rows": [{"c_custkey": 3, "c_name": "Customer#000000003", "c_mktsegment": "AUTOMOBILE", "c_acctbal": 7498.12}],
"row_count": 1}}
After the first successful call, tools/list also advertises an outputSchema for the tool ({rows: array of objects, row_count: integer}, column types from the first row). A dry run never sets it, and a config reload clears it. A write tool returns the same body as the REST write (rows_affected, plus data with the RETURNING rows).
Errors an agent can act on
If the agent can fix a failure, flAPI returns it as a normal result with isError: true, and the text says what to change:
mcp '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"find_customers","arguments":{"segment":"boats"}}}'
# {"result":{"isError":true,"content":[{"text":"Invalid arguments for tool 'find_customers': segment: Invalid enum value",...
| Failure | What the agent gets |
|---|---|
| A validator rejected an argument | isError, e.g. segment: Invalid enum value |
| An undeclared argument | isError, segmnt: Unknown parameter not defined in endpoint configuration |
| The per-tool rate limit | isError, Rate limit exceeded for tool '...'. Retry after N seconds. |
| The SQL failed | isError, Tool execution failed on the server. The details are in the server log under request_id req-... |
| Unknown tool name | JSON-RPC error -32602 |
| No credentials, or bad ones | JSON-RPC error -32000, HTTP 401 |
| Missing role | JSON-RPC error -32000 Permission denied: ..., HTTP 403 |
| The tool's cache has not been built yet | JSON-RPC error -32000, HTTP 503 |
A failed query never returns the SQL or the database error to the caller, because they can reveal paths, SQL and credentials. Grep the server log for the request_id.
Step 5: Keep Results Small
A tool call has no default row limit. A REST GET is paginated (100 rows per page), but a tools/call returns every row the template produces, and every row costs the agent context and, on a warehouse, money.
limitandoffsetwork on every tool, even though they are not in its input schema. flAPI applies them outside your SQL. The agent cannot know this unless the description says so. Do not writeLIMIT {{ params.limit }}in a template: that limit applies before flAPI's offset.- Always set
max-rows, and say so in the description. For tools the cut is silent:row_countreports the rows kept. Resources do say so, with_meta.truncated. - Prefer cached tools over live warehouse queries. A tool on a cached endpoint reads the local cache table.
- Use
sample: truefor "how much is there?" It returns{"columns": [...], "row_count": N, "sampled": true}and no rows. - Put a per-tool rate limit on every tool. It is a cost guard against an agent stuck in a loop.
response: shapes the result after the query has run. It applies to MCP only, so the REST endpoint is unaffected:
mcp-tool:
name: customer_contacts
description: Customer names and phone numbers, at most 20 rows per call (phone redacted).
response:
max-rows: 20 # rows after the 20th are dropped
redact-columns: [c_phone] # each value becomes "<redacted>"
template-source: contacts.sql
connection: [customers]
SELECT c_custkey, c_name, c_phone FROM read_parquet('{{{ conn.path }}}') ORDER BY c_custkey
redact-columns keeps the column, so the agent can see that it exists. The database still computes the full result before max-rows cuts it, so put a filter in front of a big query.
Tool-Only Endpoints, Resources and Prompts
Tool only. Leave out url-path, and the file defines a tool with no REST endpoint:
mcp-tool:
name: all_customers
description: Every customer's key and name, ordered by key. Pass limit and offset to page.
template-source: all-customers.sql
connection: [customers]
Resources are data the agent (or the user, in the client) reads rather than an action it takes: a schema, a glossary, a reference table. They are listed by resources/list and read by URI (flapi://<name>):
mcp-resource:
name: customer_columns
description: Column names and types of the customer table
mime-type: application/json
template-source: customer-columns.sql
connection: [customers]
SELECT column_name, column_type FROM (DESCRIBE SELECT * FROM read_parquet('{{{ conn.path }}}'))
A resource template takes parameters from its URI. Each {variable} must be a request: field, whose validators run when the resource is read. Templates are listed by resources/templates/list, not resources/list:
mcp-resource:
name: customer
description: One customer's key, name and balance
uri-template: flapi://customers/{id}
request:
- field-name: id
field-in: path
required: true
validators:
- type: int
min: 1
template-source: customer.sql
connection: [customers]
A resource read is capped at 1000 rows by default; mcp-resource.response.max-rows changes the cap.
Prompts are templates the user picks in the client. A prompt runs no SQL, so it needs no template-source and no connection:
mcp-prompt:
name: review_customer
description: Ask for a credit review of one customer
template: |
Review the credit standing of customer {{customer_id}}.
Call find_customers with id={{customer_id}} first, and quote the balance you used.
arguments: [customer_id]
prompts/get substitutes the arguments and returns one user message. All prompt arguments are strings. More: MCP Resources, MCP Prompts.
Mustache has no default filter (no | syntax). A default is a section plus an inverted section: {{#params.days}}{{{ params.days }}}{{/params.days}}{{^params.days}}30{{/params.days}}, with an int validator so only a number reaches the SQL.
Preview a Call with _dryRun
Add "_dryRun": true to the arguments, and flAPI validates the arguments and renders the SQL, but does not run it (there is no EXPLAIN and no plan):
mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"find_customers","arguments":{"id":3,"_dryRun":true}}}'
# "rendered_sql": "... WHERE 1=1 AND c_custkey = 3 ...", "bindings": [], "parameters": {"id": 3}
The result holds dry_run: true, tool_name, rendered_sql, bindings and the typed parameters; structuredContent also holds rows: []. A bare {{ params.x }} outside a section is a prepared-statement parameter, so it appears as ? with its value in bindings. Values inside a {{#...}} section, like id here, are rendered into the SQL. Role checks, rate limits and validators all still apply, and credentials the template interpolates are scrubbed from the preview. Use dry runs to see what an agent's arguments turn into, and to smoke-test every tool in CI.
Protect It
mcp.auth is separate from REST auth:
An endpoint's auth: block, and the top-level auth: it inherits, protect REST requests only. They do not gate tools/call. With mcp.auth off, a tool on an endpoint whose REST block requires the admin role returns every row to anonymous MCP callers. The global rate_limit: does not cover /mcp/jsonrpc either. MCP has its own block, mcp.auth, and once it is on, every tool must name the roles that may call it.
project-name: mcp-secured
template:
path: ./sqls
connections:
customers:
properties:
path: './data/customers.parquet'
cors:
allow-origins: ['https://app.example.com']
mcp:
auth:
enabled: true
type: basic
users:
- username: analyst # password: s3cret
password: '$pbkdf2-sha256$600000$ZmxhcGktZ3VpZGUtc2FsdA$97qbFjyPX93/VhMF9FkDQ8L3hbz96bFE6BGEAbdsdgE'
roles: [analyst]
- username: intern # password: intern
password: '$pbkdf2-sha256$600000$ZmxhcGktZ3VpZGUtc2FsdA$QmRDEKBk4QbAcVgz9EYzEE0SPz5BJlL8NLI601WRZiU'
roles: [reader]
methods:
tools/list:
required: false # anyone may list; calling still needs credentials
mcp-tool:
name: my_balances
description: Customer balances, with the name of the authenticated caller in column who.
allowed-roles: [analyst] # without this list, every call is denied
rate-limit:
max: 3 # 3 calls per user per 60 s
interval: 60
template-source: balances.sql
connection: [customers]
SELECT '{{{ auth.username }}}' AS who, c_custkey, c_acctbal
FROM read_parquet('{{{ conn.path }}}') ORDER BY c_custkey
URL=http://localhost:8080/mcp/jsonrpc
CALL='{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"my_balances","arguments":{"limit":1}}}'
curl -s $URL -H 'Content-Type: application/json' -d "$CALL" # 401, no credentials
curl -s $URL -H 'Content-Type: application/json' -d "$CALL" -u intern:intern # 403, role reader
curl -s $URL -H 'Content-Type: application/json' -d "$CALL" -u analyst:s3cret # rows, who = analyst
- Passwords are PBKDF2 hashes. A plaintext password works but triggers
AUTH_PLAINTEXT_PASSWORDat startup. These two hashes are for the demo only; see Authentication to make your own. - 401 or 403. A missing or rejected credential gets HTTP 401 with JSON-RPC
-32000. An authenticated caller without one of the tool'sallowed-rolesgets HTTP 403Permission denied: .... A tool, resource or prompt with noallowed-rolesrefuses every call whilemcp.authis on;allowed-roles: []lets no one in. Withoutmcp.auth, flAPI does not check roles. - Per-method requirements.
mcp.auth.methods.<method>.required: falseopens one method, such astools/list. Undermcp.auth,initializeneeds credentials too, unless you open it. Onlyserver/discoveris always public. - The caller is in the template.
auth.username,auth.rolesand the otherauth.*variables hold the MCP principal, so one tool can filter rows per caller. A caller cannot set__auth_*arguments; flAPI strips them. cors.allow-originslists the web pages that may call the server from a browser. Without it, and with authentication on, the startup auditor warnsCORS_WILDCARD_WITH_AUTH. Claude Code, the SDKs and curl are not browsers.- Bearer tokens. For agents that hold a token, use
type: bearer: HS256 JWTs with arolesclaim, signed withjwt-secret.type: oidcexists, but in v26.11.25 it rejects every token (known issue #273).
mcp:
auth:
enabled: true
type: bearer
jwt-secret: '{{env.FLAPI_MCP_JWT_SECRET}}'
jwt-issuer: my-company
Per-tool rate limits
mcp-tool.rate-limit gives each tool its own budget, counted per authenticated user; all anonymous callers share one bucket. If the block is present, the limit is on unless you set enabled: false. max defaults to 100 and interval to 60 seconds. Dry runs count against the budget. An agent over the limit gets an isError result that tells it how long to wait.
Description hygiene
Every tool description is scanned at load time. A control character, a description over 2048 bytes, or a known prompt-injection phrase (ignore previous instructions, disregard the above, system:, you are now, ...) produces a warning naming the tool and the phrase. Set mcp.strict-descriptions: true to make any finding fatal: --validate-config fails and the server refuses to start. The scanner reads descriptions only, never the rows a tool returns.
MCP_UNAUTHENTICATED_TOOLS in CI
flAPI's security auditor prints this warning on every start while mcp.enabled is true, at least one tool exists and mcp.auth.enabled is false. It does not stop the server. Make your CI stop instead:
flapi -c flapi.yaml --validate-config 2>&1 | grep MCP_UNAUTHENTICATED_TOOLS && exit 1
Threat Model and Safe Defaults
An agent with a tool is a new kind of client: it reads everything the tool returns, and it acts on what it reads.
- Returned rows are untrusted input to the model. A customer name or a comment column can hold "ignore your instructions and ...". The description scanner does not look at data. Redact or leave out free-text columns the agent does not need, and keep tools narrow.
- Data can leave through the agent's other tools. An agent that holds
find_customersand also a web-fetch or e-mail tool can send rows anywhere. Give data agents only the tools they need, and keepmax-rowssmall so one call cannot copy a table. - Keep the
flapi_*config tools away from data agents. A server started with--config-servicelistsflapi_*tools that can create, change and reload endpoints. Calls need the config-service token, but the safest setup runs data agents against a server without--config-service. - REST
auth:is not MCP auth. See above.
| Safe default | Why |
|---|---|
mcp.auth.enabled: true | no anonymous calls |
allowed-roles on every tool, resource and prompt | least privilege, per tool |
response.max-rows on every tool | bounded context, bounded exfiltration |
response.redact-columns for personal and free-text data | the model never sees it |
rate-limit on every tool | stops loops and runaway cost |
mcp.strict-descriptions: true | a poisoned description stops the server |
CI fails on MCP_UNAUTHENTICATED_TOOLS | nobody ships an open server by accident |
Long-Running Queries: Tasks
A query that runs for minutes should not hold an agent's HTTP request open. With async: true, a modern client gets a task handle at once and polls for the result:
mcp-tool:
name: segment_totals
description: Total account balance per market segment (slow; runs as a task for clients that support tasks)
async: true # return a task at once
# async-after-ms: 5000 # or: answer inline if done within 5 s, else return a task
template-source: segment-totals.sql
connection: [customers]
A call becomes a task only when all three hold: the request uses the 2026-07-28 protocol, the client declared io.modelcontextprotocol/tasks in clientCapabilities.extensions, and the tool opts in. Any other call runs synchronously, so legacy clients never see a task. The client polls tasks/get until status is completed, failed or cancelled; tasks/cancel interrupts the query. Tuning (mcp.tasks.workers, queue-depth, default-ttl-ms, poll-interval-ms) and the curl flow are in the Protocol Reference.
Trace an Agent's Calls
flAPI honours SEP-414: a traceparent in params._meta makes the tool call part of the agent's own trace, from the agent's reasoning step to the DuckDB query. When both are present, the _meta value wins over an HTTP traceparent header. flAPI reads it even with tracing off, so log lines and the audit record carry the agent's trace ID. See Observability.
Common Mistakes
- Relying on REST
auth:to protect a tool. It does not. Turn onmcp.authand give every toolallowed-roles. - Turning on
mcp.authand forgettingallowed-roles. Every call then answers 403has no allowed-roles configured. - Assuming a tool is paginated. A tool returns every row. Set
max-rowsand tell the agent aboutlimitandoffset. LIMIT {{ params.limit }}in the template. Your limit runs first and breaksoffset.- Adding a file and expecting the tool to appear. Restart the server, or run
flapii endpoints reload --file sqls/<file>.yamlagainst a server with--config-service. - A one-line description. "Gets customers" leaves the agent guessing at units, filters and size.
- Arguments without validators. An unvalidated argument appears as a bare
string, and nothing but your template stands between it and the SQL. parametersinstead ofargumentsin a hand-writtentools/call.- Waiting for
list_changed. flAPI never sends it.
Next Steps
- Claude & Client Integration: Claude Code, Claude Desktop, Cursor, SDKs
- MCP Protocol Reference: every JSON-RPC method, error code and header
- MCP Config Tools (
flapi_*): manage flAPI itself from an agent - Caching Setup: serve agents from a cache table, not the warehouse
- Authentication: users, password hashes, JWT
- Validation: validators that become the input schema
Need help building AI-powered data tools? Check out our professional services.