governed-mcp-agent
by pratik2607
README.md
# governed-mcp-agent
**Production security boundaries for tool-calling AI agents:** a stateless **Streamable HTTP MCP server** (OAuth 2.1 + `S256` PKCE + RFC 8707 audience binding), a **two-phase HMAC proposal-gate executor** ("the model proposes; it never commits"), a **single-source Zod / provider-safe JSON Schema DSL**, and a **deterministic governance eval suite**.
Extracted and distilled from production patterns built for real-world operational software (clean-room MIT-licensed reference implementation with zero proprietary data).
---
## Why This Exists
Most LLM agent demos fail in production for three structural reasons:
1. **Unbounded Write Authority:** Giving a model direct write tools lets hallucinations, prompt injections, or retry loops mutate ledgers and databases silently.
2. **Schema Drift Across LLM Providers:** Hand-maintaining Zod validators separately from JSON Schema tool declarations leads to runtime 400 errors (when providers reject `minimum`/`maximum`/`pattern`) and silent type mismatches.
3. **Insecure Remote MCP Plumbing:** Shipping a local `stdio` MCP script is easy; exposing a remote HTTP MCP server safely requires RFC 9728 / RFC 8414 discovery, mandatory `S256` PKCE, RFC 8707 `resource` audience validation, SHA-256 token digests, live permission re-evaluation, and metadata-only audit logs.
---
## Architecture
```mermaid
flowchart LR
Client["MCP Client (Claude / Hosted AI)"] -->|1. Unauthenticated POST /mcp| Guard["McpBearerGuard (401 + WWW-Authenticate)"]
Guard -->|2. Discover RFC 9728 / 8414| OAuth["OAuth 2.1 Server (S256 PKCE + RFC 8707)"]
OAuth -->|3. Audience-bound Access Token| Guard
Guard -->|4. SHA-256 Digest + Live RBAC + Rate Limit| MCP["Streamable HTTP MCP Server (Scoped Reads)"]
Model["In-App Agent"] -->|propose()| Catalog["FieldSpec DSL (Zod + Provider-Safe JSON Schema)"]
Catalog -->|Read Tier| ReadExec["Deterministic Read + Amount Masking"]
Catalog -->|Write / Sensitive Tier| Mint["HKDF + HMAC Stateless Proposal Envelope"]
Mint -->|Human Reviews / Edits -> Confirm| Gate["ActionGate.confirm() (Verify + Live RBAC + Step-Up + Idempotency)"]
Gate --> WriteExec["Deterministic Write Executor + Audit Log"]
```
---
## Key Engineering Trade-offs
| Pattern | Decision | Why It Matters in Production |
| --- | --- | --- |
| **Two-Phase Proposal Envelope** (`src/proposal/proposal-envelope.ts`) | Sign `(tenantId, actorId, actionId, nonce, expiresAt)` with HKDF-SHA256 + HMAC; leave proposed input unsigned | Eliminates DB proposal tables and TTL sweeps while allowing operators to edit proposed quantities/dates before clicking Confirm. `confirm()` re-parses edited args with Zod, re-checks live RBAC permissions, enforces step-up (`CONFIRM`), and deduplicates via `clientMutationId`. |
| **Single-Source FieldSpec DSL** (`src/schema/field-spec.ts`) | One declaration emits both `.zod` and provider-safe `.json` Schema | Never emits `minimum`, `maximum`, `minLength`, `pattern`, `format`, or `$ref` (which break strict LLM function-calling endpoints) while preserving bounds in prose `description` and enforcing full strictness in Zod. |
| **OAuth 2.1 + RFC 8707 + RFC 9728** (`src/mcp/oauth.ts`, `src/mcp/token-guard.ts`) | Reject `plain` PKCE at type & runtime; bind every token to explicit `resource` origin; set `WWW-Authenticate` *before* auth check | Ensures `401` responses carry discovery metadata, prevents cross-server token replay, derives discovery URLs strictly from configured origin (never untrusted `Host` headers), and stores only SHA-256 token hashes. |
| **Amount Masking & Excluded Intents** (`src/catalog/action-catalog.ts`) | Strip sensitive valuation fields when `canViewAmounts: false`; intercept payout language even on valid tools | Staff without financial permissions still get stock counts without leaking unit prices; payment-execution intents are refused deterministically before reaching a proposal card. |
---
## Quickstart
Requires **Node.js 20+**. Runs 100% locally with zero external databases or API keys required.
```bash
npm install
npm run typecheck
npm test
npm run eval
```
To start the local Streamable HTTP MCP server and OAuth 2.1 discovery endpoints:
```bash
npm run demo:server
```
---
## Project Layout
```text
src/
schema/field-spec.ts # Single-source Zod + provider-safe JSON Schema DSL
catalog/action-catalog.ts # Tiered action catalog (read / write / sensitive / excluded)
proposal/proposal-envelope.ts # HKDF-SHA256 + HMAC stateless proposal identity
proposal/action-gate.ts # Two-phase Propose -> Confirm gate with live RBAC & idempotency
mcp/token-guard.ts # SHA-256 token store, RFC 8707 check, rate limit, audit log
mcp/oauth.ts # OAuth 2.1 (S256 PKCE), RFC 9728 / 8414 discovery, refresh rotation
mcp/server.ts # Stateless Streamable HTTP MCP server (@modelcontextprotocol/sdk)
evals/cases.ts # Governance, masking, tamper, and schema-safety eval assertions
evals/runner.ts # CLI eval scorecard runner
tests/
field-spec.test.ts # Zod vs JSON Schema parity & forbidden-keyword checks
proposal-gate.test.ts # Tamper/expiry, edit-on-confirm, mid-flight revocation, idempotency
mcp-server.test.ts # End-to-end HTTP MCP + OAuth 2.1 S256 PKCE + 401/429/revocation
evals.test.ts # Eval harness assertions
```
---
## Author
**Pratik Kumar** — Anthropic Claude Certified Developer · Agentic AI & Integration Engineer
[LinkedIn](https://www.linkedin.com/in/pratikkr99) · [Credly Certification](https://www.credly.com/badges/91ee27ed-bbd9-4ff1-9ce0-f585a40ab16a)
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues