Skip to content

Core Concepts

github-actions[bot] edited this page Aug 3, 2026 · 3 revisions

Core Concepts

Referenced Files in This Document

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion
  10. Appendices

Introduction

This document explains the core concepts of Kairos MCP, focusing on:

  • Model Context Protocol (MCP) standards and how they are implemented
  • Memory store architecture with vector embeddings and semantic search using Qdrant
  • Workflow orchestration patterns for stateful execution
  • Tool registration mechanisms and the adapter pattern for external service integration
  • Key terms such as protocols, adapters, artifacts, spaces, and workflows
  • Data flow between components and architectural decisions

The goal is to provide a clear mental model of how Kairos orchestrates tools, persists state, indexes content for retrieval, and exposes capabilities via MCP and HTTP interfaces.

Project Structure

Kairos is organized into layers:

  • Entry points and bootstrap logic initialize configuration, services, and routes
  • HTTP server exposes REST and MCP endpoints with authentication and metrics
  • Tools implement business operations and workflow steps
  • Services encapsulate memory, embedding, Qdrant, Redis, and OIDC integrations
  • Utilities provide cross-cutting concerns like logging, error handling, and tenant context
graph TB
subgraph "Entry Points"
A["index.ts"]
B["server.ts"]
C["bootstrap.ts"]
end
subgraph "HTTP Layer"
D["http-server.ts"]
E["http-mcp-handler.ts"]
F["http-api-routes.ts"]
G["http-auth-middleware.ts"]
H["bearer-validate.ts"]
end
subgraph "Tools"
I["tools/*"]
J["forward-register.ts"]
K["mcp-contract-match.ts"]
end
subgraph "Services"
L["memory-store.ts"]
M["qdrant-memory-store.ts"]
N["embedding-service.ts"]
O["redis-cache.ts"]
P["oidc-state-store.ts"]
end
subgraph "Utilities"
Q["tenant-context.ts"]
R["structured-logger.ts"]
S["global-error-handlers.ts"]
end
A --> B --> C --> D
D --> E
D --> F
F --> G --> H
F --> I
I --> J
I --> K
I --> L
L --> M
L --> N
L --> O
L --> P
D --> Q
D --> R
D --> S
Loading

Diagram sources

Section sources

Core Components

  • MCP Host and Handler: Exposes MCP JSON-RPC endpoints, validates requests, and dispatches tool calls.
  • Tools Registry: Centralized registration of MCP tools and their schemas, including forward activation flows.
  • Memory Store Abstraction: Encapsulates persistence and retrieval of memory items, artifacts, and metadata.
  • Vector Search with Qdrant: Embeddings generated by an embedding service are stored and queried semantically.
  • Stateful Workflows: Orchestrated sequences of steps with persistent state and traceability.
  • Authentication and Tenancy: OIDC-based auth, bearer token validation, and per-tenant scoping.
  • Observability: Metrics, structured logging, audit events, and health endpoints.

Key responsibilities:

  • Protocols define the shape of interactions and tool contracts.
  • Adapters bridge external systems into the memory store and tool layer.
  • Artifacts represent versioned content units consumed or produced by workflows.
  • Spaces partition data and permissions across tenants or domains.
  • Workflows describe multi-step processes with state transitions and rewards.

Section sources

Architecture Overview

High-level flow from client to storage and back:

sequenceDiagram
participant Client as "Client"
participant HTTP as "HTTP Server"
participant Auth as "Auth Middleware"
participant MCP as "MCP Handler"
participant Tools as "Tools Registry"
participant Mem as "Memory Store"
participant Qdrant as "Qdrant Service"
participant Embed as "Embedding Service"
participant Cache as "Redis Cache"
Client->>HTTP : "HTTP Request"
HTTP->>Auth : "Validate Bearer Token"
Auth-->>HTTP : "Authenticated Context"
HTTP->>MCP : "JSON-RPC Call"
MCP->>Tools : "Resolve Tool + Schema"
Tools->>Mem : "Read/Write Memory"
Mem->>Qdrant : "Vector Search / Upsert"
Qdrant-->>Mem : "Results"
Mem->>Embed : "Generate Embeddings"
Embed-->>Mem : "Vectors"
Mem->>Cache : "Cache Results"
Cache-->>Mem : "Cached Data"
Tools-->>MCP : "Tool Result"
MCP-->>HTTP : "JSON-RPC Response"
HTTP-->>Client : "Response"
Loading

Diagram sources

Detailed Component Analysis

