@fhestate/mcp-server 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +432 -0
  3. package/SECURITY.md +158 -0
  4. package/data/agents.json +81 -0
  5. package/dist/blind-step.d.ts +43 -0
  6. package/dist/blind-step.d.ts.map +1 -0
  7. package/dist/blind-step.js +59 -0
  8. package/dist/blind-step.js.map +1 -0
  9. package/dist/cli-bridge.d.ts +62 -0
  10. package/dist/cli-bridge.d.ts.map +1 -0
  11. package/dist/cli-bridge.js +224 -0
  12. package/dist/cli-bridge.js.map +1 -0
  13. package/dist/config.d.ts +13 -0
  14. package/dist/config.d.ts.map +1 -0
  15. package/dist/config.js +37 -0
  16. package/dist/config.js.map +1 -0
  17. package/dist/content/overview.d.ts +3 -0
  18. package/dist/content/overview.d.ts.map +1 -0
  19. package/dist/content/overview.js +30 -0
  20. package/dist/content/overview.js.map +1 -0
  21. package/dist/content/tweets.d.ts +3 -0
  22. package/dist/content/tweets.d.ts.map +1 -0
  23. package/dist/content/tweets.js +23 -0
  24. package/dist/content/tweets.js.map +1 -0
  25. package/dist/data/agents.json +81 -0
  26. package/dist/index.d.ts +3 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +13 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/redact.d.ts +23 -0
  31. package/dist/redact.d.ts.map +1 -0
  32. package/dist/redact.js +36 -0
  33. package/dist/redact.js.map +1 -0
  34. package/dist/resources.d.ts +6 -0
  35. package/dist/resources.d.ts.map +1 -0
  36. package/dist/resources.js +12 -0
  37. package/dist/resources.js.map +1 -0
  38. package/dist/server.d.ts +15 -0
  39. package/dist/server.d.ts.map +1 -0
  40. package/dist/server.js +124 -0
  41. package/dist/server.js.map +1 -0
  42. package/dist/tools/agents.d.ts +44 -0
  43. package/dist/tools/agents.d.ts.map +1 -0
  44. package/dist/tools/agents.js +91 -0
  45. package/dist/tools/agents.js.map +1 -0
  46. package/dist/tools/devnet.d.ts +43 -0
  47. package/dist/tools/devnet.d.ts.map +1 -0
  48. package/dist/tools/devnet.js +119 -0
  49. package/dist/tools/devnet.js.map +1 -0
  50. package/dist/tools/fhe.d.ts +7 -0
  51. package/dist/tools/fhe.d.ts.map +1 -0
  52. package/dist/tools/fhe.js +22 -0
  53. package/dist/tools/fhe.js.map +1 -0
  54. package/dist/tools/knowledge.d.ts +19 -0
  55. package/dist/tools/knowledge.d.ts.map +1 -0
  56. package/dist/tools/knowledge.js +15 -0
  57. package/dist/tools/knowledge.js.map +1 -0
  58. package/dist/tools/social.d.ts +14 -0
  59. package/dist/tools/social.d.ts.map +1 -0
  60. package/dist/tools/social.js +10 -0
  61. package/dist/tools/social.js.map +1 -0
  62. package/dist/tools/verification.d.ts +7 -0
  63. package/dist/tools/verification.d.ts.map +1 -0
  64. package/dist/tools/verification.js +6 -0
  65. package/dist/tools/verification.js.map +1 -0
  66. package/package.json +58 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FHESTATE Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,432 @@
