Skip to content

MCP Servers

The mcp module exposes your application’s models, module operations, GraphQL queries, and custom Python functions as standardized tools to external AI coding and agent environments (Cursor, Windsurf, Claude Desktop, Antigravity, and autonomous agents) using the Model Context Protocol (MCP).

Each MCP server is declared declaratively as a single JSON file in the project’s mcp/ directory and served over Streamable HTTP with JSON responses (or stdio). Nothing is exposed by default; each server exposes only the explicit tools, models, and operations you specify.


Install the MCP extra:

Terminal window
pip install "kirak[mcp]"

Uses MCP Python SDK v2: The module leverages the official MCP SDK v2 (mcp.server.mcpserver).

Enable the module in kirak.json:

{
"modules": ["mcp"]
}

flowchart TD
Client["MCP Client<br/>(Cursor / Claude Desktop / Antigravity)"] --> Transport{"Transport Layer"}
Transport -- "Streamable HTTP (JSON)" --> HTTPServer["Mounted ASGI App<br/>/mcp/<server_name>/"]
Transport -- "Local stdio" --> StdioProcess["kirak mcp run <name>"]
HTTPServer --> HostCheck{"Host Verification<br/>(mcp.allowed_hosts, default base_url's host)"}
HostCheck -- "Foreign Host" --> RefuseHost["400 Invalid host header"]
HostCheck -- "Valid" --> OriginCheck{"Origin Verification<br/>(DNS Rebinding & CORS)"}
OriginCheck -- "Foreign Origin" --> RefuseOrigin["403 PERMISSION_DENIED"]
OriginCheck -- "Valid" --> AuthCheck{"Authentication & Role Check<br/>(Bearer Token / API Key)"}
StdioProcess --> AuthCheck
AuthCheck -- "Unauthorized" --> Refuse401["401 MISSING_TOKEN / 403 FORBIDDEN"]
AuthCheck -- "Authorized" --> RateLimit{"Rate Limit Check<br/>(rate_limit_per_minute)"}
RateLimit -- "Exceeded" --> Refuse429["429 RATE_LIMIT_EXCEEDED"]
RateLimit -- "Allowed" --> ToolDispatch["MCP Tool Dispatcher"]
ToolDispatch --> SafetyFilter{"Tool Safety Check<br/>(tool_safe != false)"}
SafetyFilter -- "Credential Op (login/register)" --> RejectTool["Excluded from Manifest<br/>(Never exposed to LLM context)"]
SafetyFilter -- "Safe Tool" --> ConfirmGate{"requires_confirmation = true?"}
ConfirmGate -- "Yes (Write/Destructive)" --> IssueForm["Return Multi-roundtrip Confirmation Form<br/>(10-minute HMAC signed approval ticket)"]
IssueForm --> UserDecision{"Human Approves?"}
UserDecision -- "Declined" --> RefuseConfirm["403 CONFIRMATION_DECLINED"]
UserDecision -- "Accepted" --> ExecuteOp["Execute Operation with Ambient Caller Context"]
ConfirmGate -- "No (Read-only)" --> ExecuteOp
ExecuteOp --> EnforceRLS["Execute Model CRUD / Module Op<br/>(RLS & Field Permissions Enforced)"]
EnforceRLS --> OutputValidation{"Declared Output Schema?"}
OutputValidation -- "Mismatch" --> ErrMismatch["502 OUTPUT_SCHEMA_MISMATCH"]
OutputValidation -- "Valid / Omitted" --> ReturnMCP["Return Standard Result Envelope to Client"]

Place server configurations in mcp/ (e.g. mcp/support.json, mcp/admin.json):

mcp/support.json:

{
"$schema": "../.kirak/mcp.schema.json",
"name": "support",
"description": "Customer support tools for order lookups and refunds",
"instructions": "Always look up the order details before issuing refunds or updates.",
"access": "User",
"roles": ["support", "admin"],
"rate_limit_per_minute": 60,
"tools": {
"orders_fetch": {
"operation": "orders.fetch",
"description": "Retrieve customer orders"
},
"orders_search": {
"operation": "orders.search",
"description": "Search orders by email or status"
},
"refund_payment": {
"operation": "payments.refund_payment",
"fixed": { "provider": "stripe" },
"requires_confirmation": true
}
}
}

Served automatically at /mcp/support/.

Field Required Description
name Yes Unique server name (lowercase letters, numbers, _). Forms the URL route /mcp/<name>/.
description Yes High-level summary sent to connecting clients and agent inspectors.
instructions No System prompt / instructions delivered to the model when connecting.
access No Minimum caller access level: Guest (public), User (authenticated, default), Admin, or System.
roles No Whitelist of user roles allowed to connect (e.g. ["support", "admin"]).
rate_limit_per_minute No Request cap per caller per minute (default 60).
tools No Map of tool definitions exposed by this server.

