protect-mcp 0.3.3 → 0.4.1

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.
package/dist/cli.mjs CHANGED
@@ -1,13 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- ProtectGateway,
4
3
  formatSimulation,
4
+ parseLogFile,
5
+ simulate
6
+ } from "./chunk-VWUN6AI6.mjs";
7
+ import {
8
+ ProtectGateway,
5
9
  initSigning,
6
10
  loadPolicy,
7
- parseLogFile,
8
- simulate,
9
11
  validateCredentials
10
- } from "./chunk-WDCPUM2O.mjs";
12
+ } from "./chunk-7HBHIKLN.mjs";
11
13
 
12
14
  // src/cli.ts
13
15
  function printHelp() {
@@ -31,6 +33,8 @@ Options:
31
33
  --policy <path> Policy/config JSON file (default: allow-all)
32
34
  --slug <slug> ScopeBlind tenant slug (optional)
33
35
  --enforce Enable enforcement mode (default: shadow mode)
36
+ --http Start HTTP/SSE server instead of stdio proxy
37
+ --port <port> HTTP server port (default: 3000, requires --http)
34
38
  --verbose Enable debug logging to stderr
35
39
  --help Show this help
36
40
 
@@ -1020,6 +1024,14 @@ async function main() {
1020
1024
  signing,
1021
1025
  credentials
1022
1026
  };
1027
+ const useHttp = args.includes("--http");
1028
+ if (useHttp) {
1029
+ const portIdx = args.indexOf("--port");
1030
+ const httpPort = portIdx >= 0 && args[portIdx + 1] ? parseInt(args[portIdx + 1]) : 3e3;
1031
+ const { startHttpTransport } = await import("./http-transport-RIVV2RVQ.mjs");
1032
+ startHttpTransport({ port: httpPort, config, serverCommand: childCommand });
1033
+ return;
1034
+ }
1023
1035
  const gateway = new ProtectGateway(config);
1024
1036
  await gateway.start();
1025
1037
  }
