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
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:
kompile mcp-stdio --work-dir /path/to/project --profile=full --schema-level=compact- Zero ports, zero server required: With
--urlomitted,mcp-stdioruns everything locally inside the project (code index, LSP, drafts, persistent memory, semantic memory, file context, builds, processes, and offline crawl/knowledge tools underdata/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:
# 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 0disables 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 Version | Transport | Endpoints & Behavior |
|---|---|---|
2024-11-05 | Legacy SSE | GET /mcp/sse opens an SSE stream and sends an endpoint event pointing to POST /mcp/message for JSON-RPC requests |
2025-03-26 | Streamable HTTP | POST /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)
| Profile | Approximate Schema Budget | Tools Included |
|---|---|---|
minimal | ~1,000 tokens (5 tools) | read, file_context, grep, glob, list |
explore | ~2,500 tokens | Read-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 tokens | File 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 catalog | All registered Kompile tools + installed extensions |
custom | User-defined | Loaded 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_toolstells 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:
- Context & containment binding: Attaches
McpSessionTracker,CoordinationStateManager,TranscriptLogScope, andSubagentDelegationGuard(enforcingKOMPILE_SUBAGENT_DEPTHand delegated child restrictions). - Deterministic Enforcer (
EnforcerToolCallGuard): Runs fail-closed< 1 mschecks before execution — Shell Mandate, Build/Script/Lane/Draft Enforcers, read-before-edit, and/tmpredirects. - Optional LLM Gateway & Resource Gate:
CliToolGatewayInterceptorevaluates configured gateway rules (ALLOW | BLOCK | REWRITE).HighMemoryToolCallGuardapplies a fail-closed resource admission check on high-memory tools so parallel agents cannot OOM the host.PermissionServicechecks tool permissions andedit_coordinatorfile locks.
- Execution & async detachment (
AsyncToolExecutor): Runs built-inCliToolimplementations, Java SPI / declarative JSON tools (ToolExtensionLoader), and process extensions (ProcessExtensionMcpBridge). Delegation tools background by default; other tools can opt in with_background=true. - 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:textThe agent then pages or greps only the slice it needs via[Full result cached as ref:ID — N chars, M lines]fetch_resultorfetch_result_batch(offset,limit,pattern) without flooding its context window. - Audit, indexing & automatic milestones:
McpToolAuditLoggerwrites structured records totool_call_catalog.McpToolProgressLoggerstreams activity to<repo>/.kompile/logs/mcp-activity.log.StdioInvocationAccountingattributes invocation counts and usage.- File mutations notify
FileWatcherService,BackgroundIndexService, anddiff_indexautomatically; authorized test runs triggerTestMilestoneCapture. SkillRegistryserves Kompile skills natively over MCP'sprompts/listandprompts/getendpoints.
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 Agent | Injection Mechanism | What Kompile Preserves / Enforces |
|---|---|---|
| Claude Code | Project .mcp.json + PreToolUse / Stop hooks | Preserves existing custom servers in .mcp.json; blocks shell substitutes before execution |
| Codex | Per-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 guard | Eagerly loads core redirect tools (mcp_kompile_*), lazy-loads the rest via call_mcp_tool, blocks direct ~/.gemini/antigravity-cli/brain access |
| OpenCode | OPENCODE_CONFIG_CONTENT ({"*":"deny","kompile_*":"allow"} for workers) | Isolates subagent workers strictly onto Kompile's MCP tool surface |
| Standalone MCP client | Add 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.
Related guides
- MCP Integration & Pipelines — Offline crawl pipelines, connectors, and model/pipeline MCP contracts
- MCP Tool Reference — Complete catalog of MCP tools by category
- Custom MCP Servers — Connecting third-party stdio and HTTP MCP servers into Kompile
- Why Kompile Is Opinionated — The Enforcer, Judge, and Evidence planes running inside every MCP call
- Security & Permission Model — Minimal permission defaults,
PermissionService,ToolPermissionService, and secret hygiene - Agent Skill (
SKILL.md) — Teaching agents how to navigate Kompile's MCP tools