Files
leocrm/docs/api-documentation.md
T
Agent Zero 3d9b76cea4
Check Cross-Plugin Imports / check (push) Has been cancelled
feat(E): Unified Search — 24 Tasks complete
- SPIKE-E: FTS+Vector+Permission benchmark on 10k records (all <30ms)
- E-PROV: supports_fts/vector/rag/graph capability flags on all providers
- E-FTS/VEC: All 11 providers refactored to BaseSearchProvider with permission filtering
- E-PERM: Over-fetch strategy for vector+permission (15x faster than ANY() filter)
- E-FUSE: rrf_fusion_multi() for N-way RRF over FTS+Vector+RAG+Graph
- E-LLM: Query understanding cleaned up to use central llm_complete()
- E-CHUNK: Document chunking module + document_chunks table with HNSW index
- E-EMB: Chunk embedding ARQ jobs (index_file_chunks, reindex_chunks)
- E-RAG: RAG retrieval via FileSearchProvider.search_rag()
- E-GRAPH: GraphRAG BFS traversal via GraphRAGSearchProvider.search_graph()
- E-IX-EVT: Auto-indexing via outbox events + delete/cleanup handlers
- E-IX-RE: Batch reindex with progress tracking + reindex_all job
- E-DATA-LIFE: Lifecycle module (remove/rebuild/restore/correct) + API endpoints
- E-K-MEM: AgentMemorySearchProvider
- E-P-AI: AIChatSearchProvider
- E-P-WF: WorkflowSearchProvider
- E-P-COMM: ConversationSearchProvider verified (already on BaseSearchProvider)
- E-API: Filter params (date_from/to, tags, sort) + /facets endpoint
- E-TOOL: unified_search AI tool registered in ToolRegistry
- E-MCP: Search tool in MCP server with normal RBAC/tenant checks
- E-UI-CMD: CommandPalette (Cmd+K) with debounced search + recent searches
- E-UI-FAC: SearchFacets, SearchResultCard, SavedSearches components
- E-TEST: 40 new tests in test_unified_search_phase_e.py (105 total green)
- E-DOC: api-documentation.md, plugin-development-guide.md, test-strategy.md updated

105 tests passing, TypeScript clean.
2026-08-14 01:34:58 +02:00

23 KiB
Raw Blame History

LeoCRM API Documentation

Auto-generated from FastAPI route enumeration. 295 endpoints across 30 tag groups.

Overview

LeoCRM exposes a RESTful API under /api/v1/. All endpoints (except /api/v1/health and /api/v1/auth/login) require authentication via session cookie.

  • Swagger UI: /docs
  • ReDoc: /redoc
  • OpenAPI JSON: /openapi.json

Authentication

  1. Call POST /api/v1/auth/login with {email, password} → receives session cookie.
  2. Include the session cookie in all subsequent requests.
  3. Call POST /api/v1/auth/logout to invalidate the session.

Multi-Tenancy

All data is tenant-scoped. The tenant context is derived from the authenticated session. Users with multiple tenants can switch via POST /api/v1/auth/switch-tenant.

Error Format

{"detail": "Error message", "code": "error_code", "fields": {"field": "error"}}

Pagination

List endpoints use page (1-based) and page_size (1-100) query parameters. Responses include total, page, page_size, and items.


Core Routes

health (1 endpoint)

Method Path Description
GET /api/v1/health Health check — no auth required. Returns status + DB/Redis/storage/worker checks. Response model: HealthResponse

metrics (1 endpoint)

Method Path Description
GET /api/v1/metrics Prometheus metrics endpoint.

auth (7 endpoints)

Method Path Description
POST /api/v1/auth/login Login with email+password. Sets session cookie. Request: LoginRequest, Response: AuthResponse
POST /api/v1/auth/logout Logout — invalidate session, clear cookie. Response: MessageResponse
GET /api/v1/auth/me Get current user + active tenant. Response: AuthResponse
GET /api/v1/auth/me/permissions Get resolved permissions for current user.
POST /api/v1/auth/switch-tenant Switch active tenant. Request: SwitchTenantRequest
POST /api/v1/auth/password-reset/request Request password reset email. Request: PasswordResetRequest
POST /api/v1/auth/password-reset/confirm Confirm password reset with token. Request: PasswordResetConfirm

users (5 endpoints)

Method Path Description
GET /api/v1/users List users with pagination. Response: PaginatedUsers
POST /api/v1/users Create a new user (admin only). Request: UserCreate, Response: UserResponse
GET /api/v1/users/{user_id} Get a single user. Response: UserResponse
PATCH /api/v1/users/{user_id} Update user fields. Request: UserUpdate
DELETE /api/v1/users/{user_id} Delete/deactivate a user.