@@ -0,0 +1,157 @@
1
+ import {
2
+ ProtectGateway
3
+ } from "./chunk-7HBHIKLN.mjs";
4
+
5
+ // src/http-transport.ts
6
+ import { createServer } from "http";
7
+ async function startHttpTransport(options) {
8
+ const { port, config, serverCommand } = options;
9
+ const sseClients = /* @__PURE__ */ new Set();
10
+ const httpConfig = {
11
+ ...config,
12
+ command: serverCommand[0],
13
+ args: serverCommand.slice(1)
14
+ };
15
+ const gateway = new ProtectGateway(httpConfig);
16
+ await gateway.startForHttp();
17
+ const server = createServer(async (req, res) => {
18
+ const origin = req.headers.origin || "*";
19
+ res.setHeader("Access-Control-Allow-Origin", origin);
20
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
21
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id");
22
+ res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
23
+ res.setHeader("Access-Control-Allow-Credentials", "true");
24
+ if (req.method === "OPTIONS") {
25
+ res.writeHead(204);
26
+ res.end();
27
+ return;
28
+ }
29
+ const url = new URL(req.url || "/", `http://localhost:${port}`);
30
+ if (url.pathname === "/health" && req.method === "GET") {
31
+ res.writeHead(200, { "Content-Type": "application/json" });
32
+ res.end(JSON.stringify({
33
+ status: "ok",
34
+ server: "protect-mcp",
35
+ version: "0.4.0",
36
+ transport: "streamable-http",
37
+ mode: config.policy ? config.enforce ? "enforce" : "shadow" : "shadow",
38
+ wrapping: serverCommand.join(" ")
39
+ }));
40
+ return;
41
+ }
42
+ if (url.pathname === "/mcp/sse" && req.method === "GET") {
43
+ res.writeHead(200, {
44
+ "Content-Type": "text/event-stream",
45
+ "Cache-Control": "no-cache",
46
+ "Connection": "keep-alive"
47
+ });
48
+ res.write(`data: ${JSON.stringify({ type: "connected", server: "protect-mcp" })}
49
+
50
+ `);
51
+ sseClients.add(res);
52
+ req.on("close", () => sseClients.delete(res));
53
+ return;
54
+ }
55
+ if (url.pathname === "/mcp" && req.method === "POST") {
56
+ let body = "";
57
+ req.on("data", (chunk) => {
58
+ body += chunk;
59
+ });
60
+ req.on("end", async () => {
61
+ try {
62
+ const jsonRpc = JSON.parse(body);
63
+ const acceptSSE = (req.headers.accept || "").includes("text/event-stream");
64
+ const responseStr = await gateway.processRequest(jsonRpc);
65
+ const response = JSON.parse(responseStr);
66
+ if (acceptSSE) {
67
+ res.writeHead(200, {
68
+ "Content-Type": "text/event-stream",
69
+ "Cache-Control": "no-cache"
70
+ });
71
+ res.write(`data: ${JSON.stringify(response)}
72
+
73
+ `);
74
+ res.end();
75
+ } else {
76
+ res.writeHead(200, { "Content-Type": "application/json" });
77
+ res.end(JSON.stringify(response));
78
+ }
79
+ if (jsonRpc.method === "tools/call") {
80
+ const event = {
81
+ type: "decision",
82
+ tool: jsonRpc.params?.name,
83
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
84
+ };
85
+ for (const client of sseClients) {
86
+ try {
87
+ client.write(`data: ${JSON.stringify(event)}
88
+
89
+ `);
90
+ } catch {
91
+ sseClients.delete(client);
92
+ }
93
+ }
94
+ }
95
+ } catch (err) {
96
+ res.writeHead(400, { "Content-Type": "application/json" });
97
+ res.end(JSON.stringify({
98
+ jsonrpc: "2.0",
99
+ error: { code: -32700, message: "Parse error" },
100
+ id: null
101
+ }));
102
+ }
103
+ });
104
+ return;
105
+ }
106
+ if (url.pathname === "/mcp" && req.method === "DELETE") {
107
+ res.writeHead(200, { "Content-Type": "application/json" });
108
+ res.end(JSON.stringify({ status: "session_closed" }));
109
+ return;
110
+ }
111
+ res.writeHead(404, { "Content-Type": "application/json" });
112
+ res.end(JSON.stringify({
113
+ error: "not_found",
114
+ endpoints: [
115
+ "POST /mcp \u2014 JSON-RPC endpoint (Streamable HTTP)",
116
+ "GET /mcp/sse \u2014 Server-Sent Events stream",
117
+ "GET /health \u2014 Health check",
118
+ "DELETE /mcp \u2014 Close session"
119
+ ]
120
+ }));
121
+ });
122
+ server.listen(port, () => {
123
+ process.stderr.write(`
124
+ [PROTECT_MCP] HTTP transport listening on http://0.0.0.0:${port}
125
+ `);
126
+ process.stderr.write(` POST /mcp \u2014 JSON-RPC (Streamable HTTP)
127
+ `);
128
+ process.stderr.write(` GET /mcp/sse \u2014 Server-Sent Events
129
+ `);
130
+ process.stderr.write(` GET /health \u2014 Health check
131
+ `);
132
+ process.stderr.write(` DELETE /mcp \u2014 Close session
133
+ `);
134
+ process.stderr.write(`
135
+ Wrapping: ${serverCommand.join(" ")}
136
+ `);
137
+ process.stderr.write(` Mode: ${config.enforce ? "enforce" : "shadow"}
138
+
139
+ `);
140
+ });
141
+ const shutdown = () => {
142
+ process.stderr.write("\n[PROTECT_MCP] Shutting down HTTP transport...\n");
143
+ for (const client of sseClients) {
144
+ try {
145
+ client.end();
146
+ } catch {
147
+ }
148
+ }
149
+ server.close();
150
+ gateway.stop();
151
+ };
152
+ process.on("SIGINT", shutdown);
153
+ process.on("SIGTERM", shutdown);
154
+ }
155
+ export {
156
+ startHttpTransport
157
+ };
package/dist/index.d.mts CHANGED
@@ -316,6 +316,9 @@ declare class ProtectGateway {
316
316
  private readonly approvalNonce;
317
317
  private currentTier;
318
318
  private admissionResult;
319
+ /** HTTP transport mode: pending response resolvers keyed by JSON-RPC id */
320
+ private pendingResponses;
321
+ private httpMode;
319
322
  constructor(config: ProtectConfig);
320
323
  start(): Promise<void>;
321
324
  setManifest(manifest: ManifestPresentation | null): AdmissionResult;
@@ -329,6 +332,22 @@ declare class ProtectGateway {
329
332
  private makeErrorResponse;
330
333
  private sendToChild;
331
334
  private sendToClient;
335
+ /**
336
+ * Enable HTTP transport mode.
337
+ * In this mode, sendToClient resolves pending promises instead of
338
+ * writing to stdout, and start() skips stdin reading.
339
+ */
340
+ enableHttpMode(): void;
341
+ /**
342
+ * Start in HTTP mode — spawns child process but does NOT read from
343
+ * process.stdin. Requests come in via processRequest() instead.
344
+ */
345
+ startForHttp(): Promise<void>;
346
+ /**
347
+ * Process a JSON-RPC request programmatically (for HTTP transport).
348
+ * Returns a promise that resolves with the JSON-RPC response string.
349
+ */
350
+ processRequest(jsonRpc: JsonRpcRequest): Promise<string>;
332
351
  private log;
333
352
  stop(): void;
334
353
  }
package/dist/index.d.ts CHANGED
@@ -316,6 +316,9 @@ declare class ProtectGateway {
316
316
  private readonly approvalNonce;
317
317
  private currentTier;
318
318
  private admissionResult;
319
+ /** HTTP transport mode: pending response resolvers keyed by JSON-RPC id */
320
+ private pendingResponses;
321
+ private httpMode;
319
322
  constructor(config: ProtectConfig);
320
323
  start(): Promise<void>;
321
324
  setManifest(manifest: ManifestPresentation | null): AdmissionResult;
@@ -329,6 +332,22 @@ declare class ProtectGateway {
329
332
  private makeErrorResponse;
330
333
  private sendToChild;
331
334
  private sendToClient;
335
+ /**
336
+ * Enable HTTP transport mode.
337
+ * In this mode, sendToClient resolves pending promises instead of
338
+ * writing to stdout, and start() skips stdin reading.
339
+ */
340
+ enableHttpMode(): void;
341
+ /**
342
+ * Start in HTTP mode — spawns child process but does NOT read from
343
+ * process.stdin. Requests come in via processRequest() instead.
344
+ */
345
+ startForHttp(): Promise<void>;
346
+ /**
347
+ * Process a JSON-RPC request programmatically (for HTTP transport).
348
+ * Returns a promise that resolves with the JSON-RPC response string.
349
+ */
350
+ processRequest(jsonRpc: JsonRpcRequest): Promise<string>;
332
351
  private log;
333
352
  stop(): void;
334
353
  }
package/dist/index.js CHANGED
@@ -868,6 +868,9 @@ var ProtectGateway = class {
868
868
  approvalNonce = (0, import_node_crypto2.randomBytes)(16).toString("hex");
869
869
  currentTier = "unknown";
870
870
  admissionResult = null;
871
+ /** HTTP transport mode: pending response resolvers keyed by JSON-RPC id */
872
+ pendingResponses = /* @__PURE__ */ new Map();
873
+ httpMode = false;
871
874
  constructor(config) {
872
875
  this.config = config;
873
876
  this.logFilePath = (0, import_node_path3.join)(process.cwd(), LOG_FILE2);
@@ -1187,8 +1190,108 @@ var ProtectGateway = class {
1187
1190
  if (this.child?.stdin?.writable) this.child.stdin.write(message + "\n");
1188
1191
  }
1189
1192
  sendToClient(message) {
1193
+ if (this.httpMode) {
1194
+ try {
1195
+ const parsed = JSON.parse(message);
1196
+ if (parsed.id !== void 0 && parsed.id !== null) {
1197
+ const pending = this.pendingResponses.get(parsed.id);
1198
+ if (pending) {
1199
+ clearTimeout(pending.timeout);
1200
+ this.pendingResponses.delete(parsed.id);
1201
+ pending.resolve(message);
1202
+ return;
1203
+ }
1204
+ }
1205
+ } catch {
1206
+ }
1207
+ }
1190
1208
  process.stdout.write(message + "\n");
1191
1209
  }
1210
+ /**
1211
+ * Enable HTTP transport mode.
1212
+ * In this mode, sendToClient resolves pending promises instead of
1213
+ * writing to stdout, and start() skips stdin reading.
1214
+ */
1215
+ enableHttpMode() {
1216
+ this.httpMode = true;
1217
+ }
1218
+ /**
1219
+ * Start in HTTP mode — spawns child process but does NOT read from
1220
+ * process.stdin. Requests come in via processRequest() instead.
1221
+ */
1222
+ async startForHttp() {
1223
+ this.httpMode = true;
1224
+ const { command, args, verbose } = this.config;
1225
+ const mode = this.config.enforce ? "enforce" : "shadow";
1226
+ if (verbose) {
1227
+ this.log(`Starting gateway in ${mode} mode (HTTP transport)`);
1228
+ this.log(`Wrapping: ${command} ${args.join(" ")}`);
1229
+ }
1230
+ this.log(`Approval nonce: ${this.approvalNonce}`);
1231
+ const childEnv = { ...process.env };
1232
+ if (this.config.credentials) {
1233
+ for (const [label, credConfig] of Object.entries(this.config.credentials)) {
1234
+ if (credConfig.inject === "env" && credConfig.name && credConfig.value_env) {
1235
+ const envValue = process.env[credConfig.value_env];
1236
+ if (envValue) {
1237
+ childEnv[credConfig.name] = envValue;
1238
+ if (verbose) this.log(`Credential "${label}": injected as env var "${credConfig.name}"`);
1239
+ }
1240
+ }
1241
+ }
1242
+ }
1243
+ this.child = (0, import_node_child_process.spawn)(command, args, { stdio: ["pipe", "pipe", "pipe"], env: childEnv });
1244
+ if (!this.child.stdin || !this.child.stdout || !this.child.stderr) {
1245
+ throw new Error("Failed to create pipes to child process");
1246
+ }
1247
+ this.child.stderr.on("data", (data) => {
1248
+ process.stderr.write(data);
1249
+ });
1250
+ const childReader = (0, import_node_readline.createInterface)({ input: this.child.stdout, crlfDelay: Infinity });
1251
+ childReader.on("line", (line) => {
1252
+ this.handleServerMessage(line);
1253
+ });
1254
+ this.child.on("exit", (code, signal) => {
1255
+ if (verbose) this.log(`Child process exited (code=${code}, signal=${signal})`);
1256
+ this.evidenceStore.save();
1257
+ });
1258
+ this.child.on("error", (err) => {
1259
+ this.log(`Child process error: ${err.message}`);
1260
+ });
1261
+ }
1262
+ /**
1263
+ * Process a JSON-RPC request programmatically (for HTTP transport).
1264
+ * Returns a promise that resolves with the JSON-RPC response string.
1265
+ */
1266
+ async processRequest(jsonRpc) {
1267
+ const REQUEST_TIMEOUT_MS = 3e4;
1268
+ if (jsonRpc.method === "tools/call" && jsonRpc.id !== void 0) {
1269
+ const blocked = await this.interceptToolCall(jsonRpc);
1270
+ if (blocked) {
1271
+ return JSON.stringify(blocked);
1272
+ }
1273
+ }
1274
+ return new Promise((resolve, reject) => {
1275
+ const id = jsonRpc.id;
1276
+ if (id === void 0 || id === null) {
1277
+ const modified2 = this.injectParamsCredentials(jsonRpc);
1278
+ this.sendToChild(JSON.stringify(modified2));
1279
+ resolve(JSON.stringify({ jsonrpc: "2.0", result: {}, id: null }));
1280
+ return;
1281
+ }
1282
+ const timeout = setTimeout(() => {
1283
+ this.pendingResponses.delete(id);
1284
+ resolve(JSON.stringify({
1285
+ jsonrpc: "2.0",
1286
+ error: { code: -32e3, message: "Request timeout (30s)" },
1287
+ id
1288
+ }));
1289
+ }, REQUEST_TIMEOUT_MS);
1290
+ this.pendingResponses.set(id, { resolve, timeout });
1291
+ const modified = this.injectParamsCredentials(jsonRpc);
1292
+ this.sendToChild(JSON.stringify(modified));
1293
+ });
1294
+ }
1192
1295
  log(message) {
1193
1296
  process.stderr.write(`[PROTECT_MCP] ${message}
1194
1297
  `);
package/dist/index.mjs CHANGED
@@ -1,9 +1,17 @@
1
+ import {
2
+ formatSimulation,
3
+ parseLogFile,
4
+ simulate
5
+ } from "./chunk-VWUN6AI6.mjs";
6
+ import {
7
+ collectSignedReceipts,
8
+ createAuditBundle
9
+ } from "./chunk-5JXFV37Y.mjs";
1
10
  import {
2
11
  ProtectGateway,
3
12
  buildDecisionContext,
4
13
  checkRateLimit,
5
14
  evaluateTier,
6
- formatSimulation,
7
15
  getSignerInfo,
8
16
  getToolPolicy,
9
17
  initSigning,
@@ -11,18 +19,12 @@ import {
11
19
  listCredentialLabels,
12
20
  loadPolicy,
13
21
  meetsMinTier,
14
- parseLogFile,
15
22
  parseRateLimit,
16
23
  queryExternalPDP,
17
24
  resolveCredential,
18
25
  signDecision,
19
- simulate,
20
26
  validateCredentials
21
- } from "./chunk-WDCPUM2O.mjs";
22
- import {
23
- collectSignedReceipts,
24
- createAuditBundle
25
- } from "./chunk-5JXFV37Y.mjs";
27
+ } from "./chunk-7HBHIKLN.mjs";
26
28
  import {
27
29
  formatReportMarkdown,
28
30
  generateReport
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "protect-mcp",
3
- "version": "0.3.3",
3
+ "version": "0.4.1",
4
4
  "mcpName": "io.github.tomjwxf/protect-mcp",
5
5
  "description": "Security gateway for MCP servers. Shadow-mode logs, per-tool policies, optional local Ed25519-signed receipts. Programmatic hooks for trust tiers, credential config, and external policy engines.",
6
6
  "main": "dist/index.js",
@@ -49,7 +49,7 @@
49
49
  "claude-code"
50
50
  ],
51
51
  "author": "Tom Farley <tommy@scopeblind.com>",
52
- "license": "FSL-1.1-MIT",
52
+ "license": "MIT",
53
53
  "homepage": "https://www.scopeblind.com",
54
54
  "repository": {
55
55
  "type": "git",