MCP Standards and Tool Registration

  • MCP Contract Matching: Validates input schemas against declared tool contracts and supports loose schema modes for flexibility.
  • Tool Input Teaching: Provides guidance and teaching payloads to clients based on tool schemas.
  • Forward Tool Error Handling: Normalizes errors returned by tools to consistent MCP responses.
  • Forward Registration: Central registry that maps tool names to implementations and schemas, enabling dynamic discovery.
flowchart TD
Start(["Incoming MCP Call"]) --> Match["Match Tool Contract"]
Match --> Validate["Validate Inputs"]
Validate --> |Valid| Dispatch["Dispatch to Tool"]
Validate --> |Invalid| Teach["Return Teaching Payload"]
Dispatch --> Execute["Execute Tool Logic"]
Execute --> HandleErr{"Error?"}
HandleErr --> |Yes| Normalize["Normalize Error"]
HandleErr --> |No| Return["Return Result"]
Normalize --> Return
Teach --> End(["Response"])
Return --> End
Loading

Diagram sources

Section sources

Memory Store Architecture and Vector Embeddings

  • Memory Store Abstraction: Defines CRUD operations for memory items, artifacts, and metadata.
  • Qdrant Integration: Stores vectors and performs similarity search; manages collections and point mappings.
  • Embedding Service: Converts text to vectors for indexing and retrieval.
  • Title Similarity Search: Optimized search over titles and metadata fields.
  • Activation Patterns: Backfills and structures activation-related search fields.
classDiagram
class MemoryStore {
+create(item)
+read(id)
+update(id, item)
+delete(id)
+search(query)
+upsertArtifact(artifact)
}
class QdrantMemoryStore {
+connect()
+createCollection(name)
+upsertPoint(collection, point)
+queryPoints(collection, query)
+listCollections()
}
class EmbeddingService {
+embed(text)
+batchEmbed(texts)
}
class RedisCache {
+get(key)
+set(key, value, ttl)
+invalidate(pattern)
}
MemoryStore --> QdrantMemoryStore : "uses"
MemoryStore --> EmbeddingService : "generates vectors"
MemoryStore --> RedisCache : "caches results"
Loading

Diagram sources

Section sources

Adapter Pattern for External Service Integration

Adapters allow plugging in different storage backends and external systems while keeping a uniform interface. The builder constructs adapters from configuration, and helpers validate and normalize inputs.

classDiagram
class StoreAdapter {
+initialize(config)
+write(data)
+read(id)
+search(query)
}
class AdapterBuilder {
+build(type, config)
+registerAdapter(type, impl)
}
class DefaultHandler {
+handle(request)
}
class HeaderHandler {
+processHeaders(req)
}
StoreAdapter <|-- DefaultHandler
StoreAdapter <|-- HeaderHandler
AdapterBuilder --> StoreAdapter : "constructs"
Loading

Diagram sources

Section sources

Semantic Search Capabilities Using Qdrant

Semantic search combines embeddings with metadata filters and title similarity. The pipeline includes:

  • Query parsing and normalization
  • Vector generation via embedding service
  • Qdrant collection selection and filtering
  • Result ranking and caching
flowchart TD
QStart(["Search Request"]) --> Parse["Parse Query & Filters"]
Parse --> Embed["Generate Embedding"]
Embed --> SelectColl["Select Collection by Space/Tenant"]
SelectColl --> QdrantQuery["Run Vector + Metadata Query"]
QdrantQuery --> Rank["Rank & Merge Results"]
Rank --> Cache["Update Cache"]
Cache --> QEnd(["Return Ranked Results"])
Loading

Diagram sources

Section sources

Stateful Workflow Orchestration

Workflows are composed of tools and steps with persistent state and traces. The forward tool orchestrates step-by-step execution, while activate prepares initial state and views.

sequenceDiagram
participant Client as "Client"
participant MCP as "MCP Handler"
participant Act as "Activate Tool"
participant Fwd as "Forward Tool"
participant Trace as "Execution Trace Store"
participant Mem as "Memory Store"
Client->>MCP : "Call 'activate'"
MCP->>Act : "Initialize Workflow"
Act->>Mem : "Create Session & State"
Act-->>MCP : "Session ID + Initial View"
MCP-->>Client : "Activation Result"
Client->>MCP : "Call 'forward' with session"
MCP->>Fwd : "Advance Step"
Fwd->>Trace : "Record Step & Outputs"
Fwd->>Mem : "Persist State"
Fwd-->>MCP : "Next Action + View"
MCP-->>Client : "Step Result"
Loading

Diagram sources

Section sources

Tool Registration Mechanisms

Tools are registered centrally and exposed via MCP and HTTP APIs. Each tool defines its schema and behavior, and the registry resolves them at runtime.

