# API Reference
Complete API documentation for the MCP Database System HTTP endpoints.
## Base URL
```
http://localhost:8000
```
## Authentication
Currently, the API operates without authentication in development mode. For production deployment, configure API keys in the security settings.
## Content Type
All endpoints expect and return `application/json` unless otherwise specified.
## Smart Search API
### Smart Search
Intelligent search that automatically determines the best strategy.
**Endpoint:** `POST /api/database/smart-search`
**Request Body:**
```json
{
"question": "How many active users do we have?",
"include_schema": true,
"max_sql_queries": 3,
"max_semantic_results": 10
}
```
**Parameters:**
- `question` (string, required): Natural language question
- `include_schema` (boolean, optional): Include schema info in response (default: true)
- `max_sql_queries` (integer, optional): Maximum SQL queries to execute (default: 3)
- `max_semantic_results` (integer, optional): Maximum semantic results (default: 10)
**Response:**
```json
{
"success": true,
"question": "How many active users do we have?",
"strategy_used": "sql_only",
"response": "# User Count\n\n**Result: 1,245**\n\nThe database contains 1,245 active users.",
"metadata": {
"sql_queries_executed": 1,
"semantic_results_found": 0,
"confidence": 0.9,
"reasoning": "Question appears to be asking for specific data"
}
}
```
**Example cURL:**
```bash
curl -X POST http://localhost:8000/api/database/smart-search \
-H "Content-Type: application/json" \
-d '{"question": "Show me user statistics"}'
```
## Schema API
### Get Schema Information
Retrieve database schema information.
**Endpoint:** `POST /api/database/schema`
**Request Body:**
```json
{
"include_sample_data": false
}
```
**Parameters:**
- `include_sample_data` (boolean, optional): Include sample data from tables (default: false)
**Response:**
```json
{
"success": true,
"summary": "Database contains 5 tables with 12 relationships",
"table_count": 5,
"relationship_count": 12,
"tables": [
{
"name": "users",
"columns": [
{
"name": "id",
"type": "INTEGER",
"nullable": false
},
{
"name": "email",
"type": "VARCHAR(255)",
"nullable": false
}
],
"row_count": 1245,
"primary_keys": ["id"],
"foreign_keys": 0
}
]
}
```
### Find Relevant Tables
Find tables relevant to a question.
**Endpoint:** `POST /api/database/tables/find-relevant`
**Request Body:**
```json
{
"question": "user authentication data"
}
```
**Response:**
```json
{
"success": true,
"question": "user authentication data",
"relevant_tables": ["users", "auth_tokens", "user_sessions"],
"count": 3
}
```
### Get Table Details
Get detailed information about a specific table.
**Endpoint:** `GET /api/database/tables/{table_name}`
**Response:**
```json
{
"success": true,
"table_name": "users",
"details": {
"columns": [...],
"indexes": [...],
"constraints": [...],
"row_count": 1245
}
}
```
## SQL API
### Execute SQL
Execute a SQL query safely.
**Endpoint:** `POST /api/database/sql/execute`
**Request Body:**
```json
{
"sql": "SELECT COUNT(*) as user_count FROM users WHERE active = true",
"limit": true
}
```
**Parameters:**
- `sql` (string, required): SQL query to execute
- `limit` (boolean, optional): Apply safety row limits (default: true)
**Response:**
```json
{
"success": true,
"data": [
{
"user_count": 1245
}
],
"rows_affected": 0,
"execution_time": 0.045,
"query": "SELECT COUNT(*) as user_count FROM users WHERE active = true",
"error": null
}
```
**Safety Features:**
- Automatic LIMIT injection for SELECT queries
- Table existence validation
- Forbidden pattern detection
- Query timeout enforcement
### Validate SQL
Validate SQL without executing.
**Endpoint:** `POST /api/database/sql/validate`
**Request Body:**
```json
{
"sql": "SELECT * FROM nonexistent_table"
}
```
**Response:**
```json
{
"valid": false,
"error": "Table 'nonexistent_table' does not exist"
}
```
## Semantic Search API
### Semantic Search
Perform semantic/vector search.
**Endpoint:** `POST /api/database/semantic/search`
**Request Body:**
```json
{
"query": "user authentication methods",
"limit": 10,
"table_filter": "users",
"fk_filter": null
}
```
**Parameters:**
- `query` (string, required): Search query
- `limit` (integer, optional): Maximum results (default: 10)
- `table_filter` (string, optional): Filter by table name
- `fk_filter` (string, optional): Filter by foreign key relationship
**Response:**
```json
{
"success": true,
"query": "user authentication methods",
"results": [
{
"content": "User authentication is handled through email/password or OAuth providers",
"score": 0.85,
"metadata": {
"source": "documentation",
"table": "users"
}
}
],
"count": 1
}
```
## System API
### Health Check
Check system health and available models.
**Endpoint:** `GET /health`
**Response:**
```json
{
"status": "healthy",
"message": "MCP HTTP Bridge is running",
"available_models": ["mistral:latest", "llama2:latest"]
}
```
### Get Capabilities
Get information about search system capabilities.
**Endpoint:** `GET /api/database/capabilities`
**Response:**
```json
{
"success": true,
"capabilities": {
"sql_search": {
"available": true,
"capabilities": ["data_queries", "aggregations", "filtering", "joins"]
},
"semantic_search": {
"available": true,
"capabilities": ["concept_search", "similarity_matching", "text_fallback"]
},
"schema_info": {
"tables_available": 5
}
}
}
```
### Suggest Questions
Get suggested questions based on available data.
**Endpoint:** `GET /api/database/suggest-questions`
**Query Parameters:**
- `topic` (string, optional): Focus suggestions on a specific topic
**Response:**
```json
{
"success": true,
"suggestions": [
"How many records are in users?",
"Show me the latest users records",
"What information do we store about users?",
"What tables are available in the database?"
],
"count": 4
}
```
## Chat API (Legacy)
### Chat
Basic chat with LLM.
**Endpoint:** `POST /api/chat`
**Request Body:**
```json
{
"message": "Hello, how can you help me?",
"model": "mistral:latest",
"temperature": 0.7,
"max_tokens": 1000
}
```
### Chat Stream
Streaming chat responses.
**Endpoint:** `POST /api/chat/stream`
**Response:** Server-Sent Events (SSE) stream
### Conversation Chat
Chat with memory.
**Endpoint:** `POST /api/conversation/chat`
**Request Body:**
```json
{
"message": "What tables do we have?",
"conversation_id": "user-123-session",
"model": "mistral:latest",
"include_context": true,
"context_limit": 10
}
```
## Error Responses
All endpoints return consistent error responses:
```json
{
"success": false,
"error": "Description of the error",
"details": {
"error_code": "DATABASE_CONNECTION_ERROR",
"timestamp": "2024-01-15T10:30:00Z"
}
}
```
**Common Error Codes:**
- `DATABASE_CONNECTION_ERROR`: Cannot connect to database
- `INVALID_SQL`: SQL query validation failed
- `LLM_API_ERROR`: LLM provider API error
- `CONFIGURATION_ERROR`: System configuration issue
- `RATE_LIMIT_EXCEEDED`: Too many requests
## Rate Limiting
Default rate limits:
- **Development:** 60 requests/minute
- **Production:** 100 requests/minute
Rate limit headers:
- `X-RateLimit-Limit`: Requests allowed per window
- `X-RateLimit-Remaining`: Requests remaining in window
- `X-RateLimit-Reset`: Time when window resets
## CORS
CORS is enabled for development with allowed origins:
- `http://localhost:3000` (React)
- `http://localhost:5173` (Vite)
- `http://localhost:8080` (Vue/other)
## WebSocket Support
WebSocket endpoints for real-time features:
### Smart Search Stream
**Endpoint:** `ws://localhost:8000/ws/search`
**Message Format:**
```json
{
"type": "search",
"data": {
"question": "How many users?",
"stream": true
}
}
```
## SDK Examples
### JavaScript/TypeScript
```typescript
class MCPClient {
constructor(baseURL: string = 'http://localhost:8000') {
this.baseURL = baseURL;
}
async smartSearch(question: string): Promise<SearchResponse> {
const response = await fetch(`${this.baseURL}/api/database/smart-search`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question })
});
return response.json();
}
async getSchema(): Promise<SchemaResponse> {
const response = await fetch(`${this.baseURL}/api/database/schema`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({})
});
return response.json();
}
}
```
### Python
```python
import httpx
class MCPClient:
def __init__(self, base_url: str = "http://localhost:8000"):
self.base_url = base_url
self.client = httpx.Client()
def smart_search(self, question: str) -> dict:
response = self.client.post(
f"{self.base_url}/api/database/smart-search",
json={"question": question}
)
return response.json()
def get_schema(self) -> dict:
response = self.client.post(
f"{self.base_url}/api/database/schema",
json={}
)
return response.json()
```
## OpenAPI/Swagger
Interactive API documentation available at:
- **Development:** `http://localhost:8000/docs`
- **ReDoc:** `http://localhost:8000/redoc`