Zero-Dependency Submodular Knapsack, Dependency Graph Cycle Detection, Sandboxed Execution, and On-Demand Repository Synthesis.
Apex MCP Foundry transforms any local software repository portfolio into an on-demand, operator-governed Model Context Protocol (MCP) execution fabric.
Standard MCP gateway deployments suffer from severe scaling cliffs:
- Schema Explosion & Context Rot: Upfront loading of hundreds of tool schemas consumes 50,000 to 100,000+ prompt tokens, degrading LLM reasoning accuracy and inflating inference costs.
- The KV-Cache Invalidation Paradox: Naive dynamic tool filtering varies prompt prefixes turn-by-turn, thrashing the LLM inference engine's prefix KV-cache and multiplying Time-to-First-Token (TTFT) by 4x–8x.
- Multi-Process Daemon Exhaustion: Spawning separate OS processes for hundreds of repositories consumes tens of gigabytes of host RAM and introduces 250ms–700ms cold-start IPC overhead.
- Unbounded Dependency Cycles: Circular tool invocations cause hung agent sessions.
Apex MCP Foundry solves these bottlenecks from first principles:
- Submodular Budgeted Knapsack: Solves the NP-hard capability selection problem under context token ceilings, achieving >55% to 95% token reduction.
- Canonical Radix Prefix Aligner: Guarantees deterministic lexicographic prefix ordering of selected tools, preserving prompt KV-cache reuse.
-
Source-Grounded Dependency Graph & Tarjan SCC: Polynomial-time
$\mathcal{O}(V + E)$ cycle detection across imports and call sites with confidence annotations. -
Sandboxed In-Memory Adapter Runner: Executes approved deterministic repository functions in a restricted execution namespace with taint tracking in
$<25\ \mu\text{s}$ , eliminating the need to spawn hundreds of persistent daemon processes. -
Multi-Transport Gateway: Native support for standard MCP
stdioas well as authenticated HTTP POST (/rpc) and Server-Sent Events (/sse) streaming. - Zero External Dependencies: Pure Python 3.10+ standard library.
flowchart TD
subgraph ClientLayer["Frontier Agent Clients"]
CLIENT["Claude Desktop / Cursor / Windsurf / Multi-Agent Swarms"]
end
subgraph FoundryGateway["Apex MCP Foundry Core"]
direction TB
BOOTSTRAP["Bootstrap Surface<br>(search_capabilities, call_capability)"]
subgraph OptimizationCore["I. Submodular Optimization & Cache Alignment"]
KNAPSACK["Submodular Knapsack Selector<br>(1 - 1/e Greedy & Exact Branch-and-Bound)"]
RADIX["Canonical Radix Prefix Aligner<br>(Deterministic Lexicographic Trie Sorting)"]
end
subgraph AnalysisAndGraph["II. Source-Grounded Static & Graph Analysis"]
AST_IDX["AST Declaration Reflector<br>(Docstrings, Type Annotations, Parameters)"]
TARJAN["Dependency Graph & Tarjan SCC<br>(Cycle Detection & Confidence Labels)"]
end
subgraph ExecutionSandbox["III. Sandboxed Execution Adapter"]
TAINT["Lattice Taint & Injection Validator<br>(Blocks Prohibited Imports & Eval)"]
MICRO["Micro-Sandbox Execution Scope<br>(Memory Bounded, Time-Restricted <25µs)"]
end
end
subgraph Repositories["Repository Ecosystem"]
R1["Repository A (NP-Hard Kernels)"]
R2["Repository B (FinTech Rails)"]
RN["Repository N (Swarm Agents)"]
end
CLIENT <==>|"stdio / HTTP POST / SSE"| BOOTSTRAP
BOOTSTRAP --> KNAPSACK
KNAPSACK --> RADIX
BOOTSTRAP --> AST_IDX
AST_IDX --> TARJAN
BOOTSTRAP --> TAINT
TAINT --> MICRO
MICRO <==>|"In-Memory Invocation"| Repositories
Given a set of
- For small problem instances (
$N \le 20$ ), an exact branch-and-bound search evaluates the global optimum. - For large instance spaces (
$N > 20$ ), a greedy approximation selects the element maximizing the marginal density ratio:
guaranteeing a theoretical
To prevent KV-cache thrashing across dynamic turns, the selected capability subset
Any shared tool prefixes between consecutive turns remain byte-identical, preserving the prompt KV-cache across inference engines (vLLM, SGLang, Anthropic Prompt Caching).
Module and capability dependency graphs
A root vertex with
The Foundry exposes a small bootstrap interface (search_capabilities and call_capability). Inside call_capability, requests are routed to approved handlers configured in .mcp-foundry/capabilities.json:
| Handler | Execution Mode | Description |
|---|---|---|
repo.overview |
Read-Only Static | Inventories languages, source files, and symbol counts. |
repo.search_symbols |
Read-Only Static | Searches indexed declarations and docstrings without executing code. |
repo.get_symbol |
Read-Only Static | Returns declaration metadata, parameters, line numbers, and docstrings. |
repo.dependency_graph |
Read-Only Static | Generates source-grounded import/call graphs with cycle detection. |
repo.budgeted_selection |
Micro-Optimization | Solves submodular Knapsack selection under a requested token ceiling. |
repo.execute_adapter |
Sandboxed Execution | Runs approved deterministic Python functions with safety and timeout bounds. |
python3 -m apex_mcp_foundry inspect /path/to/repository# Create a draft manifest for operator review
python3 -m apex_mcp_foundry init /path/to/repository
# Or auto-approve all handlers immediately
python3 -m apex_mcp_foundry init /path/to/repository --approve-allReview the manifest at .mcp-foundry/capabilities.json:
{
"schema_version": 1,
"repository_id": "sample-repo",
"status": "approved",
"approved_handlers": [
"repo.overview",
"repo.search_symbols",
"repo.get_symbol",
"repo.dependency_graph",
"repo.budgeted_selection",
"repo.execute_adapter"
]
}python3 -m apex_mcp_foundry graph /path/to/repositorypython3 -m apex_mcp_foundry benchmark /path/to/repository --iterations 50Scan an entire parent directory containing hundreds of repositories:
python3 -m apex_mcp_foundry scan-all /path/to/projects/ --approvepython3 -m apex_mcp_foundry serve /path/to/repo1 /path/to/repo2python3 -m apex_mcp_foundry serve /path/to/repo1 \
--transport http \
--host 127.0.0.1 \
--port 8080 \
--token SECRET_BEARER_TOKENClient configuration for Claude Desktop / Cursor:
{
"mcpServers": {
"apex-mcp-foundry": {
"command": "python3",
"args": ["-m", "apex_mcp_foundry", "serve", "/absolute/path/to/repository"],
"env": {
"PYTHONPATH": "/absolute/path/to/apex-mcp-foundry"
}
}
}
}Executing the automated benchmark harness (docs/evaluation-plan.md) yields the following performance telemetry:
================================================================================
APEX MCP FOUNDRY: EMPIRICAL BENCHMARK & EVALUATION TELEMETRY
================================================================================
[*] Repetitions per Subsystem: 50 runs
[*] Static Exposure Baseline: 2,500 tokens
[*] Budgeted Schema Knapsack: 322 tokens (87.1% reduction)
[*] Prefix Cache Retention: 94.4% KV-Cache prefix stability
--------------------------------------------------------------------------------
FOUNDRY SUBSYSTEM | KEY METRIC | LATENCY (p50 / p95)
--------------------------------------------------------------------------------
1. Submodular Schema Knapsack | 87.1% token cut | 180.98 µs / 221.80 µs
2. Dependency Tarjan SCC | 0 cycles detected | 11.34 ms / 25.51 ms
3. Sandboxed Execution | Zero-process in-memory | 1.94 µs / 3.81 µs
--------------------------------------------------------------------------------
[+] VERIFICATION: All empirical measurements meet evaluation-plan.md criteria.
- Zero-Process Architecture: Sandboxed adapters execute inside memory-bounded Python namespaces without spawning OS processes, preventing process table exhaustion and socket exhaustion.
- AST Safety Verification: Prohibits dangerous imports (
subprocess,socket,ctypes,shlex) and dynamic evaluation (eval,exec). - Taint Tracking: Input arguments are recursively inspected for injection payloads and shell escapes before reaching callable targets.
- Local Manifest Boundary: Manifests are re-read on discovery and invocation; revoking a handler takes effect immediately without server restart.
- Transport Security: Network HTTP/SSE endpoints require constant-time Bearer token verification (
hmac.compare_digest) and enforce strict payload size ceilings.
# Run all unit tests (12/12 passing in <0.03s)
python3 -m unittest discover -s tests -v
# Compile-time syntax verification
python3 -m py_compile apex_mcp_foundry/*.py tests/*.py