Each entry under tools specifies an operation to expose:

  1. Model CRUD Operations (<model>.<operation>): fetch, search, count, exists, create, update, upsert, delete, destroy, restore.
    • Row-Level Security (RLS): Executes with the ambient caller’s identity. A support agent only sees rows permitted by their model access rules.
  2. Module Operations (<module>.<operation>): payments.refund_payment, vector.search, notifications.send_email.
  3. Fixed GraphQL Queries (graphql): Fixed query document stored in fixed.query; variables are exposed as tool arguments. Model tools take AND filters only; an or: list exists only inside a fixed GraphQL query document.
  4. Entire AI Agents as Tools (ai.run_agent):
    "ask_billing": {
    "operation": "ai.run_agent",
    "fixed": { "agent": "billing-specialist" }
    }
  5. Custom Python Tools: Registered via @kirak.mcp("<server_name>").tool:
def on_kirak_ready(kirak):
@kirak.mcp("support").tool(requires_confirmation=True)
async def cancel_subscription(user_id: int, reason: str) -> dict:
"""Cancel a user subscription immediately."""
# Executes with the authenticated caller's identity
result = await kirak.payments.cancel_subscription({"user_id": user_id})
return {"status": "cancelled", "user_id": user_id}

A tool’s output schema tells the client the shape of its result, in the standard envelope (statusCode, status, message, data).

  • Model fetch and search: data is a list of records, and each field has the JSON Schema type of its Kirak type, the same on SQLite, MySQL and PostgreSQL: boolean fields are true / false, integer fields integers, float and decimal fields numbers, dates and timestamps ISO-8601 strings, multiselect fields lists of strings. Every field except the primary key may also be null. json fields are untyped, since they hold any JSON value. Write-only fields are left out.
  • Model exists: data is {"exists": true | false}.
  • Module operations whose result the catalog declares have that shape.
  • output on a tool sets data’s JSON Schema itself, for any tool kind. Use it for module operations whose result depends on the provider, best with fixed.provider. Kirak checks every result against a declared output: a result that does not match answers 502 OUTPUT_SCHEMA_MISMATCH, naming the fields, and is logged. kirak validate reports an output that is not valid JSON Schema (invalid_tool_output).
"send_receipt": {
"operation": "notifications.send_email",
"fixed": { "provider": "sendgrid" },
"output": {
"type": "object",
"properties": { "id": { "type": ["string", "null"] }, "message": { "type": "string" } },
"required": ["id"]
}
}

To ensure AI coding agents and external LLMs never receive credentials in their context windows, Kirak enforces a strict Tool Safety Gate:

[!CAUTION] Credential Operations Blacklisted: Operations that accept or return raw credentials (login, register, change_password, create_api_key, verify_otp, generate_verification_link) have tool_safe: false in their catalog metadata.

The MCP server compiler strictly refuses to expose these operations as MCP tools. Attempting to add an auth credential operation to mcp/*.json fails schema validation at startup (kirak validate mcp).


Human-in-the-Loop Confirmation (requires_confirmation)

Section titled “Human-in-the-Loop Confirmation (requires_confirmation)”

Destructive and state-modifying tools (delete, destroy, refund_payment, orders.update) default to requires_confirmation: true.

  1. When a client calls a confirmed tool, Kirak issues a multi-roundtrip confirmation form detailing the tool name, arguments, and an HMAC-signed ticket valid for 10 minutes.
  2. The MCP client (e.g. Cursor or Claude Desktop) displays an interactive approval prompt to the user.
  3. If the user clicks Accept, the client retries with the signed ticket and the operation executes. If Declined, Kirak returns 403 CONFIRMATION_DECLINED without executing the underlying logic.

An approval is single-use: each ticket carries a nonce, and the first accepted call records it as used. Sending the same accepted ticket again returns 409 CONFIRMATION_USED and does not run the tool, so one approval runs one call. The record is kept in the one-time id store (Redis when KIRAK_REDIS_URL is set, else the database). If that store is unavailable, the call is refused with 503 CONFIRMATION_UNAVAILABLE and does not run; the person can approve again once it is back.

An approval covers one attempt: if the tool fails after an accepted approval, the approval is spent, and a new call asks the person again. Single-use approval does not make a tool idempotent: a write tool that does not require confirmation runs again whenever its call is repeated.


Kirak MCP servers support two transport modes:

Running your Kirak FastAPI app mounts all MCP servers under /mcp/<name>/. Servers are stateless and answer each request with one JSON response, not an SSE stream: a tool call returns its result when it finishes, with no progress updates or partial output on the way. Connect remote clients or IDE plugins by specifying the server URL:

{
"mcpServers": {
"kirak-support": {
"url": "https://api.yourdomain.com/mcp/support/",
"headers": {
"Authorization": "Bearer kirak_api_key_here"
}
}
}
}

For local coding tools (Claude Desktop, Cursor local MCP) running directly against your codebase:

{
"mcpServers": {
"kirak-local": {
"command": "uv",
"args": ["run", "kirak", "mcp", "run", "support"]
}
}
}