roles (5 endpoints)

Method Path Description
GET /api/v1/roles List all roles.
POST /api/v1/roles Create a custom role.
GET /api/v1/roles/permissions Get all available permission definitions.
PATCH /api/v1/roles/{role_id} Update role permissions.
DELETE /api/v1/roles/{role_id} Delete a custom role.

groups (9 endpoints)

Method Path Description
GET /api/v1/groups List all groups.
POST /api/v1/groups Create a new group.
GET /api/v1/groups/{group_id} Get a single group.
PATCH /api/v1/groups/{group_id} Update group.
DELETE /api/v1/groups/{group_id} Delete group.
GET /api/v1/groups/{group_id}/members List group members.
POST /api/v1/groups/{group_id}/members Add member to group.
DELETE /api/v1/groups/{group_id}/members/{user_id} Remove member from group.
GET /api/v1/groups/user/{user_id} Get groups for a user.

tenants (4 endpoints)

Method Path Description
GET /api/v1/tenants List tenants for current user.
POST /api/v1/tenants Create a new tenant.
GET /api/v1/tenants/{tenant_id}/users List users in a tenant.
POST /api/v1/tenants/{tenant_id}/users Add user to tenant.

notifications (6 endpoints)

Method Path Description
GET /api/v1/notifications List notifications with pagination.
PATCH /api/v1/notifications/{notification_id}/read Mark notification as read.
GET /api/v1/notifications/unread-count Get unread count. Response: UnreadCountResponse
GET /api/v1/notifications/types List notification types.
GET /api/v1/notifications/preferences Get notification preferences.
PATCH /api/v1/notifications/preferences/{type_key} Update notification preference.

contacts (10 endpoints)

Method Path Description
GET /api/v1/contacts List contacts with pagination, FTS search, type/folder filter, sorting.
POST /api/v1/contacts Create a contact (company or person).
GET /api/v1/contacts/export Stream contacts as CSV.
GET /api/v1/contacts/{contact_id} Get a single contact.
PUT /api/v1/contacts/{contact_id} Update contact.
DELETE /api/v1/contacts/{contact_id} Soft-delete contact.
GET /api/v1/contacts/{contact_id}/persons List contact persons.
POST /api/v1/contacts/{contact_id}/persons Add contact person.
PUT /api/v1/contacts/{contact_id}/persons/{person_id} Update contact person.
DELETE /api/v1/contacts/{contact_id}/persons/{person_id} Delete contact person.

contact-folders (6 endpoints)

Method Path Description
GET /api/v1/contact-folders List contact folders.
POST /api/v1/contact-folders Create a folder.
PUT /api/v1/contact-folders/{folder_id} Update folder.
DELETE /api/v1/contact-folders/{folder_id} Delete folder.
PUT /api/v1/contact-folders/{folder_id}/reorder Reorder folder.
PUT /api/v1/contact-folders/contacts/{contact_id}/move Move contact to folder.

entity-history (3 endpoints)

Method Path Description
GET /api/v1/entity-history/{entity_type}/{entity_id} Get change history for an entity.
POST /api/v1/entity-history/undo/{entity_type}/{entity_id} Undo last change.
POST /api/v1/entity-history/restore Restore entity to a specific version.

import-export (2 endpoints)

Method Path Description
POST /api/v1/import Import data from file.
POST /api/v1/import/preview Preview import data.

plugins (11 endpoints)

Method Path Description
GET /api/v1/plugins List all plugins.
GET /api/v1/plugins/manifest Get plugin manifest schema.
GET /api/v1/plugins/active-manifests Get manifests of all active plugins.
POST /api/v1/plugins/install-url Install plugin from URL.
POST /api/v1/plugins/upload Upload and install plugin ZIP.
POST /api/v1/plugins/{name}/install Install a discovered plugin.
POST /api/v1/plugins/{name}/activate Activate a plugin.
POST /api/v1/plugins/{name}/deactivate Deactivate a plugin.
GET /api/v1/plugins/{name}/config Get plugin configuration.
PATCH /api/v1/plugins/{name}/config Update plugin configuration.
DELETE /api/v1/plugins/{name} Uninstall a plugin.

ai-copilot (3 endpoints)

Method Path Description
POST /api/v1/ai/copilot/query Ask the AI copilot a question.
POST /api/v1/ai/copilot/execute Execute an AI copilot action.
GET /api/v1/ai/copilot/history Get copilot conversation history.

workflows (10 endpoints)

