Skip to content

How the Kompile MCP Server Works ​

Kompile's MCP server is more than a thin JSON-RPC wrapper around tools — it is the execution boundary that enforces Kompile's guardrails, resource gates, result caching, and telemetry whether tools are called from Kompile Standard Chat, the Web Harness, or an external coding CLI (Claude Code, Codex, Antigravity agy, OpenCode, or custom MCP clients).


Architecture at a glance ​

mermaid
flowchart LR
    CLIENTS["MCP Clients\n(Claude Code • Codex • agy •\nOpenCode • Custom Clients)"] --> TRANS{"Transport Layer"}
    TRANS -->|"stdio JSON-RPC\n(default)"| STDIO["kompile mcp-stdio\n(In-Process CLI MCP Server)"]
    TRANS -->|"Unix socket (--daemon)\n~/.kompile/runtime/kompile.sock"| DAEMON["kompile serve\n(Shared Multiplexed Daemon)"]
    TRANS -->|"SSE (2024-11-05) &\nStreamable HTTP (2025-03-26)"| HTTP["kompile-app-mcp\n(/mcp/sse • /mcp/message)"]

    STDIO --> PIPE["Tool Execution Pipeline\n1. EnforcerToolCallGuard (fail-closed)\n2. CliToolGatewayInterceptor & HighMemoryGuard\n3. Sync / AsyncToolExecutor + Extensions\n4. ToolResultReferenceCache (ref:ID handles)\n5. Audit Log • Diff Index • Test Milestones"]
    DAEMON --> PIPE
    HTTP --> PIPE2["Spring MCP Pipeline\nScopedMcpCapabilityService •\nToolPermissionService •\nCompressingToolCallbackProvider"]

Three server modes & transports ​

1. In-process Stdio (kompile mcp-stdio, default) ​

Each agent launches Kompile as a child process over standard JSON-RPC stdio:

bash
kompile mcp-stdio --work-dir /path/to/project --profile=full --schema-level=compact
  • Zero ports, zero server required: With --url omitted, mcp-stdio runs everything locally inside the project (code index, LSP, drafts, persistent memory, semantic memory, file context, builds, processes, and offline crawl/knowledge tools under data/crawls).
  • Optional server bridge: Pass --url http://localhost:8080 (and/or --graph-url) to route distributed RAG, graph, and crawl tools to a running Kompile server while keeping local file/code/LSP tools fast on disk.
  • Session diagnostic isolation: --transcript-id <id> binds diagnostics, activity logs, and automatic test milestone attribution back to the parent chat session.

2. Shared Unix-Socket Daemon (kompile serve + --daemon) ​

When running many concurrent external agent sessions on one machine, launching a separate JVM per agent wastes memory (~120 MB JVM overhead + ~100 MB duplicated classloading per process).

Passing --daemon to kompile mcp-stdio bridges stdio cleanly onto a single shared daemon listening on ~/.kompile/runtime/kompile.sock:

bash
# Auto-managed on demand, or inspect/tune directly:
kompile serve --idle-timeout 30 --max-sessions 10 --detach
kompile daemon
  • Protected by an exclusive file lock (daemonLockFile) so only one daemon runs per Kompile home.
  • Auto-shuts down after 30 minutes with zero active sessions (--idle-timeout 0 disables idle shutdown).
  • Keeps warm caches, shared coordination state, and multiplexed connections across sessions.

3. Server HTTP / SSE & Streamable HTTP (kompile-app-mcp) ​

Inside a full Kompile server (:8080), McpSseController (/mcp) supports both official MCP HTTP transports simultaneously:

Protocol VersionTransportEndpoints & Behavior
2024-11-05Legacy SSEGET /mcp/sse opens an SSE stream and sends an endpoint event pointing to POST /mcp/message for JSON-RPC requests
2025-03-26Streamable HTTPPOST /mcp/sse initializes a session (returns Mcp-Session-Id header) and streams per-request responses (202 Accepted for notifications); GET /mcp/sse with Mcp-Session-Id opens the server notification stream; DELETE /mcp/sse terminates the session

Server-side MCP adds ScopedMcpCapabilityService (per-persona/scope capability filtering), ToolPermissionService, McpActionLogService, and CompressingToolCallbackProvider (domain-aware RagResponseCompressor, KnowledgeGraphResponseCompressor, and FilesystemResponseCompressor).


Profiles, schema compaction & progressive tool exposure ​

Sending 100+ verbose tool schemas on every turn wastes thousands of prompt tokens and degrades smaller models. Kompile solves this at three levels:

1. Tool profiles (--profile) ​

ProfileApproximate Schema BudgetTools Included
minimal~1,000 tokens (5 tools)read, file_context, grep, glob, list
explore~2,500 tokensRead-only I/O + read_batch, grep_batch, explore, code_search, local_code_index, code_graph, graph_search, graph_reasoning_query, fetch_result*
core~3,000 tokensFile I/O, search, edits, patch/edit_patch, draft/draft_batch, bash, todowrite/todoread/progress, memory, incident, websearch/webfetch, mcp_tool_search/mcp_tool_call
full (default)Full catalogAll registered Kompile tools + installed extensions
customUser-definedLoaded from a custom profile allowlist file

