# mcpx gateway — Full Specification & JSON-RPC Protocol

## 1. Protocol Architecture
- Protocol: Model Context Protocol (MCP) over JSON-RPC 2.0 (HTTP POST / SSE)
- Transport: HTTPS / Server-Sent Events
- Base URL: `https://mcpx.harrykrauze.com/mcp/sse`
- REST Endpoint: `https://mcpx.harrykrauze.com/tools/execute`
- Auth Header: `Authorization: Bearer mcpx_live_<token>`
- Author & Publisher: Harry Krauze (https://harrykrauze.com/#harry-krauze)
- Operating System: Cloudflare Workers (V8 Isolate Edge)

## 2. Core Security & Pre-Flight Gate Architecture
- Zero-dependency remote HTTP MCP server generation on Cloudflare Workers (`generate_mcp_server`)
- V8 isolate sandboxing for untrusted MCP tool execution
- Sub-300ms System One prompt-injection and blast-radius pre-flight gate (`gemini-decision-1` / `gemini-decision-1-001`)
- Deterministic Zero-PII filter stripping secrets, tokens, and PII before execution
- Native x402 micropayment protocol and Creem.io credit top-up integration

### 2.1 System 1 Decision Gate (`gemini-decision-1`)
mcpx incorporates a sub-300ms probabilistic pre-flight classification gate powered by Google DeepMind's `gemini-decision-1` (`gemini-decision-1-001`):
- **Evaluated Axes:**
  - `is_prompt_injection`: Detects adversarial jailbreaks, system prompt overrides, delimiter attacks, and hidden instructions.
  - `has_residual_secret`: Scans for leaked credentials, bearer tokens, private keys, and passwords.
  - `intent_route`: Classifies intent into canonical domains (`compute`, `financial`, `system`, `sandbox`, `query`).
  - `execution_risk`: Calculates blast-radius risk level (`low`, `medium`, `high`, `critical`).
  - `needs_clarification`: Identifies ambiguous payloads or missing required parameters.
- **Enforcement Actions (`GateAction`):**
  - `ALLOW`: Payload is safe; proceeds directly to tool execution.
  - `SANITIZE`: PII or residual secrets are redacted in-memory before forwarding.
  - `CHALLENGE`: High-risk or ambiguous requests prompt for explicit confirmation.
  - `BLOCK`: Immediate rejection (HTTP 403 / JSON-RPC error -32600) with security event logging.
- **Telemetry & Caching:** Pre-flight gate decisions are hashed and cached in Cloudflare KV (`MCPX_TELEMETRY_KV`) and recorded in Cloudflare Analytics Engine with zero personal data.

### 2.2 FAQ & Architecture Affirmations
- **Q: How does mcpx deploy remote MCP servers?**
  A: mcpx compiles and deploys stateless, HTTP-accessible Model Context Protocol (MCP) servers directly onto Cloudflare Workers V8 isolates with sub-millisecond cold starts and built-in security guardrails.
- **Q: How does mcpx protect MCP endpoints from prompt injection and unauthorized mutations?**
  A: Every incoming tool payload passes through a deterministic Zero-PII filter and a sub-300ms System One probabilistic decision gate that blocks prompt injections and flags high-blast-radius mutations before execution.

## 3. Discovery Methods (Free Tier: $0.00 / 0 credits)

### 3.1 Handshake (`initialize`)
Request:
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {},
    "clientInfo": { "name": "AgentClient", "version": "1.0.0" }
  }
}
```

Response:
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": { "tools": {} },
    "serverInfo": {
      "name": "mcpx-gateway",
      "version": "1.0.0",
      "runtime": "cloudflare-workers-v8"
    }
  }
}
```

### 3.2 Tool Inspection (`tools/list`)
Request:
```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/list",
  "params": {}
}
```