Method Path Description
GET /api/v1/workflows List workflow definitions.
POST /api/v1/workflows Create a workflow.
GET /api/v1/workflows/{workflow_id} Get a workflow.
PATCH /api/v1/workflows/{workflow_id} Update a workflow.
DELETE /api/v1/workflows/{workflow_id} Delete a workflow.
POST /api/v1/workflows/{workflow_id}/instances Start a workflow instance.
GET /api/v1/workflows/instances List workflow instances.
GET /api/v1/workflows/instances/{instance_id} Get a workflow instance.
POST /api/v1/workflows/instances/{instance_id}/advance Advance workflow to next step.
POST /api/v1/workflows/instances/{instance_id}/cancel Cancel a workflow instance.

user-preferences (4 endpoints)

Method Path Description
GET /api/v1/user/preferences Get all user preferences.
GET /api/v1/user/preferences/{key} Get a specific preference.
PUT /api/v1/user/preferences/{key} Set a preference.
DELETE /api/v1/user/preferences/{key} Delete a preference.

currencies (4 endpoints)

Method Path Description
GET /api/v1/currencies List currencies.
POST /api/v1/currencies Create a currency.
PATCH /api/v1/currencies/{currency_id} Update a currency.
DELETE /api/v1/currencies/{currency_id} Delete a currency.

taxes (4 endpoints)

Method Path Description
GET /api/v1/taxes List tax rates.
POST /api/v1/taxes Create a tax rate.
PATCH /api/v1/taxes/{tax_id} Update a tax rate.
DELETE /api/v1/taxes/{tax_id} Delete a tax rate.

sequences (4 endpoints)

Method Path Description
GET /api/v1/sequences List number sequences.
POST /api/v1/sequences Create a sequence.
PATCH /api/v1/sequences/{sequence_id} Update a sequence.
DELETE /api/v1/sequences/{sequence_id} Delete a sequence.

system-settings (2 endpoints)

Method Path Description
GET /api/v1/system-settings Get system settings. Response: SystemSettingsResponse
PUT /api/v1/system-settings Upsert system settings. Request: SystemSettingsUpsert, Response: SystemSettingsResponse

attachments (4 endpoints)

Method Path Description
GET /api/v1/attachments List attachments.
POST /api/v1/attachments Upload an attachment.
GET /api/v1/attachments/{attachment_id} Download an attachment.
DELETE /api/v1/attachments/{attachment_id} Delete an attachment.

addresses (4 endpoints)

Method Path Description
GET /api/v1/addresses List addresses.
POST /api/v1/addresses Create an address.
PATCH /api/v1/addresses/{address_id} Update an address.
DELETE /api/v1/addresses/{address_id} Delete an address.

audit (1 endpoint)

Method Path Description
GET /api/v1/audit-log Query audit log entries.

Plugin Routes

automation (Automation & Agents)

Agent Builder, Automation Builder, Cron-Scheduler, Agent Runner.