2. Schema optimization (--schema-level) ​

Controls how aggressively JSON Schema descriptions are compacted before being sent in tools/list:

  • compact (default) — shortest parameter descriptions and trimmed metadata to keep context lean across any model size.
  • aggressive, moderate, none — progressively fuller inline parameter documentation.

3. Dynamic / progressive group activation (DynamicToolManager + activate_tools) ​

In dynamic mode, Kompile starts with a compact working surface and exposes the activate_tools meta-tool (list, describe, activate) so the agent unlocks domain groups (code, web, workflow, delegation, graph, integrations, etc.) only when needed:

  • Idempotent + loop-guarded: Re-activating an already-active group returns an honest confirmation without inflating progress. Repeated redundant calls escalate after 3 identical / 6 total attempts and hard-block after 5 identical / 10 total attempts so a confused model can never loop on tool activation.
  • In full static stdio mode (!isDynamicMode()), activate_tools tells the model up front that the full catalog is already active so it doesn't waste turns trying to unlock tools.

Inside every tools/call: the middleware pipeline ​

Every MCP tool invocation in kompile mcp-stdio passes through the exact same enforcement and observability stack as native Kompile chat:

  1. Context & containment binding: Attaches McpSessionTracker, CoordinationStateManager, TranscriptLogScope, and SubagentDelegationGuard (enforcing KOMPILE_SUBAGENT_DEPTH and delegated child restrictions).
  2. Deterministic Enforcer (EnforcerToolCallGuard): Runs fail-closed < 1 ms checks before execution — Shell Mandate, Build/Script/Lane/Draft Enforcers, read-before-edit, and /tmp redirects.
  3. Optional LLM Gateway & Resource Gate:
    • CliToolGatewayInterceptor evaluates configured gateway rules (ALLOW | BLOCK | REWRITE).
    • HighMemoryToolCallGuard applies a fail-closed resource admission check on high-memory tools so parallel agents cannot OOM the host.
    • PermissionService checks tool permissions and edit_coordinator file locks.
  4. Execution & async detachment (AsyncToolExecutor): Runs built-in CliTool implementations, Java SPI / declarative JSON tools (ToolExtensionLoader), and process extensions (ProcessExtensionMcpBridge). Delegation tools background by default; other tools can opt in with _background=true.
  5. Large-result reference caching (ToolResultReferenceCache): When a tool output exceeds the inline size cap, the full payload is cached and the client receives a compact handle:
    text
    [Full result cached as ref:ID — N chars, M lines]
    The agent then pages or greps only the slice it needs via fetch_result or fetch_result_batch (offset, limit, pattern) without flooding its context window.
  6. Audit, indexing & automatic milestones:
    • McpToolAuditLogger writes structured records to tool_call_catalog.
    • McpToolProgressLogger streams activity to <repo>/.kompile/logs/mcp-activity.log.
    • StdioInvocationAccounting attributes invocation counts and usage.
    • File mutations notify FileWatcherService, BackgroundIndexService, and diff_index automatically; authorized test runs trigger TestMilestoneCapture.
    • SkillRegistry serves Kompile skills natively over MCP's prompts/list and prompts/get endpoints.

How Kompile wires its MCP server into external agents (McpToolInjection) ​

When you run external coding CLIs inside Kompile (or register kompile mcp-stdio standalone), McpToolInjection adapts cleanly to each vendor's configuration contract without clobbering your existing setup:

External AgentInjection MechanismWhat Kompile Preserves / Enforces
Claude CodeProject .mcp.json + PreToolUse / Stop hooksPreserves existing custom servers in .mcp.json; blocks shell substitutes before execution
CodexPer-launch -c command-line overrides (codexCommandLineOverrides)Never rewrites global ~/.codex/config.toml; separate repos never collide
Antigravity (agy)Shared ~/.gemini/config/mcp_config.json + agy-native-tools guardEagerly loads core redirect tools (mcp_kompile_*), lazy-loads the rest via call_mcp_tool, blocks direct ~/.gemini/antigravity-cli/brain access
OpenCodeOPENCODE_CONFIG_CONTENT ({"*":"deny","kompile_*":"allow"} for workers)Isolates subagent workers strictly onto Kompile's MCP tool surface
Standalone MCP clientAdd kompile mcp-stdio --work-dir <repo> (or http://localhost:8080/mcp/sse)Full Kompile tool, memory, LSP, draft, and Enforcer surface

Kompile also acts in reverse as an MCP client & aggregator (McpStdioClient, McpStreamableHttpClient, McpBundleToolLoader, ExternalMcpServerManager), bringing any third-party MCP servers configured in ~/.kompile/config/mcp-servers.json into Kompile chat — see Custom MCP Servers.


Released under the Apache-2.0 License.