flowchart TD
RegStart(["Bootstrapping"]) --> Register["Register Tools"]
Register --> Schema["Attach JSON Schema"]
Schema --> Discover["Expose via MCP List Tools"]
Discover --> Invoke["Invoke Tool by Name"]
Invoke --> Exec["Execute Tool Logic"]
Exec --> Resp["Return Result"]
Loading

Diagram sources

Section sources

Key Terms

  • Protocols: Formal definitions of tool contracts, schemas, and interaction patterns.
  • Adapters: Pluggable components implementing a common interface to integrate external systems.
  • Artifacts: Versioned content units with metadata, used as inputs or outputs in workflows.
  • Spaces: Logical partitions for data isolation and access control, often aligned with tenants or projects.
  • Workflows: Multi-step processes orchestrated by tools with persistent state and observability.

[No sources needed since this section doesn't analyze specific files]

Dependency Analysis

Component relationships and coupling:

graph LR
HTTP["HTTP Server"] --> Auth["Auth Middleware"]
HTTP --> MCPH["MCP Handler"]
MCPH --> Tools["Tools Registry"]
Tools --> Mem["Memory Store"]
Mem --> Qdrant["Qdrant Service"]
Mem --> Embed["Embedding Service"]
Mem --> Cache["Redis Cache"]
HTTP --> OIDC["OIDC State Store"]
HTTP --> Metrics["Metrics Server"]
HTTP --> Health["Health Routes"]
HTTP --> UI["UI Static"]
Loading

Diagram sources

Section sources

Performance Considerations

  • Embedding Generation: Batch embeddings where possible and cache results to reduce latency and cost.
  • Vector Search: Use appropriate collection strategies and filters to minimize payload sizes and improve recall.
  • Caching: Leverage Redis for hot paths like search results and activation states.
  • Concurrency Limits: Apply rate limiting and concurrency controls to protect downstream services.
  • Structured Logging: Keep logs concise and avoid heavy payloads to reduce overhead.

[No sources needed since this section provides general guidance]

Troubleshooting Guide

Common issues and diagnostics:

  • Authentication Failures: Check bearer token validation and OIDC redirects/callbacks.
  • MCP Contract Mismatches: Review tool schema matching and loose input modes.
  • Qdrant Connectivity: Verify collection existence and vector dimensions.
  • Embedding Errors: Inspect provider health and retry policies.
  • Workflow Stalls: Inspect execution traces and persisted state for stuck sessions.

Operational utilities:

  • Audit Events: Correlate MCP actions with audit summaries.
  • Global Error Handlers: Ensure consistent error propagation and user-friendly messages.
  • Health Endpoints: Confirm service readiness and dependencies.

Section sources

Conclusion

Kairos MCP integrates MCP standards with a robust memory store backed by Qdrant for semantic search, and orchestrates stateful workflows through a centralized tool registry. The adapter pattern enables flexible integrations, while authentication, tenancy, and observability ensure secure and maintainable operations. Understanding these core concepts helps developers extend capabilities, troubleshoot effectively, and design scalable workflows.

[No sources needed since this section summarizes without analyzing specific files]

Appendices

Tool Catalog Reference

  • Activate: Initializes workflows and returns initial views.
  • Forward: Advances workflow steps and returns next actions.
  • Search: Performs semantic and metadata-driven searches.
  • Train: Ingests and indexes content with embeddings.
  • Tune: Adjusts models or parameters based on feedback.
  • Reward: Records evaluations and propagates signals.
  • Export/Dump: Exports artifacts and telemetry.
  • Delete/Update: Manages lifecycle of resources.
  • Next: Determines canonical next actions based on protocol state.
  • Spaces: Lists and manages spaces for data isolation.

Section sources

Artifact and URI Utilities

  • Artifact cataloging and MIME inference support diverse content types.
  • URI builders and relative path resolution simplify artifact references.

Section sources

Protocol Validation and Structure

  • Protocol structure validation ensures consistency across tools and workflows.
  • Activation pattern payloads and fields guide search and display.

Section sources

Storage Initialization and Methods

  • Store initialization sets up collections and default handlers.
  • Store methods abstract common operations for memory and artifacts.

Section sources

HTTP API and Resources

  • Well-known endpoints and health checks expose operational status.
  • Export download routes serve artifacts securely.
  • UI static assets and offerings enhance developer experience.

Section sources

CLI and Stdio Interfaces

  • CLI commands wrap core functionality for automation and scripting.
  • Stdio server enables process-based invocation.

Section sources

KAIROS MCP

Clone this wiki locally