All my work / AI infrastructure · by Ravindra Sawant
Toolgate
Model Context Protocol gateway: curated tools, signed identity, tenant policy, approvals, audit.
Verified 2026-11-28; CI re-runs the acceptance tests on every push.
The problem
Enterprise agents need one place to discover, authorize and audit tools across many providers. This Model Context Protocol gateway, built on the official MCP SDK, exposes a curated namespaced tool set behind signed identities and tenant policies.
What I found
- Hidden and cross-tenant tools return exactly the same error as non-existent ones, so tool names cannot be probed.
- Approvals bind principal + tenant + tool + argument digest and are single-use; changing one argument after approval is denied.
- Gateway overhead was 0.07 ms p95 at 10 concurrent clients, and 50/50 negative-auth calls were denied and audited.
Architecture
client ─(HTTP POST /mcp + Bearer JWT | stdio + trusted token)─► identity verifier (PyJWT HS256: iss/aud/exp/iat)
─► JSON-RPC adapter (initialize, ping, tools/list, tools/call)
─► registry snapshot (alias = <upstream>.<tool>, TTL cache) ─► policy (tenant allowlist ∧ scope) — deny by default
─► arg gate (size, depth, JSON Schema) ─► approval gate (writes: principal+tenant+alias+args digest, single use)
─► circuit breaker ─► semaphores (global + per upstream) ─► upstream ClientSession.call_tool (deadline)
─► response filter (text only, size cap) ─► audit (every allow/deny, config version, args digest only)
- Upstreams: each stdio session (official
mcpSDK 1.25, protocol2025-11-25) lives in its own background task; transport errors mark it dead and the next call reconnects (subject to the breaker). Executables come only from the operator config (command: fixture→ fixed script + args) — never from requests. - Discovery: follows
nextCursor(≤ 20 pages), drops tools not curated in config (e.g.admin_dump) and invalid descriptors, checks alias collisions, publishes the new route map atomically. - Errors: protocol errors (unknown tool, invalid params, unauthorized, approval required, unavailable) are JSON-RPC errors; tool failures are results with
isError: true. Hidden and unknown tools return the same public error. - Side effects: never retried; timeouts return
unknown_outcome. Read-only calls get one bounded retry.
Requirements → tests
| Req | Pri | Requirement | Proven by | Status |
|---|---|---|---|---|
| FR-01 | P0 | Two trusted stdio upstreams via official SDK; pinned protocol revision; handle disconnect/init failure | T01, T04 | pass |
| FR-02 | P0 | Discover tools with pagination, namespace aliases, validate + cache descriptors, one downstream session | T01, T03 | pass |
| FR-03 | P0 | Signed tokens (issuer/audience/expiry/scopes); filter discovery and invocation by identity + tenant | T02 | pass |
| FR-04 | P0 | Route authorized calls; schema/size/deadline/concurrency limits; structured errors; audit events | T03, T04 | pass |
| FR-05 | P1 | Per-tool approval for side effects; cache refresh/TTL; per-upstream circuit breaker | T05, T04 | pass |
| Test | What it proves | Result |
|---|---|---|
| T01 | Two upstreams expose the same tool name: unique aliases, pagination, correct routing, pinned protocol | pass |
| T02 | Tenant A cannot list/call tenant B tools; forged/expired/wrong-audience tokens rejected; hidden alias denied before execution | pass |
| T03 | Schema violation, oversized/too-deep args, oversized and malformed results, unknown/hidden tools; correlated sanitized audit | pass |
| T04 | Slow tool timeout with bounded read retry, upstream crash, circuit open + half-open probe recovery, permits returned | pass |
| T05 | Approval bound to principal/tool/args digest, single use, no self-approval; side-effect timeout -> unknown outcome, no retry | pass |
Benchmark
| Target (hypothesis from the spec) | Goal | Actual | |
|---|---|---|---|
| p95 gateway-only overhead < 20 ms at 10 concurrent clients (provisional) | < 20 ms | 0.102 ms | met |
| 100% denial of negative auth fixtures | 50/50 | 50/50 | met |
| audit covers every invocation | 1.0 | 1.0 | met |
gateway_p95_ms@10= 0.102upstream_p95_ms@10= 13.661calls_per_s@10= 1163
quick run · 2026-11-28T23:57:30+00:00
Design questions
What does MCP standardize?
How clients discover and call tools (and other capabilities) from providers over JSON-RPC. The runtime/gateway still owns authorization and execution policy.
Why filter both discovery and invocation?
Hiding a tool from tools/list is not security - a client can guess a name. Invocation must independently enforce authorization (and return the same error as for unknown tools).
What is the confused-deputy risk?
A gateway with broad upstream credentials acting on behalf of a less-privileged caller. Bind actions to the validated identity, scope and tenant and do not forward client tokens indiscriminately.
How do you handle upstream failures?
Deadlines, bounded retries only for read-only calls, circuit breakers with half-open probes, and explicit unknown-outcome results for ambiguous side effects.
What would production need?
A real OAuth/OIDC resource server, secrets vault for upstream credentials, Streamable HTTP, private networking, multi-instance registry and tested client/protocol compatibility.
Limitations
- Tools only (no prompts/resources/sampling)
- Local HS256 fixture tokens, not an OAuth server
- HTTP transport is a minimal loopback JSON-RPC endpoint, not Streamable HTTP
Run it
git clone https://github.com/ravirs/toolgate.git && cd toolgate
pip install -r requirements.txt
PYTHONPATH=src python -m mcpgw demo # demo
PYTHONPATH=src python -m pytest -q # test
PYTHONPATH=src python benchmarks/bench.py --quick # benchMore systems I've built from scratch
Storage & data systems
- Strata LSM-tree key-value storage engine: WAL, SSTables with Bloom filters, atomic manifest, compaction
- Tidelog Kafka-style durable partitioned log broker: CRC'd records, offsets, generation-fenced consumer groups
- Floe Iceberg-style table format: immutable Parquet, manifests, snapshots, time travel, compare-and-swap commits
- Flint Spark-style batch engine: lazy lineage, stage planning, shuffles, broadcast and salted skew joins
- Watermark Event-time stream processor: windows, watermarks, lateness, exactly-once checkpoints
- Warden Data governance catalog: explainable grants, row filters, column masks, lineage impact
- SnapshotDB MVCC transaction engine: snapshot isolation, the write-skew anomaly, a serializable mode
AI infrastructure
- Nearline HNSW-style vector search index from scratch, measured against exact search
- KVPager Paged KV cache with copy-on-write forks and prefix reuse (PagedAttention-style)
- Batchwise LLM inference scheduler simulator: static vs continuous vs chunked-prefill batching
- Steadyhand Durable AI agent runtime: allowlisted tools, approvals, budgets, crash recovery, replay