1
+ <div align="center">
2
+
3
+ # 🧠 FHESTATE: Model Context Protocol (MCP) Server
4
+
5
+ ### *AUTONOMOUS AI AGENTS POWERED BY FULLY HOMOMORPHIC ENCRYPTION (FHE)*
6
+
7
+ > **"Granting AI the power to execute FHE on-chain, without ever seeing the plaintext."**
8
+
9
+ [![FHESTATE](https://img.shields.io/badge/FHESTATE-MCP_v1.0.0-8A2BE2?style=for-the-badge&logo=rocket&logoColor=white)](https://github.com/fhestate/fhestate-mcp)
10
+ [![Solana](https://img.shields.io/badge/Solana-Devnet-14F195?style=for-the-badge&logo=solana&logoColor=black)](https://solana.com)
11
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue?style=for-the-badge&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
12
+ <br>
13
+ [![Model Context Protocol](https://img.shields.io/badge/Protocol-MCP-orange?style=for-the-badge)](https://modelcontextprotocol.io)
14
+ [![TFHE-rs](https://img.shields.io/badge/TFHE--rs-v0.7.3-red?style=for-the-badge&logo=rust&logoColor=white)](https://github.com/zama-ai/tfhe-rs)
15
+
16
+ </div>
17
+
18
+ ## 📑 Table of Contents
19
+
20
+ - [1. Overview](#-1-overview)
21
+ - [2. The Coprocessor Architecture & IPC](#%EF%B8%8F-2-the-coprocessor-architecture--ipc)
22
+ - [3. The Security & Redaction Engine](#-3-the-security--redaction-engine)
23
+ - [4. The Confidential Execution Flow (Memo Anchoring)](#-4-the-confidential-execution-flow-memo-anchoring)
24
+ - [5. Use Case: Autonomous Agent Workflows](#-5-use-case-autonomous-agent-workflows)
25
+ - [6. The Comprehensive Tool Matrix](#%EF%B8%8F-6-the-comprehensive-tool-matrix)
26
+ - [7. Quick Start & IDE Integration](#-7-quick-start--ide-integration)
27
+ - [8. LLM Execution Example (JSON-RPC Lifecycle)](#-8-llm-execution-example-json-rpc-lifecycle)
28
+ - [9. Troubleshooting & IPC Error Codes](#-9-troubleshooting--ipc-error-codes)
29
+ - [10. Contact & Support](#-10-contact--support)
30
+
31
+ ---
32
+
33
+ ## 🌟 1. Overview
34
+
35
+ The **FHESTATE MCP Server** is a production-grade execution bridge that connects non-deterministic Large Language Models (LLMs) like Claude 3.5 Sonnet to deterministic Fully Homomorphic Encryption (FHE) on the Solana blockchain.
36
+
37
+ In the current landscape of Artificial Intelligence, LLMs act as "brains in vats." They can reason and write code, but they are fundamentally isolated from secure, cryptographic hardware. The FHESTATE Model Context Protocol (MCP) solves this by providing a standardized, zero-trust `stdio` pipeline directly into a local Rust cryptographic coprocessor.
38
+
39
+ By utilizing this MCP Server, you transform a passive AI chatbot into an active, confidential FHE operator. The AI can autonomously encrypt local memory, perform off-chain homomorphic math, and anchor the resulting `SHA-256` hash commitments to the Solana blockchain—all without ever possessing the decryption keys.
40
+
41
+ ### 1.1 The Institutional Paradigm Shift
42
+ - 🤖 **Zero-Trust AI Autonomy**: The LLM can direct FHE operations without ever seeing the plaintext data or the `client_key.bin`.
43
+ - 🛡️ **Subprocess Isolation**: Heavy TFHE mathematics are routed safely through local Rust subprocesses to prevent AI memory exhaustion and Denial of Service (DoS).
44
+ - 🔗 **Solana Devnet Anchoring**: Agents can autonomously construct, sign, and broadcast transactions to the Solana Devnet, spending local wallet funds to post immutable cryptographic proofs.
45
+ - 🔒 **Aggressive Redaction**: Absolute system paths are scrubbed from LLM context windows to prevent local host topology leaks to cloud providers (OpenAI/Anthropic).
46
+ - ✅ **Strict Zod Boundaries**: Cryptographic `Uint32` constraints are strictly enforced via Zod schemas, instantly rejecting AI hallucinations before they crash the Rust binary.
47
+
48
+ ---
49
+
50
+ ## 🏗️ 2. The Coprocessor Architecture & IPC
51
+
52
+ The fundamental challenge of implementing FHE on Solana is the strict 1.4 million Compute Unit (CU) transaction limit. Evaluating a single TFHE-rs boolean gate requires thousands of CPU cycles; evaluating a full homomorphic addition or multiplication requires billions.
53
+
54
+ To solve this, the FHESTATE MCP Server implements a **Coprocessor Architecture**. The Node.js server does not perform the cryptography itself. Instead, it securely spawns the `fhe-cli` Rust binary, acts as a sanitization layer, and manages the blockchain network calls.
55
+
56
+ ### 2.1 Component Interaction Flow
57
+
58
+ ```mermaid
59
+ graph TD
60
+ subgraph "Cloud / AI Layer"
61
+ LLM[Claude 3.5 / Cursor LLM]
62
+ MCP_CLIENT[MCP Client Interface]
63
+ end
64
+
65
+ subgraph "Host Machine (Node.js MCP Server)"
66
+ ZOD[Zod Validation Layer]
67
+ REDACT[Path Redaction Engine]
68
+ RPC_SERVER[JSON-RPC 2.0 Server]
69
+ WEB3[Solana Web3.js]
70
+ end
71
+
72
+ subgraph "Host Machine (Rust / Cryptography)"
73
+ FHE_CLI[fhe-cli Binary]
74
+ TFHE[TFHE-rs Library]
75
+ KEYS[.fhe_keys Directory]
76
+ end
77
+
78
+ subgraph "Solana Network"
79
+ DEVNET[Solana Devnet RPC]
80
+ end
81
+
82
+ LLM <-->|JSON-RPC via stdio| MCP_CLIENT
83
+ MCP_CLIENT <--> RPC_SERVER
84
+
85
+ RPC_SERVER -->|Validate Params| ZOD
86
+ ZOD -->|fhe_encrypt / blind_step| FHE_CLI
87
+ FHE_CLI -->|Reads| KEYS
88
+ FHE_CLI -->|Computes| TFHE
89
+ FHE_CLI -->|stdout Hash| REDACT
90
+ REDACT --> RPC_SERVER
91
+
92
+ ZOD -->|devnet_submit_memo| WEB3
93
+ WEB3 -->|Sign Tx| DEVNET
94
+ ```
95
+
96
+ ### 2.2 Deep Dive: Inter-Process Communication (IPC)
97
+ The MCP server uses asynchronous `stdio` to communicate with the IDE/Claude Desktop, but it uses `child_process.spawn` to communicate with the Rust Coprocessor. This is managed by the `cli-bridge.ts` module.
98
+
99
+ When the AI Agent calls `fhe_encrypt(42)`:
100
+ 1. **Payload Interception**: The Node MCP Server receives the JSON-RPC request.
101
+ 2. **Argument Construction**: Node constructs an argument array: `['encrypt', '--value', '42']`. It strictly avoids using shell interpolation.
102
+ 3. **Subprocess Spawning**: Node spawns the Rust process with `shell: false` and a `cwd` restricted to the workspace.
103
+ 4. **Lattice Computation**: The Rust Coprocessor spins up the TFHE-rs lattice mathematics. This consumes ~500MB of RAM and heavily utilizes the CPU for roughly 2-3 seconds to generate a massive 15MB ciphertext file.
104
+ 5. **Buffer Management**: The Rust binary writes the resulting SHA-256 hash of that file to its `stdout` pipe. Node's `cli-bridge.ts` reads the stream.
105
+ 6. **Graceful Exit**: The Node server closes the process, parses the output through the Redaction Engine, and returns the formatted hash to the AI.
106
+
107
+ ---
108
+
109
+ ## 🔒 3. The Security & Redaction Engine
110
+
111
+ Because the AI Agent is fundamentally untrusted and operates in a non-deterministic manner, the MCP Server implements extreme isolation and data scrubbing mechanisms. It assumes the LLM is actively hostile or prone to severe hallucinations.
112
+
113
+ ### 3.1 The Redaction Engine (`redact.ts`)
114
+
115
+ LLMs are cloud-hosted. If the local Rust binary outputs a success message like `Saved to C:\Users\Admin\Documents\Crypto\.fhe_keys\client_key.bin`, passing this raw string back to the LLM exposes your local folder structure, username, and topology to Anthropic/OpenAI servers.
116
+
117
+ The MCP Server utilizes a specialized **Redaction Engine** that intercepts all `stdout` arrays before they are formatted into the JSON-RPC response.
118
+
119
+ ```mermaid
120
+ flowchart LR
121
+ Rust[Rust Coprocessor] -->|Raw stdout| Buffer[Node.js Buffer]
122
+ Buffer --> Regex1[Regex: Match Absolute Paths]
123
+ Regex1 --> Regex2[Regex: Match Base58/Seeds]
124
+ Regex2 --> Mask[Overwrite with REDACTED]
125
+ Mask --> LLM[Return to AI Context]
126
+ ```
127
+
128
+ - **Path Scrubbing**: It uses heuristic regex to locate Windows (`C:\...`) and POSIX (`/...`) absolute paths and overwrites them with `[REDACTED_PATH]`.
129
+ - **Key Scrubbing**: It scans for 12-word seed phrases or 88-character Base58 strings that resemble private keys and masks them, ensuring the AI never accidentally reads the developer's wallet secret into its context window.
130
+
131
+ ### 3.2 Zod Strictness & Cryptographic Bounds
132
+ LLMs frequently hallucinate string parameters where integers are required. Because `TFHE-rs` operates on strict byte widths, it will panic and abort the process if fed a non-standard byte width (e.g., a float or a negative number).
133
+
134
+ The MCP Server uses strict `zod` schemas to enforce `Uint32` boundaries. If Claude attempts to call `fhe_encrypt(1.5)` or injects a path traversal payload like `fhe_encrypt("../../")`, the Zod layer intercepts the call *before* it hits the Rust binary. It immediately returns a JSON-RPC `-32602` Invalid Params error, forcing the AI to self-correct its logic.
135
+
136
+ ### 3.3 Buffer Capping & DoS Prevention
137
+ The `stdout` buffer from the FHE binary is capped at exactly 512KB. If an AI hallucinates an infinite loop or triggers a command that dumps massive amounts of data, the subprocess is forcefully terminated via `SIGKILL` after 60 seconds to prevent host memory exhaustion.
138
+
139
+ ### 3.4 Read-Only Sandbox Override
140
+ If you are running a public hackathon or do not want the AI to spend Devnet SOL, you can hard-lock the network layer. Set `FHESTATE_MCP_READ_ONLY=1` in the `env` block of your MCP configuration. The AI will still be able to execute heavy FHE math locally, but the `devnet_submit_memo` tool will immediately throw an `Unauthorized` error.
141
+
142
+ ---
143
+
144
+ ## 🌊 4. The Confidential Execution Flow (Memo Anchoring)
145
+
146
+ The core functional purpose of the MCP Server is to allow AI agents to securely execute FHE commitments and anchor them to the Solana blockchain.
147
+
148
+ ```mermaid
149
+ sequenceDiagram
150
+ participant User
151
+ participant AI Agent
152
+ participant Node Coprocessor
153
+ participant Solana Devnet
154
+
155
+ note over User, Solana Devnet: Phase 1: Local FHE Encryption
156
+ User->>AI Agent: "Encrypt the value 150"
157
+ AI Agent->>Node Coprocessor: fhe_encrypt(150)
158
+ Node Coprocessor->>Node Coprocessor: Load client_key.bin
159
+ Node Coprocessor->>Node Coprocessor: Generate 15MB Ciphertext
160
+ Node Coprocessor-->>AI Agent: Return SHA-256 Hash
161
+
162
+ note over User, Solana Devnet: Phase 2: On-Chain Anchoring
163
+ AI Agent->>Solana Devnet: devnet_submit_memo(Hash)
164
+ Solana Devnet-->>AI Agent: Return Signature & Solscan Link
165
+ AI Agent-->>User: "Success. Your data is encrypted and anchored."
166
+ ```
167
+
168
+ ### 4.1 Local Encryption Phase
169
+ The AI Agent utilizes the `fhe_encrypt` tool to encrypt the data locally. The plaintext value never leaves the host machine. Because the generated ciphertext is massive, the Rust node stores it securely in the `.fhe_keys/` directory and returns only the 32-byte cryptographic hash to the AI.
170
+
171
+ ### 4.2 On-Chain Anchoring Phase
172
+ The AI Agent automatically calls the `devnet_submit_memo` tool with the resulting hash. The MCP server utilizes `@solana/web3.js` to construct an SPL Memo transaction (formatted exactly as `local://<hash>`). The server signs the transaction using the developer's keypair specified in `FHESTATE_WALLET_PATH`, and broadcasts it to the Solana Devnet, returning the finalized signature to the AI.
173
+
174
+ ---
175
+
176
+ ## 🤖 5. Use Case: Autonomous Agent Workflows
177
+
178
+ How does an AI actually use this MCP server in a real-world scenario?
179
+
180
+ To ensure that the LLM cannot hallucinate steps or skip cryptographic verifications, the MCP server enforces an internal `blind-step` hash chain. The server's registry defines **3 distinct AI agents** (Sentinel, Auditor, Coordinator) that can be combined into different confidential workflows (missions).
181
+
182
+ The MCP Server is pre-configured with **3 execution workflows** (demo scripts) that show how these agents interact:
183
+
184
+ ### Workflow 1: The Fast Path (Sentinel Only)
185
+ **"Sentinel Secret Vote"**
186
+ This is the fastest workflow. A single Sentinel agent takes a user's binary vote (1 or 0), encrypts it locally via `fhe_encrypt`, and advances the hash chain. No other agents are required.
187
+
188
+ ### Workflow 2: The Compliance Path (Sentinel → Auditor)
189
+ **"Sentinel → Auditor Compliance Scan → Auditor Seal Record"**
190
+ 1. **Sentinel**: Encrypts the user's intent and establishes the `stepHash`.
191
+ 2. **Auditor**: Receives the `stepHash` from the Sentinel, runs a zero-knowledge compliance scan against the encrypted data, and permanently seals the record if the policy passes.
192
+
193
+ ### Workflow 3: The Routing Path (Sentinel → Coordinator)
194
+ **"Sentinel Market Signal → Coordinator Route Intent"**
195
+ 1. **Sentinel**: Encrypts a quantitative market signal (e.g., a blind trade intent) and passes the hash forward.
196
+ 2. **Coordinator**: Takes the verified signal hash and routes the intent to a specific execution channel on-chain using `devnet_submit_memo`.
197
+
198
+ ---
199
+
200
+ ## 🛠️ 6. The Comprehensive Tool Matrix
201
+
202
+ The MCP Server exposes exactly **13 highly restricted JSON-RPC tools**. If a tool is not on this list, the AI cannot execute it. Every tool is strictly typed using Zod.
203
+
204
+ ### 6.1 FHE Cryptography Tools (Compute-Heavy)
205
+
206
+ #### 1. `fhe_encrypt`
207
+ - **Description**: The core cryptographic engine. Takes a plaintext `Uint32` integer from the LLM, pipes it to the local Rust `fhe-cli`, and generates a massive (15MB+) `TFHE-rs` ciphertext. To protect the LLM context window, it only returns the `SHA-256` commitment hash.
208
+ - **Risk Profile**: Moderate (High CPU Usage).
209
+ - **Zod Schema**:
210
+ ```typescript
211
+ z.object({
212
+ value: z.number().int().min(0).max(4294967295)
213
+ }).strict()
214
+ ```
215
+
216
+ #### 2. `agent_run_blind_step`
217
+ - **Description**: Advances the agent memory chain. Takes an `agentId` (Sentinel/Auditor) and a `missionId`, and computes the next link in the local `stepHash` chain.
218
+ - **Risk Profile**: Low.
219
+ - **Zod Schema**:
220
+ ```typescript
221
+ z.object({
222
+ agentId: z.string(),
223
+ missionId: z.string(),
224
+ value: z.number().int().min(0).max(4294967295)
225
+ }).strict()
226
+ ```
227
+
228
+ #### 3. `fhe_cli_run`
229
+ - **Description**: A highly restricted sandbox allowing the AI to execute specific diagnostic commands on the `fhe-cli` binary.
230
+ - **Risk Profile**: Moderate.
231
+ - **Zod Schema**:
232
+ ```typescript
233
+ z.object({
234
+ subcommand: z.string(),
235
+ args: z.array(z.string()).max(10)
236
+ }).strict()
237
+ ```
238
+ *(Note: Only subcommands `['doctor', 'history', 'balance']` are allowlisted. Path traversal `../` is explicitly blocked).*
239
+
240
+ #### 4. `simulate_homomorphic_eval`
241
+ - **Description**: Simulates the Auditor homomorphic logic over an encrypted payload, returning a deterministic boolean pseudo-hash. Bridges the gap between the theoretical Auditor functionality and the current CLI capabilities.
242
+ - **Risk Profile**: Low.
243
+ - **Zod Schema**:
244
+ ```typescript
245
+ z.object({
246
+ logicGate: z.string(),
247
+ inputHash: z.string().min(64)
248
+ }).strict()
249
+ ```
250
+
251
+ ### 6.2 Solana Network Tools (State Modifying)
252
+
253
+ #### 5. `devnet_wallet_status`
254
+ - **Description**: Pings the `FHESTATE_RPC` and checks the exact SOL lamport balance of the keypair specified in `FHESTATE_WALLET_PATH`.
255
+ - **Risk Profile**: Low (Read-Only RPC call).
256
+ - **Zod Schema**: `z.object({}).strict()`
257
+
258
+ #### 6. `devnet_history`
259
+ - **Description**: Fetches the 5 most recent transaction signatures associated with the local developer wallet, allowing the AI to verify if its previous transactions successfully landed on-chain.
260
+ - **Risk Profile**: Low (Read-Only RPC call).
261
+ - **Zod Schema**: `z.object({}).strict()`
262
+
263
+ #### 7. `devnet_submit_memo`
264
+ - **Description**: **[CRITICAL]** This tool modifies blockchain state and spends funds. It constructs, signs, and broadcasts a live transaction to the Solana Devnet. It wraps the `SHA-256` ciphertext hash generated by `fhe_encrypt` in an SPL Memo (`local://<hash>`), anchoring the FHE commitment on-chain.
265
+ - **Risk Profile**: Extreme. Spends Devnet SOL. Automatically disabled if `FHESTATE_MCP_READ_ONLY=1` is set.
266
+ - **Zod Schema**:
267
+ ```typescript
268
+ z.object({
269
+ value: z.number().int().min(0).max(4294967295)
270
+ }).strict()
271
+ ```
272
+
273
+ #### 8. `solscan_link`
274
+ - **Description**: A static formatting tool. Takes a raw Solana Base58 signature and constructs a valid `https://solscan.io` URL bound strictly to the Devnet cluster.
275
+ - **Risk Profile**: None (Static String Generation).
276
+ - **Zod Schema**:
277
+ ```typescript
278
+ z.object({
279
+ signature: z.string().min(80).max(90)
280
+ }).strict()
281
+ ```
282
+
283
+ ### 6.3 Knowledge & Verification Tools (Zero Risk)
284
+
285
+ #### 9. `list_agents_and_missions`
286
+ - **Description**: Returns the full JSON registry of all available confidential AI agents (Sentinel, Auditor, Coordinator) and their specific allowed mission IDs. Used to ground the AI before it executes a workflow.
287
+ - **Zod Schema**: `z.object({}).strict()`
288
+
289
+ #### 10. `execution_protocol_script`
290
+ - **Description**: Returns the exact step-by-step presentation script used for walking a developer through the Sentinel Secret Vote workflow. Ensures the AI uses canonical phrasing during live integrations.
291
+ - **Zod Schema**: `z.object({}).strict()`
292
+
293
+ #### 11. `architectural_proof_checklist`
294
+ - **Description**: Returns the pre-flight checklist required to successfully deploy the FHESTATE system in a live environment, ensuring all devnet wallets, rust binaries, and environment variables are positioned correctly.
295
+ - **Zod Schema**: `z.object({}).strict()`
296
+
297
+ #### 12. `get_mcp_config_state`
298
+ - **Description**: Safely reads the server's local environment configuration. Returns redacted visibility into the operational state.
299
+ - **Zod Schema**: `z.object({}).strict()`
300
+
301
+ #### 13. `verify_ciphertext_hash`
302
+ - **Description**: Zero-Trust format verification of an intent hash before anchoring to Devnet. Mathematically validates the SHA-256 entropy.
303
+ - **Zod Schema**:
304
+ ```typescript
305
+ z.object({
306
+ hash: z.string().min(64)
307
+ }).strict()
308
+ ```
309
+
310
+ ---
311
+
312
+ ## 🚀 7. Quick Start & IDE Integration
313
+
314
+ Because this MCP server interfaces with a local Rust binary, setup requires compiling the Coprocessor first.
315
+
316
+ ### Step 1: Compile the Rust Coprocessor
317
+ You must have Rust `1.70+` installed.
318
+ ```bash
319
+ git clone https://github.com/fhestate/fhestate-rs.git
320
+ cd fhestate-rs
321
+ cargo build --release -p fhe-cli
322
+ ```
323
+ *Note the absolute path to the generated binary: `.../fhestate-rs/target/release/fhe-cli`.*
324
+
325
+ ### Step 2: Build the MCP Server
326
+ ```bash
327
+ cd mcp/fhestate-mcp
328
+ npm install
329
+ npm run build
330
+ ```
331
+
332
+ ### Step 3: Configure the Solana Wallet
333
+ Generate a new Devnet keypair. **DO NOT USE A MAINNET WALLET.**
334
+ ```bash
335
+ solana-keygen new --outfile devnet-wallet.json --no-bip39-passphrase
336
+ solana airdrop 2 -k devnet-wallet.json --url devnet
337
+ ```
338
+ *Note the absolute path to this JSON file.*
339
+
340
+ ### Step 3: Configure Cursor IDE or Claude Desktop
341
+
342
+ Open your MCP configuration file:
343
+ - **Cursor IDE**: `Settings > Features > MCP > Add New`
344
+ - **Claude Desktop**: `~/Library/Application Support/Claude/claude_desktop_config.json` (Mac) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows)
345
+
346
+ Add the following configuration, replacing the absolute paths with your actual system paths:
347
+
348
+ ```json
349
+ {
350
+ "mcpServers": {
351
+ "fhestate-coprocessor": {
352
+ "command": "node",
353
+ "args": ["/ABSOLUTE/PATH/TO/fhestate/mcp/fhestate-mcp/dist/index.js"],
354
+ "env": {
355
+ "FHESTATE_CLI_PATH": "/ABSOLUTE/PATH/TO/fhestate-rs/target/release/fhe-cli",
356
+ "FHESTATE_WALLET_PATH": "/ABSOLUTE/PATH/TO/devnet-wallet.json",
357
+ "FHESTATE_RPC": "https://api.devnet.solana.com",
358
+ "FHESTATE_MCP_READ_ONLY": "0"
359
+ }
360
+ }
361
+ }
362
+ }
363
+ ```
364
+
365
+ Restart your IDE or Claude Desktop. You should now see the 13 tools available in the agent's context window. Type `"Check my devnet wallet balance"` to initiate the handshake.
366
+
367
+ ---
368
+
369
+ ## 💻 8. LLM Execution Example (JSON-RPC Lifecycle)
370
+
371
+ This is how an AI Agent (like Claude) actually communicates with the MCP Server under the hood to execute a confidential operation. The AI constructs a JSON-RPC payload:
372
+
373
+ ```json
374
+ {
375
+ "jsonrpc": "2.0",
376
+ "id": "req_1a2b3c",
377
+ "method": "tools/call",
378
+ "params": {
379
+ "name": "fhe_encrypt",
380
+ "arguments": {
381
+ "value": 50
382
+ }
383
+ }
384
+ }
385
+ ```
386
+
387
+ The MCP Server intercepts this, enforces the Zod `Uint32` boundary, pipes the `50` to the Rust Coprocessor, and returns the redacted hash commitment back to the AI's context window:
388
+
389
+ ```json
390
+ {
391
+ "jsonrpc": "2.0",
392
+ "id": "req_1a2b3c",
393
+ "result": {
394
+ "content": [
395
+ {
396
+ "type": "text",
397
+ "text": "Ciphertext generated. Local Hash: 8f434346648f6b96df89dda901c5176b10a6d83961dd3c1ac88b59b2dc327aa4"
398
+ }
399
+ ]
400
+ }
401
+ }
402
+ ```
403
+
404
+ ---
405
+
406
+ ## 🛑 9. Troubleshooting & IPC Error Codes
407
+
408
+ When interacting with the MCP server over standard input/output (stdio), you may encounter specific JSON-RPC error codes resulting from the IPC Bridge.
409
+
410
+ | JSON-RPC Code | HTTP Equivalent | Trigger Scenario | Resolution |
411
+ |---------------|-----------------|------------------|------------|
412
+ | `-32602` | `400 Bad Request` | Zod Validation Failure. AI hallucinated a string instead of a `Uint32` or tried to use path traversal `../`. | Inform the AI of the Zod constraints. It will automatically correct its payload. |
413
+ | `-32603` | `500 Internal Error` | CLI Binary `ENOENT`. The Node server cannot find the `fhe-cli` binary. | Verify `FHESTATE_CLI_PATH` in your MCP Config is absolute and the binary was compiled. |
414
+ | `-32000` | `504 Gateway Timeout`| Coprocessor Timeout. The FHE math took longer than 60s. | You likely ran `cargo build` instead of `cargo build --release`. FHE math requires release optimizations. |
415
+ | `-32001` | `401 Unauthorized` | Read-Only Sandbox active. AI tried to call `devnet_submit_memo`. | Set `FHESTATE_MCP_READ_ONLY=0` if you intend to spend Devnet SOL. |
416
+ | `-32002` | `502 Bad Gateway` | Solana Web3 Connection Error. Devnet RPC dropped the packet. | Switch `FHESTATE_RPC` to a premium provider like Helius or Alchemy. |
417
+
418
+ ---
419
+
420
+ ## 📞 10. Contact & Support
421
+
422
+ - **Documentation**: [Comprehensive Technical Specs](https://docs.fhestate.org)
423
+ - **GitHub Issues**: [Report bugs or request features](https://github.com/fhestate/fhestate-mcp/issues)
424
+ - **Discussions**: [Join community discussions](https://github.com/fhestate/fhestate-mcp/discussions)
425
+ - **Twitter**: [@fhe_state](https://twitter.com/fhe_state)
426
+
427
+ ---
428
+
429
+ <div align="center">
430
+ Copyright © 2026 FHESTATE Protocol. All rights reserved. <br>
431
+ <i>Private Intelligence. Public Settlement.</i>
432
+ </div>
package/SECURITY.md ADDED
@@ -0,0 +1,158 @@
1
+ # 🛡️ SECURITY MODELING: @fhestate/mcp-server
2
+
3
+ **Document Version:** 1.0.0
4
+ **Target Infrastructure:** Solana Devnet & TFHE-rs Coprocessor
5
+ **Compliance Standard:** FHESTATE Enterprise Security Guidelines
6
+
7
+ ---
8
+
9
+ ## 1. Executive Security Posture
10
+
11
+ The `@fhestate/mcp-server` is explicitly designed as a zero-trust execution bridge between non-deterministic Large Language Models (LLMs) and deterministic cryptographic processors (FHE/TFHE). Because this Node.js process sits directly on a host machine with access to a filesystem, shell binaries, and Solana private keys, the security posture must assume that the connected AI Agent is **actively hostile or deeply hallucinating**.
12
+
13
+ This document outlines the strict cryptographic, systemic, and network-level security guarantees enforced by the server, as well as the known vulnerabilities, risk boundaries, and incident response protocols required for enterprise deployment.
14
+
15
+ ---
16
+
17
+ ## 2. The AI Threat Model
18
+
19
+ Advanced LLMs (such as Claude 3.5 Sonnet or OpenAI models) are highly capable but mathematically unpredictable. When granting an AI access to a local Model Context Protocol (MCP) server, operators face three primary threat vectors:
20
+
21
+ ### 2.1 Prompt Injection to Shell Execution (RCE)
22
+ If an attacker feeds a malicious prompt to the LLM (e.g., via an untrusted file loaded in the IDE), the AI may attempt to execute arbitrary shell commands.
23
+ * **Mitigation**: The MCP Server completely disables raw shell access. The `fhe_cli_run` and `fhe_encrypt` tools spawn the Rust `fhe-cli` binary using `child_process.spawn` with `shell: false`. Furthermore, command arguments are strictly allowlisted. The AI cannot pipe (`|`), chain (`&&`), or inject bash commands.
24
+
25
+ ### 2.2 Host System Path Traversal
26
+ An AI might attempt to read sensitive files outside the FHESTATE workspace (e.g., `~/.ssh/id_rsa` or `~/.config/solana/id.json`).
27
+ * **Mitigation**: Any argument passed to the CLI bridge that contains `../` or relative traversal operators is aggressively intercepted by the MCP Node server and blocked with a `-32602` JSON-RPC error.
28
+
29
+ ### 2.3 Cryptographic Memory Exhaustion (DoS)
30
+ FHE operations (specifically Zama's TFHE-rs) are computationally massive. Generating a single ciphertext can consume hundreds of megabytes of RAM and heavy CPU cycles. If an AI hallucinates a loop, it could trigger a Denial of Service (DoS) on the host machine.
31
+ * **Mitigation**: The MCP Server enforces a strict `timeout` of 60 seconds on all subprocesses. Additionally, the `stdout` and `stderr` buffers are capped at exactly 512KB. If the FHE coprocessor exceeds these limits, the Node process sends a `SIGKILL` to forcefully terminate the Rust worker, returning a `-32603` timeout error to the AI.
32
+
33
+ ---
34
+
35
+ ## 3. Strict Zod Boundary Enforcement
36
+
37
+ Every single JSON-RPC request originating from the LLM must pass through a strict `zod` schema validation layer before interacting with the Node runtime or the Rust coprocessor.
38
+
39
+ ### 3.1 The Uint32 Cryptographic Boundary
40
+ TFHE-rs operates on highly specific integer types. Passing a floating-point number or a negative integer into the CLI will cause a Rust panic.
41
+ * **Zod Enforcement**:
42
+ ```typescript
43
+ value: z.number().int().min(0).max(4294967295)
44
+ ```
45
+ This schema guarantees that the AI can only pass valid `u32` integers into the `fhe_encrypt` and `agent_run_blind_step` tools. If the AI attempts to pass a string or a float, the MCP server rejects it immediately and feeds the Zod type error back to the AI for self-correction.
46
+
47
+ ### 3.2 Enum Sandboxing for Agent Workflows
48
+ The confidential agents are bounded by specific logical states. The AI cannot invent new agents or mission types.
49
+ * **Zod Enforcement**:
50
+ ```typescript
51
+ agentId: z.enum(["sentinel", "auditor", "coordinator"])
52
+ ```
53
+ This prevents the AI from hallucinating unauthorized operators or injecting SQL-like syntax into the local hash-chain memory.
54
+
55
+ ---
56
+
57
+ ## 4. The Redaction Engine (`redact.ts`)
58
+
59
+ LLMs are highly context-sensitive. If an internal tool returns an absolute file path (e.g., `C:\Users\Admin\Documents\wallet.json`), the LLM will store that path in its active context window. This creates a high risk of leaking host-system topology to cloud-based LLM providers.
60
+
61
+ To solve this, the FHESTATE MCP Server employs an aggressive redaction layer on all outgoing JSON-RPC packets.
62
+
63
+ ### 4.1 Automated Path Scrubbing
64
+ The `redact.ts` module intercepts all strings returning to the AI. It uses regular expressions to identify absolute system paths (both Unix `/` and Windows `C:\` styles) and aggressively overwrites them with safe placeholder tokens.
65
+ * *Raw CLI Output*: `"Saved ciphertext to /Users/dev/.fhe_keys/client_key.bin"`
66
+ * *Redacted AI Output*: `"Saved ciphertext to [REDACTED_PATH]/client_key.bin"`
67
+
68
+ ### 4.2 Seed Phrase and Private Key Isolation
69
+ While the MCP server does not expose tools to read raw private keys, the redaction engine acts as a fail-safe. Any output matching the structure of a BIP39 12-word mnemonic or a Base58 Solana private key array is forcefully scrubbed.
70
+
71
+ ---
72
+
73
+ ## 5. Wallet Management & On-Chain Risk
74
+
75
+ The MCP Server interacts with the Solana blockchain via the `@solana/web3.js` library, specifically through the `devnet_submit_memo` tool. This tool requires access to a local Keypair to sign and pay for transactions.
76
+
77
+ ### 5.1 Devnet Scope ONLY
78
+ **WARNING**: This repository and its accompanying tools are explicitly audited for the **Solana Devnet** only.
79
+ * You must never place a Mainnet wallet containing real financial value (SOL, USDC) into the path resolved by `FHESTATE_WALLET_PATH`.
80
+ * The transaction construction logic does not currently utilize Mainnet priority fees or advanced MEV-protection logic.
81
+
82
+ ### 5.2 The Read-Only Sandbox (`FHESTATE_MCP_READ_ONLY`)
83
+ For environments where the host machine is shared or the operator does not wish to allow the AI to mutate blockchain state, operators must configure the environment variable:
84
+ `FHESTATE_MCP_READ_ONLY=1`
85
+
86
+ When this flag is active:
87
+ 1. The `devnet_submit_memo` tool is artificially disabled.
88
+ 2. If the AI attempts to call it, the server intercepts the request before touching the Solana RPC and returns an error: `Network mutations are disabled. FHESTATE_MCP_READ_ONLY is active.`
89
+ 3. The AI can still perform local FHE mathematics (`fhe_encrypt`), but it cannot spend Devnet SOL.
90
+
91
+ ---
92
+
93
+ ## 6. The Coprocessor Handshake (`fhe-cli`)
94
+
95
+ The security of the MCP Server relies entirely on the integrity of the `fhe-cli` binary.
96
+
97
+ ### 6.1 Binary Sourcing
98
+ The MCP Server assumes that the `fhe-cli` binary was compiled locally by the operator from the official `fhestate-rs` repository.
99
+ * **Do not download pre-compiled `fhe-cli` binaries from untrusted sources.** A malicious binary could intercept the FHE payload and exfiltrate it before encryption.
100
+ * **Path Resolution**: The server attempts to find the binary via the `FHESTATE_CLI_PATH` environment variable. If omitted, it attempts to resolve the binary relative to the repository root. Ensure your file permissions prevent unauthorized modification of the target release folder.
101
+
102
+ ### 6.2 Key Material Isolation
103
+ The `fhe-cli` generates its evaluation and client keys inside the `.fhe_keys/` hidden directory.
104
+ * The MCP Server does **not** expose any JSON-RPC tools capable of reading these files.
105
+ * The AI Agent never possesses the `client_key.bin` and therefore cannot mathematically decrypt the ciphertexts it requests. It operates strictly in a "blind" capacity.
106
+
107
+ ---
108
+
109
+ ## 7. Incident Response Matrix
110
+
111
+ If an operator suspects that the MCP server or the connected AI Agent has behaved maliciously, follow this response matrix:
112
+
113
+ | Severity Level | Indicator of Compromise (IoC) | Immediate Action | Secondary Action |
114
+ |---|---|---|---|
115
+ | **CRITICAL** | Devnet SOL is draining rapidly from the configured wallet without user prompt. | 1. Terminate the Node.js MCP Process immediately.<br>2. Disconnect the IDE/Claude Desktop. | Revoke the Devnet wallet. Audit the `server.ts` file for unauthorized modifications. |
116
+ | **HIGH** | The `fhe-cli` process is consuming 100% CPU for more than 5 minutes. | 1. Run `killall fhe-cli` (Unix) or End Process in Task Manager (Windows). | Check the LLM context window to see if it hallucinated an infinite loop of `fhe_encrypt` calls. |
117
+ | **MEDIUM** | Redaction failure: Absolute system paths are visible in the AI chat window. | 1. Clear the chat context window immediately to prevent the LLM from caching the paths. | Submit a bug report to the repository detailing the regex failure in `redact.ts`. |
118
+ | **LOW** | The AI repeatedly fails to execute `fhe_cli_run` due to Zod validation errors. | 1. No action required. The system is operating as designed. | Guide the AI with better prompting regarding Uint32 limits. |
119
+
120
+ ---
121
+
122
+ ## 8. Vulnerability Disclosure Policy
123
+
124
+ FHESTATE takes the security of our cryptography and integration pipelines seriously. If you discover a vulnerability in the `@fhestate/mcp-server` that allows for Remote Code Execution (RCE), Mainnet financial loss, or cryptographic bypass, please follow our responsible disclosure protocol.
125
+
126
+ ### 8.1 Reporting Guidelines
127
+ 1. **Do not open a public GitHub issue.**
128
+ 2. Send an encrypted email to `security@fhestate.org` detailing the exact exploit path, the MCP version, and a minimal reproducible example (MRE).
129
+ 3. Wait for acknowledgment from the core engineering team within 48 hours.
130
+
131
+ ### 8.2 Out of Scope Vulnerabilities
132
+ The following scenarios are considered out of scope for security bounties:
133
+ * Social engineering of the AI Agent (e.g., convincing the AI to write a bad tweet).
134
+ * Denial of Service (DoS) caused by intentionally setting the `timeout` parameter in `cli-bridge.ts` to `0`.
135
+ * Loss of Devnet SOL due to intentional abuse of the `devnet_submit_memo` tool.
136
+
137
+ ---
138
+
139
+ ## 9. Architectural Integrity & Continuous Integration
140
+
141
+ To maintain the security posture described in this document, the `fhestate-mcp` repository enforces strict CI/CD pipelines.
142
+
143
+ ### 9.1 The Smoke Test Suite
144
+ Before any code is merged into the `main` branch, it must pass the `smoke-list-tools.mjs` test. This test programmatically spawns the MCP server and executes a mock JSON-RPC handshake, verifying that exactly 10 zero-trust tools are registered and that the `zod` schemas are intact.
145
+
146
+ ### 9.2 Dependency Auditing
147
+ The server relies on highly vetted dependencies:
148
+ * `@modelcontextprotocol/sdk`: The official standard for AI tool execution.
149
+ * `zod`: The industry standard for runtime type validation.
150
+ * `@solana/web3.js`: The official Solana foundation library.
151
+
152
+ The `package.json` explicitly pins these dependencies. Operators should run `npm audit` frequently to ensure no transitive dependencies have introduced supply-chain vulnerabilities.
153
+
154
+ ---
155
+
156
+ ## 10. Disclaimer
157
+
158
+ This software is provided "as is", without warranty of any kind, express or implied. By operating the `@fhestate/mcp-server`, you acknowledge that bridging non-deterministic LLMs to local filesystems and cryptographic binaries inherently involves risk. You agree to run this server in a sandboxed, Devnet-only capacity.