Response:
```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "tools": [
      {
        "name": "analyze_jev_semantic_ast",
        "description": "Static AST analyzer that detects dangerous globals (process, fetch, prototype pollution) and code injection vectors.",
        "inputSchema": {
          "type": "object",
          "properties": { "code": { "type": "string" }, "filename": { "type": "string" } },
          "required": ["code"]
        },
        "x-pricing-tier": "read",
        "x-credit-cost": 1
      },
      {
        "name": "evaluate_fraud_transaction",
        "description": "Deterministic transaction scoring and fraud anomaly classification in real time (~210ms).",
        "inputSchema": {
          "type": "object",
          "properties": { "amount": { "type": "number" }, "currency": { "type": "string" }, "ipCountry": { "type": "string" } },
          "required": ["amount"]
        },
        "x-pricing-tier": "compute",
        "x-credit-cost": 1
      },
      {
        "name": "calculate_u_value_iso6946",
        "description": "Certified EN ISO 6946 thermal transmittance, total resistance, and condensation risk calculation (~140ms).",
        "inputSchema": {
          "type": "object",
          "properties": { "layers": { "type": "array" }, "r_si": { "type": "number" }, "r_se": { "type": "number" } },
          "required": ["layers"]
        },
        "x-pricing-tier": "compute",
        "x-credit-cost": 2
      },
      {
        "name": "generate_mcp_server",
        "description": "Dynamic TypeScript and FastMCP server code compilation and remote schema generation.",
        "inputSchema": {
          "type": "object",
          "properties": { "serverName": { "type": "string" }, "tools": { "type": "array" } },
          "required": ["serverName"]
        },
        "x-pricing-tier": "sandbox",
        "x-credit-cost": 5
      },
      {
        "name": "zibe_rekins_create",
        "description": "Deterministic LVS EN 16931-1 and Peppol BIS Billing 3.0 UBL 2.1 XML compilation with TypeSafe Jev validation and 0.00 drift integer cents.",
        "inputSchema": {
          "type": "object",
          "properties": {
            "invoiceNumber": { "type": "string" },
            "issueDate": { "type": "string" },
            "dueDate": { "type": "string" },
            "buyerReference": { "type": "string" },
            "seller": { "type": "object" },
            "buyer": { "type": "object" },
            "lines": { "type": "array" }
          },
          "required": ["invoiceNumber", "issueDate", "dueDate", "seller", "buyer", "lines"]
        },
        "x-pricing-tier": "invoice",
        "x-credit-cost": 5
      }
    ]
  }
}
```

## 4. Tool Invocation & Billing Handshake (`tools/call`)

Request:
```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "calculate_u_value_iso6946",
    "arguments": { "layers": [{ "name": "Concrete", "thickness": 0.2, "lambda": 1.7 }] }
  }
}
```

### 4.1 Success Response (200 OK)
```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [{ "type": "text", "text": "{\"uValue\": 2.85, \"rTotal\": 0.35, \"status\": \"compliant\"}" }],
    "meta": {
      "creditsDeducted": 2,
      "remainingCredits": 48
    }
  }
}
```

### 4.2 HTTP 402 Payment Required Error Schema

When bearer key credits are below tool cost:

```http
HTTP/1.1 402 Payment Required
Content-Type: application/json
WWW-Authenticate: L402 token="...", invoice="..."
X-Credits-Required: 2
X-Credits-Available: 0
```

```json
{
  "error": "Payment Required",
  "code": 402,
  "message": "Insufficient credits for tool execution.",
  "details": {
    "tool": "calculate_u_value_iso6946",
    "requiredCredits": 2,
    "availableCredits": 0,
    "topUpUrl": "https://mcpx.harrykrauze.com/#pricing"
  }
}
```

## 5. Rīks: `zibe_rekins_create` (EN 16931 / Peppol BIS 3.0 UBL 2.1 kompilators)

- **Namespace:** `quantric.finance`
- **Augšupstraumes galapunkts:** `POST https://zib.harrykrauze.com/api/mcp`
- **Tarifs:** `5` kredīti (`$0.05`) — tiek norakstīti tikai pēc veiksmīgas UBL 2.1 XML kompilācijas (`schematronPassed === true`).
- **TypeSafe Jev Zero-PII audits (`jevZibeAudit.ts`):**
  - Pirms pārsūtīšanas pārbauda 64 KB limitu un ISO datumus (`dueDate >= issueDate`).
  - Bloķē peldošā komata cenas (`unitPriceCents` obligāti vesels skaitlis centos; peldošie skaitļi tiek noraidīti ar `JEV_REJECT`).
  - Bloķē XXE, DTD un SSRF injekciju mēģinājumus.
  - Telemetrijā aizstāj IBAN un uzņēmuma reģistrācijas numuru ar neatgriezenisku SHA-256 nospiedumu (`ibanHash`, `sellerRegNrHash`).
  - Kredītu norakstīšana (`deductAccountCredits`) notiek TIKAI pēc tam, kad upstream atgriezis derīgu UBL 2.1 XML ar `schematronPassed === true`.

