All my work / AI infrastructure · by Ravindra Sawant

Toolgate

Model Context Protocol gateway: curated tools, signed identity, tenant policy, approvals, audit.

Python 3.11+ · asyncio · mcp SDK 1.25 (protocol 2025-11-25) · PyJWT · jsonschema 683 lines of core code source on GitHub ↗ CI status

4/4 core requirements 5 tests passing 3/3 benchmark targets

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 mcp SDK 1.25, protocol 2025-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

ReqPriRequirement Proven byStatus
FR-01P0Two trusted stdio upstreams via official SDK; pinned protocol revision; handle disconnect/init failureT01, T04pass
FR-02P0Discover tools with pagination, namespace aliases, validate + cache descriptors, one downstream sessionT01, T03pass
FR-03P0Signed tokens (issuer/audience/expiry/scopes); filter discovery and invocation by identity + tenantT02pass
FR-04P0Route authorized calls; schema/size/deadline/concurrency limits; structured errors; audit eventsT03, T04pass
FR-05P1Per-tool approval for side effects; cache refresh/TTL; per-upstream circuit breakerT05, T04pass
TestWhat it provesResult
T01Two upstreams expose the same tool name: unique aliases, pagination, correct routing, pinned protocolpass
T02Tenant A cannot list/call tenant B tools; forged/expired/wrong-audience tokens rejected; hidden alias denied before executionpass
T03Schema violation, oversized/too-deep args, oversized and malformed results, unknown/hidden tools; correlated sanitized auditpass
T04Slow tool timeout with bounded read retry, upstream crash, circuit open + half-open probe recovery, permits returnedpass
T05Approval bound to principal/tool/args digest, single use, no self-approval; side-effect timeout -> unknown outcome, no retrypass

Benchmark

Target (hypothesis from the spec)GoalActual
p95 gateway-only overhead < 20 ms at 10 concurrent clients (provisional)< 20 ms0.102 msmet
100% denial of negative auth fixtures50/5050/50met
audit covers every invocation1.01.0met
  • gateway_p95_ms@10 = 0.102
  • upstream_p95_ms@10 = 13.661
  • calls_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   # bench

More 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

Distributed systems

  • Quorum Deterministic Raft consensus simulator with fault injection and an always-on invariant checker
  • Tandem Collaborative text editor on a sequence CRDT: offline edits, any delivery order, always converges
  • Burrow Minimal Linux container runtime in Go: namespaces, pivot_root, cgroup v2 limits

← See all my work: apps, ML/AI and systems