Method Path Description
GET/POST /api/v1/automation/* Automation definitions, triggers, execution logs.

agents (AI Agents)

Method Path Description
GET/POST/PUT/DELETE /api/v1/agents/* AI agent CRUD and runner endpoints.

dms (Document Management System)

19 endpoints for file and folder management.

Method Path Description
GET /api/v1/dms/files List files.
POST /api/v1/dms/files/upload Upload a file.
GET /api/v1/dms/files/{file_id} Get file metadata.
GET /api/v1/dms/files/{file_id}/preview Preview a file.
POST /api/v1/dms/files/{file_id}/share Share a file.
GET/POST /api/v1/dms/folders Folder CRUD.
GET /api/v1/dms/search Search documents.
GET /api/v1/dms/shared-with-me Files shared with current user.

mail (Email Integration)

50 endpoints for IMAP/SMTP email management.

Method Path Description
GET/POST /api/v1/mail/accounts Email account management.
GET/POST /api/v1/mail/folders Folder management.
GET /api/v1/mail/{mail_id} Get a specific email.
POST /api/v1/mail/send Send an email.
POST /api/v1/mail/drafts Save draft.
GET /api/v1/mail/search Search emails.
GET /api/v1/mail/threads List email threads.
POST /api/v1/mail/pgp/keys PGP key management.
POST /api/v1/mail/rules Mail filter rules.
POST /api/v1/mail/vacation Vacation responder.

calendar (Calendar & Scheduling)

21 endpoints for calendar management.

Method Path Description
GET/POST /api/v1/calendar/entries Calendar entry CRUD.
GET/POST /api/v1/calendars Calendar CRUD.
GET /api/v1/calendar/kanban Kanban board view.
POST /api/v1/calendar/import Import ICS.
GET /api/v1/calendar/{calendar_id}/ics-feed ICS feed.
POST /api/v1/resources Resource booking.

Hybrid cross-entity search (PostgreSQL FTS + pgvector) with KI query understanding, RRF rank fusion, visibility filtering, and field-level RBAC.

Method Path Description
GET /api/v1/search Hybrid search via query params (same as POST).
POST /api/v1/search Hybrid search with KI query understanding.
GET /api/v1/search/suggest Autocomplete suggestions (FTS prefix).
POST /api/v1/search/similar Find similar entities across all types by embedding.
POST /api/v1/search/reindex Trigger reindexing of entity types (admin).
GET /api/v1/search/providers List active search providers + capability flags.
POST /api/v1/search/providers/{entity_type}/toggle Toggle a provider on/off (admin).
GET /api/v1/search/stats Search index statistics (indexed/pending per table).
GET /api/v1/search/facets Available facets (entity types, tags, date ranges).
POST /api/v1/search/rebuild/{entity_type}/{entity_id} Rebuild index for a single entity (admin).
POST /api/v1/search/purge/{entity_type}/{entity_id} Purge entity from index (admin, GDPR).

MCP: Unified search is also exposed as an MCP tool named search (category search, permission search:read) via the MCP server plugin (app/plugins/builtins/mcp_server/tool_definitions.py).

Search Request (POST /api/v1/search)

{
  "query": "Max Mustermann",
  "entity_types": ["contact", "mail"],
  "limit": 20,
  "offset": 0,
  "date_from": "2026-01-01",
  "date_to": "2026-12-31",
  "tags": ["vip", "partner"],
  "sort": "relevance"
}
Field Type Default Description
query string Search query (1500 chars, required).
entity_types list[string] all Restrict search to these entity types.
limit int 20 Max results (1100).
offset int 0 Pagination offset.
date_from string null ISO date YYYY-MM-DD — filter by created_at/updated_at >= date_from.
date_to string null ISO date YYYY-MM-DD — filter by created_at/updated_at <= date_to.
tags list[string] null Filter results by tags (comma-separated on entities).
sort string relevance Sort order: relevance, date, name.

Search Response

{
  "query": "Max Mustermann",
  "normalized_query": "max mustermann",
  "results": [
    {
      "entity_type": "contact",
      "entity_id": "uuid",
      "title": "Max Mustermann",
      "snippet": "max@example.com",
      "score": 0.95,
      "data": {"type": "person"}
    }
  ],
  "facets": {"types": {"contact": 1}},
  "summary": "1 Ergebnis",
  "suggestions": []
}
Field Type Description
query string Original query.
normalized_query string KI-normalized query.
results list[SearchResult] Ranked results (entity_type, entity_id, title, snippet, score, data).
facets object KI-generated facet counts.
summary string Human-readable summary.
suggestions list[string] Suggested follow-up filters.

GET /api/v1/search Query Params

Same fields as the POST body, passed as query parameters: q (required), entity_types (comma-separated), limit, offset, date_from, date_to, tags (comma-separated), sort.

GET /api/v1/search/suggest

Query params: q (required, 1200), limit (default 10, 150). Returns {"suggestions": ["..."]}.

POST /api/v1/search/similar

Body: {"entity_type": "contact", "entity_id": "uuid", "limit": 5}. Returns {"similar": {"mail": [SearchResult...], ...}}.

POST /api/v1/search/reindex

Body: {"entity_types": ["contact"], "include_chunks": true}. Returns {"status": "ok", "entity_types": [...], "include_chunks": true, "job_ids": [...]}. Requires search:admin.

GET /api/v1/search/providers

Returns a list of providers: {"entity_type", "plugin_name", "is_active", "supports_fts", "supports_vector", "supports_rag", "supports_graph"}.

GET /api/v1/search/facets

Returns {"entity_types": [...], "tags": [...], "date_ranges": {"contacts": {"min": "...", "max": "..."}, ...}}.

GET /api/v1/search/stats

Returns per-table {"total", "indexed", "pending"} plus recent_logs (last 10 index log entries).

POST /api/v1/search/rebuild/{entity_type}/{entity_id} / /purge/{entity_type}/{entity_id}

Admin-only. Rebuild regenerates the embedding + TSV; purge sets embedding/TSV to NULL (and removes chunks for files). Returns {"status": "ok"|"failed", "entity_type", "entity_id", "message"}.

reports (Report Generator)

8 endpoints for report templates and generation.

Method Path Description
GET/POST /api/v1/reports/templates Report template CRUD.
POST /api/v1/reports/generate Generate a report.
GET /api/v1/reports/{report_id} Get report status.
GET /api/v1/reports/{report_id}/download Download generated report.

4 endpoints for connecting entities.

Method Path Description
GET /api/v1/contacts/{contact_id}/files Get files linked to a contact.
POST/DELETE /api/v1/dms/files/{file_id}/link Link/unlink a file to an entity.
GET /api/v1/dms/files/{file_id}/links Get all links for a file.

kommunikation (Unified Messaging)

23 endpoints for conversations and messages.

Method Path Description
GET/POST /api/v1/comm/conversations Conversation CRUD.
GET/POST /api/v1/comm/conversations/{id}/messages Message list and send.
POST /api/v1/comm/conversations/{id}/participants Manage participants.
POST /api/v1/comm/messages/{id}/reactions Message reactions.
GET /api/v1/comm/miniapps List mini-apps.

ai-proactive (Proactive AI)

8 endpoints for AI insights and suggestions.

Method Path Description
GET /api/v1/ai-proactive/suggestions Get AI suggestions.
GET /api/v1/ai-proactive/suggestions/stream SSE stream of suggestions.
POST /api/v1/ai-proactive/suggestions/{id}/act Act on a suggestion.
POST /api/v1/ai-proactive/suggestions/{id}/dismiss Dismiss a suggestion.
GET/PUT /api/v1/ai-proactive/settings Proactive AI settings.

ai-assistant (AI Assistant)

30 endpoints for AI chat sessions, providers, models, and tools.

Method Path Description
GET/POST /api/v1/ai/sessions Chat session CRUD.
GET /api/v1/ai/sessions/{id}/messages List messages in session.
POST /api/v1/ai/sessions/{id}/stream Stream chat completion (SSE).
GET/POST /api/v1/ai/providers AI provider CRUD.
GET/POST /api/v1/ai/models AI model CRUD.
GET/POST /api/v1/ai/presets Preset CRUD.
GET /api/v1/ai/tools List available AI tools.

ai-ui-control (AI UI Control)

WebSocket and REST endpoints for AI-driven UI control.

Method Path Description
WebSocket /ws/ai-ui-control Real-time UI command stream.
POST /api/v1/ai-ui-control/command Send UI command from AI agent.

tags (Tag Management)

8 endpoints for tag CRUD and assignment.

Method Path Description
GET/POST /api/v1/tags Tag CRUD.
POST/DELETE /api/v1/tags/assign Assign/remove tag from entity.
POST /api/v1/tags/bulk-assign Bulk assign tags.
GET /api/v1/tags/{tag_id}/entities Get entities with a tag.

permissions (Permission Management)

5 endpoints for file-level permissions and share links.

Method Path Description
GET/POST /api/v1/dms/files/{file_id}/permissions File permission CRUD.
POST /api/v1/dms/files/{file_id}/share-link Create public share link.
DELETE /api/v1/dms/share-links/{link_id} Revoke share link.

public-share (Public Sharing)

2 endpoints — no auth required, token-based access.

Method Path Description
GET /api/public/share/{token} Access shared resource via token.
POST /api/public/share/{token} Interact with shared resource.

Schema Examples

LoginRequest

{"email": "admin@leocrm.local", "password": "secure-password"}

AuthResponse

{
  "user_id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "admin@leocrm.local",
  "name": "Admin User",
  "role": "admin",
  "tenant_id": "550e8400-e29b-41d4-a716-446655440001",
  "tenant_name": "Acme GmbH"
}

UserCreate

{
  "email": "user@leocrm.local",
  "name": "John Doe",
  "password": "secure-password",
  "role": "viewer",
  "is_active": true
}

UserResponse

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "user@leocrm.local",
  "name": "John Doe",
  "role": "viewer",
  "is_active": true,
  "tenant_id": "550e8400-e29b-41d4-a716-446655440001"
}

HealthResponse

{"status": "healthy", "version": "1.0.0"}

UnreadCountResponse

{"count": 5}

KI Integration Notes

For AI Agents

  1. Health Check: Run python scripts/ai_health_check.py --base-url <url> --token <token> before and after updates.
  2. Deploy: Use python scripts/ai_deploy.py --dry-run to preview, then python scripts/ai_deploy.py for real deployment.
  3. OpenAPI: The full OpenAPI spec is available at /openapi.json — use it for dynamic endpoint discovery.
  4. Safe Methods: GET endpoints are safe to probe. POST/PUT/DELETE require careful payload construction.
  5. Session Auth: AI agents should call POST /api/v1/auth/login first, then use the returned cookie for all subsequent requests.