### 5.1 Izsaukuma piemērs (`tools/call`)
```json
{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "tools/call",
  "params": {
    "name": "zibe_rekins_create",
    "arguments": {
      "invoiceNumber": "ZR-2026-001",
      "issueDate": "2026-11-24",
      "dueDate": "2026-12-08",
      "buyerReference": "PO-99120",
      "seller": {
        "name": "SIA Paraugs",
        "regNr": "40203000001",
        "vatId": "LV40203000001",
        "address": "Brīvības iela 1, Rīga",
        "countryCode": "LV",
        "iban": "LV80BANK0000435195001"
      },
      "buyer": {
        "name": "SIA Klients",
        "regNr": "40003000002",
        "vatId": "LV40003000002",
        "address": "Dzirnavu iela 10, Rīga",
        "countryCode": "LV"
      },
      "lines": [
        {
          "description": "Programmatūras arhitektūras izstrāde",
          "quantity": 1,
          "unitCode": "HUR",
          "unitPriceCents": 15000,
          "vatCategory": "S",
          "vatPercent": 21
        }
      ]
    }
  }
}
```

### 5.2 Veiksmīga atbilde (200 OK)
```json
{
  "jsonrpc": "2.0",
  "id": 4,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Invoice xmlns=\"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\" ...>...</Invoice>"
      }
    ],
    "meta": {
      "schematronPassed": true,
      "creditsDeducted": 5,
      "remainingCredits": 45
    }
  }
}
```

## Upstream Free PLG Tools: Latvian Self-Employed Tax (`pasdarbi_*`)

- **Gateway Endpoint:** `POST https://mcpx.harrykrauze.com/mcp` (also accessible directly at `POST https://darbi.harrykrauze.com/api/mcp`)
- **Proxy Module:** `src/routes/proxyPasdarbiMcp.ts` — SSRF-locked strictly to `https://darbi.harrykrauze.com/api/mcp`, enforces `8000 ms` `AbortController` timeout, and runs a deterministic Zero-PII pre-flight filter blocking Latvian personal identity codes, IBANs, and email addresses before any network request.
- **Pricing & Auth:** `0` x402 credits (`$0.00`), public Discovery Free Tier (no `Authorization` header required, `readOnlyHint: true`).

### 6.1 `pasdarbi_calculate_vsaoi_threshold` -> `calculate_vsaoi_threshold`
```json
{
  "jsonrpc": "2.0",
  "id": 10,
  "method": "tools/call",
  "params": {
    "name": "pasdarbi_calculate_vsaoi_threshold",
    "arguments": {
      "year": 2026,
      "monthlyNetProfitEur": 1200,
      "isPensioner": false
    }
  }
}
```

### 6.2 `pasdarbi_calculate_vat_139_2_reverse_charge` -> `calculate_vat_139_2_reverse_charge`
```json
{
  "jsonrpc": "2.0",
  "id": 11,
  "method": "tools/call",
  "params": {
    "name": "pasdarbi_calculate_vat_139_2_reverse_charge",
    "arguments": {
      "serviceAmountEur": 100,
      "isRegisteredStandardVatPayer": false,
      "platformLabel": "Google Ads"
    }
  }
}
```

### 6.3 `pasdarbi_check_vat_50k_threshold` -> `check_vat_50k_threshold`
Calendar-year VAT registration threshold check (VAT Law Section 55): `GREEN` (<= €50 000,00), `YELLOW_BUFFER` (€50 000,01 – €55 000,00), `RED_MANDATORY` (> €55 000,00). MK Regulations No. 322 Column 7.c non-taxable income is excluded from the VAT turnover.
```json
{
  "jsonrpc": "2.0",
  "id": 12,
  "method": "tools/call",
  "params": {
    "name": "pasdarbi_check_vat_50k_threshold",
    "arguments": {
      "taxableTurnoverEur": 48000,
      "plannedTransactionEur": 4000,
      "nonTaxableIncome7cEur": 0
    }
  }
}
```