@posewalker/mcp-xray 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bulasmam
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 CHANGED
@@ -1,3 +1,92 @@
1
- # Temporary Holding Version
1
+ # @posewalker/mcp-xray — Live Stdio Firewall, Secret Redactor & Token Profiler for MCP Servers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/@posewalker/mcp-xray.svg?color=9af8ac)](https://www.npmjs.com/package/@posewalker/mcp-xray)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-9af8ac.svg)](LICENSE)
5
+ [![Zero Dependencies](https://img.shields.io/badge/Dependencies-0%20Runtime-63c27b.svg)](#security--firewall-rules-built-in)
6
+
7
+ > **See what your MCP servers are actually executing, leaking, and costing in context tokens — before it reaches Claude Code, Cursor, Codex CLI, or Hermes.**
8
+
9
+ `mcp-xray` sits transparently between your coding agent and any stdio MCP server (`npx`, `uvx`, Python, Go, Node). Every `tools/list` and `tools/call` payload passes through an in-memory JSON-RPC 2.0 firewall with **zero runtime dependencies**.
10
+
11
+ ```text
12
+ [Claude Code / Cursor / Codex] <--stdio--> [mcp-xray firewall] <--stdio--> [Any MCP Server]
13
+ │
14
+ ├─ Measures tools/list schema token tax
15
+ ├─ Scrubs leaked API keys / DB URIs ([REDACTED])
16
+ ├─ Blocks rm -rf, DROP TABLE, ~/.ssh reads (-32001)
17
+ └─ Optional JSONL audit log (--log trace.jsonl)
18
+ ```
19
+
20
+ ## Instant 5-Second Demo (Zero Install via `npx`)
21
+
22
+ ```bash
23
+ npx -y @posewalker/mcp-xray demo
24
+ ```
25
+
26
+ Or install globally:
27
+
28
+ ```bash
29
+ npm i -g @posewalker/mcp-xray
30
+ ```
31
+
32
+ Example terminal output:
33
+
34
+ ```text
35
+ [mcp-xray] live stdio MITM attached (redact=true, blockDestructive=true)
36
+ 12:41:02.104 [SCHEMA] exposed 4 tools = ~148 tokens/turn context tax (2ms)
37
+ 12:41:02.109 [CALL ->] read_file (~14 tok)
38
+ 12:41:02.111 [<- RESP] read_file (2ms, ~24 tok)
39
+ 12:41:02.114 [CALL ->] read_env (~13 tok)
40
+ 12:41:02.116 [<-REDACT] read_env scrubbed 2 leaked secret(s) [GitHub Token, DB / URI Password] (2ms, ~48 tok)
41
+ 12:41:02.119 [BLOCK] run_shell rule=destructive-rm match=rm -rf /
42
+ [mcp-xray summary] tools=4 schema_tax=~148tok · calls=3 · blocked=1 · redacted=2 · payload=~112tok
43
+ ```
44
+
45
+ ## Drop-In Usage in `.mcp.json` (Claude Code / Cursor / Windsurf)
46
+
47
+ Simply prepend `npx -y @posewalker/mcp-xray --` in front of any existing MCP server command:
48
+
49
+ ```json
50
+ {
51
+ "mcpServers": {
52
+ "github": {
53
+ "command": "npx",
54
+ "args": ["-y", "@posewalker/mcp-xray", "--", "npx", "-y", "@modelcontextprotocol/server-github"]
55
+ },
56
+ "postgres": {
57
+ "command": "npx",
58
+ "args": ["-y", "@posewalker/mcp-xray", "--log", "/tmp/pg-mcp.jsonl", "--", "uvx", "mcp-server-postgres", "postgresql://..."]
59
+ }
60
+ }
61
+ }
62
+ ```
63
+
64
+ Or run directly from CLI:
65
+
66
+ ```bash
67
+ npx -y @posewalker/mcp-xray -- npx -y @modelcontextprotocol/server-filesystem ./repo
68
+ npx -y @posewalker/mcp-xray audit /tmp/pg-mcp.jsonl
69
+ ```
70
+
71
+ ## Security & Firewall Rules Built In
72
+
73
+ - **Credential Leak Redaction (Both Directions):** Detects and scrubs OpenAI/Anthropic `sk-` / `sk-ant-` keys, GitHub `ghp_` / `github_pat_` tokens, Google `AIza` keys, AWS `AKIA` keys, `Bearer` tokens, PEM private keys, and database password URIs (`://user:pass@host`) before tool outputs ever enter your LLM prompt context.
74
+ - **Destructive Action Firewall (`-32001` JSON-RPC Error):** Blocks downstream execution of `rm -rf` on system/home paths, `curl | sh`, `mkfs` / `dd if=`, fork bombs, `DROP TABLE` / `DROP DATABASE` / `TRUNCATE TABLE`, and direct reads of `~/.ssh/id_rsa`, `~/.ssh/id_ed25519`, `.aws/credentials`, `/etc/shadow`, and `.env.production`.
75
+ - **Context Tax Accounting:** Measures exact `tools/list` schema token overhead sent on every agent turn.
76
+
77
+ ## Flags
78
+
79
+ | Flag | Default | Description |
80
+ | --- | --- | --- |
81
+ | `--no-redact` | `false` | Disable automatic secret scrubbing |
82
+ | `--no-block` | `false` | Disable destructive command blocking |
83
+ | `--log <file>` | `off` | Append JSONL audit events to file |
84
+ | `--quiet` | `false` | Silence stderr terminal trace |
85
+
86
+ ## Companion Browser UI
87
+
88
+ Need to convert `.mcp.json` <-> Cursor <-> OpenAI Codex `config.toml` <-> Hermes `config.yaml` in browser RAM? Try [devpose.net/mcp-converter](https://devpose.net/mcp-converter) (part of [bulasmam/devpose](https://github.com/bulasmam/devpose)).
89
+
90
+ ## License
91
+
92
+ [MIT](LICENSE)
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import { runDemo } from './demo.js';
4
+ import { runStdioProxy, summarizeAuditLog } from './proxy.js';
5
+ const HELP = `mcp-xray — Live stdio JSON-RPC firewall & secret redactor for MCP servers
6
+
7
+ Usage:
8
+ mcp-xray [options] -- <mcp-command> [args...]
9
+ mcp-xray demo
10
+ mcp-xray audit <trace.jsonl>
11
+
12
+ Options:
13
+ --no-redact Disable automatic API key / URI credential redaction
14
+ --no-block Disable blocking destructive shell / SQL / SSH tool calls
15
+ --log <file> Append JSONL audit events to <file>
16
+ --quiet Suppress live terminal trace output on stderr
17
+ -h, --help Show this help message
18
+
19
+ Examples:
20
+ npx -y @posewalker/mcp-xray -- npx -y @modelcontextprotocol/server-github
21
+ npx -y @posewalker/mcp-xray --log trace.jsonl -- uvx mcp-server-postgres postgresql://...
22
+ npx -y @posewalker/mcp-xray demo
23
+ `;
24
+ async function main() {
25
+ const argv = process.argv.slice(2);
26
+ if (argv.length === 0 || argv.includes('-h') || argv.includes('--help')) {
27
+ process.stdout.write(HELP);
28
+ return;
29
+ }
30
+ if (argv[0] === 'demo') {
31
+ await runDemo();
32
+ return;
33
+ }
34
+ if (argv[0] === 'audit') {
35
+ const file = argv[1];
36
+ if (!file || !fs.existsSync(file)) {
37
+ process.stderr.write(`Usage: mcp-xray audit <existing-trace.jsonl>\n`);
38
+ process.exit(1);
39
+ }
40
+ const summary = summarizeAuditLog(fs.readFileSync(file, 'utf8'));
41
+ process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
42
+ return;
43
+ }
44
+ let redact = true;
45
+ let blockDestructive = true;
46
+ let quiet = false;
47
+ let logFile;
48
+ const sepIdx = argv.indexOf('--');
49
+ const flagSlice = sepIdx >= 0 ? argv.slice(0, sepIdx) : argv;
50
+ const cmdSlice = sepIdx >= 0 ? argv.slice(sepIdx + 1) : [];
51
+ for (let i = 0; i < flagSlice.length; i++) {
52
+ const f = flagSlice[i];
53
+ if (f === '--no-redact')
54
+ redact = false;
55
+ else if (f === '--no-block')
56
+ blockDestructive = false;
57
+ else if (f === '--quiet')
58
+ quiet = true;
59
+ else if (f === '--log' && flagSlice[i + 1]) {
60
+ logFile = flagSlice[++i];
61
+ }
62
+ else if (sepIdx < 0 && !f.startsWith('-')) {
63
+ cmdSlice.push(...flagSlice.slice(i));
64
+ break;
65
+ }
66
+ }
67
+ if (cmdSlice.length === 0) {
68
+ process.stderr.write('[mcp-xray] Missing target MCP server command. Run `mcp-xray --help`.\n');
69
+ process.exit(1);
70
+ }
71
+ const [cmd, ...args] = cmdSlice;
72
+ const code = await runStdioProxy(cmd, args, {
73
+ redact,
74
+ blockDestructive,
75
+ quiet,
76
+ logFile,
77
+ });
78
+ process.exit(code);
79
+ }
80
+ void main();
package/dist/demo.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Runs an offline self-contained MCP MITM firewall demo showing live schema tax,
3
+ * leaked secret redaction, and destructive command blocking with JSON-RPC -32001.
4
+ */
5
+ export declare function runDemo(): Promise<void>;
package/dist/demo.js ADDED
@@ -0,0 +1,87 @@
1
+ import { PassThrough } from 'node:stream';
2
+ import { attachProxyStreams } from './proxy.js';
3
+ /**
4
+ * Runs an offline self-contained MCP MITM firewall demo showing live schema tax,
5
+ * leaked secret redaction, and destructive command blocking with JSON-RPC -32001.
6
+ */
7
+ export async function runDemo() {
8
+ const clientToProxy = new PassThrough();
9
+ const proxyToClient = new PassThrough();
10
+ const proxyToServer = new PassThrough();
11
+ const serverToProxy = new PassThrough();
12
+ // Simulated MCP server reading JSON-RPC lines from proxyToServer
13
+ let serverBuf = '';
14
+ proxyToServer.on('data', (chunk) => {
15
+ serverBuf += chunk.toString('utf8');
16
+ const parts = serverBuf.split('\n');
17
+ serverBuf = parts.pop() ?? '';
18
+ for (const line of parts) {
19
+ if (!line.trim())
20
+ continue;
21
+ const req = JSON.parse(line);
22
+ if (req.method === 'initialize') {
23
+ serverToProxy.write(`${JSON.stringify({ jsonrpc: '2.0', id: req.id, result: { serverInfo: { name: 'demo-mcp', version: '1.0.0' } } })}\n`);
24
+ }
25
+ else if (req.method === 'tools/list') {
26
+ serverToProxy.write(`${JSON.stringify({
27
+ jsonrpc: '2.0',
28
+ id: req.id,
29
+ result: {
30
+ tools: [
31
+ { name: 'read_file', description: 'Read workspace source files', inputSchema: { type: 'object', properties: { path: { type: 'string' } } } },
32
+ { name: 'read_env', description: 'Inspect runtime service config', inputSchema: { type: 'object', properties: { service: { type: 'string' } } } },
33
+ { name: 'run_shell', description: 'Execute bounded shell command', inputSchema: { type: 'object', properties: { cmd: { type: 'string' } } } },
34
+ { name: 'git_status', description: 'Inspect git working tree status', inputSchema: { type: 'object', properties: {} } },
35
+ ],
36
+ },
37
+ })}\n`);
38
+ }
39
+ else if (req.method === 'tools/call') {
40
+ const name = req.params?.name;
41
+ if (name === 'read_file') {
42
+ serverToProxy.write(`${JSON.stringify({ jsonrpc: '2.0', id: req.id, result: { content: [{ type: 'text', text: 'export const version = "1.0.0"' }] } })}\n`);
43
+ }
44
+ else if (name === 'read_env') {
45
+ serverToProxy.write(`${JSON.stringify({
46
+ jsonrpc: '2.0',
47
+ id: req.id,
48
+ result: {
49
+ content: [
50
+ {
51
+ type: 'text',
52
+ text: 'GITHUB_TOKEN=ghp_DemoExposedSecret9876543210\nDB_URI=postgresql://admin:DemoPass99@db.internal:5432/prod',
53
+ },
54
+ ],
55
+ },
56
+ })}\n`);
57
+ }
58
+ }
59
+ }
60
+ });
61
+ const { flushDone } = attachProxyStreams(clientToProxy, proxyToClient, proxyToServer, serverToProxy, { redact: true, blockDestructive: true, stderr: process.stderr });
62
+ const receivedFromProxy = [];
63
+ let clientBuf = '';
64
+ proxyToClient.on('data', (chunk) => {
65
+ clientBuf += chunk.toString('utf8');
66
+ const lines = clientBuf.split('\n');
67
+ clientBuf = lines.pop() ?? '';
68
+ for (const l of lines) {
69
+ if (l.trim())
70
+ receivedFromProxy.push(l);
71
+ }
72
+ });
73
+ const send = (msg) => clientToProxy.write(`${JSON.stringify({ jsonrpc: '2.0', ...msg })}\n`);
74
+ send({ id: 1, method: 'initialize', params: {} });
75
+ send({ id: 2, method: 'tools/list', params: {} });
76
+ send({ id: 3, method: 'tools/call', params: { name: 'read_file', arguments: { path: 'src/index.ts' } } });
77
+ send({ id: 4, method: 'tools/call', params: { name: 'read_env', arguments: { service: 'billing' } } });
78
+ send({ id: 5, method: 'tools/call', params: { name: 'run_shell', arguments: { cmd: 'rm -rf /var/lib/prod' } } });
79
+ await new Promise((r) => setTimeout(r, 120));
80
+ clientToProxy.end();
81
+ serverToProxy.end();
82
+ await flushDone;
83
+ process.stderr.write('\n--- Client-facing JSON-RPC responses seen by Claude/Cursor ---\n');
84
+ for (const r of receivedFromProxy) {
85
+ process.stderr.write(`${r}\n`);
86
+ }
87
+ }
@@ -0,0 +1,27 @@
1
+ export interface SecretMatch {
2
+ rule: string;
3
+ preview: string;
4
+ path: string;
5
+ }
6
+ export interface BlockDecision {
7
+ blocked: boolean;
8
+ rule?: string;
9
+ reason?: string;
10
+ matched?: string;
11
+ }
12
+ /**
13
+ * Recursively scans JSON payloads for leaked credentials and replaces matched
14
+ * secret substrings cleanly with `[REDACTED:<TAG>]`.
15
+ */
16
+ export declare function redactSecretsInValue(value: unknown, path?: string): {
17
+ value: unknown;
18
+ matches: SecretMatch[];
19
+ };
20
+ /**
21
+ * Evaluates an outgoing `tools/call` invocation against destructive shell/SQL/credential rules.
22
+ */
23
+ export declare function evaluateToolCallPolicy(toolName: string, args: unknown, blockDestructive: boolean): BlockDecision;
24
+ /**
25
+ * Fast zero-dependency token estimator (~3.7 chars per token + JSON structural punctuation).
26
+ */
27
+ export declare function estimateTokens(text: string): number;
package/dist/policy.js ADDED
@@ -0,0 +1,136 @@
1
+ const SECRET_PATTERNS = [
2
+ { rule: 'Anthropic Key', tag: 'ANTHROPIC_KEY', regex: /\bsk-ant-[A-Za-z0-9_-]{12,}/g },
3
+ { rule: 'OpenAI / Gateway Key', tag: 'API_KEY', regex: /\bsk-[A-Za-z0-9_-]{16,}/g },
4
+ { rule: 'GitHub PAT', tag: 'GITHUB_TOKEN', regex: /\bgithub_pat_[A-Za-z0-9_]{16,}/g },
5
+ { rule: 'GitHub Token', tag: 'GITHUB_TOKEN', regex: /\bgh[pousr]_[A-Za-z0-9_]{12,}/g },
6
+ { rule: 'Google API Key', tag: 'GOOGLE_KEY', regex: /\bAIza[0-9A-Za-z_-]{20,}/g },
7
+ { rule: 'AWS Access Key', tag: 'AWS_ACCESS_KEY', regex: /\bAKIA[0-9A-Z]{16}\b/g },
8
+ {
9
+ rule: 'Private Key PEM',
10
+ tag: 'PRIVATE_KEY',
11
+ regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
12
+ },
13
+ { rule: 'Bearer Token', tag: 'BEARER_TOKEN', regex: /Bearer\s+[A-Za-z0-9._-]{14,}/gi },
14
+ { rule: 'DB / URI Password', tag: 'URI_PASSWORD', regex: /:\/\/([^:\s/@]+):([^@\s/]+)@/g },
15
+ ];
16
+ function maskPreview(val) {
17
+ if (val.length <= 10)
18
+ return '***';
19
+ return `${val.slice(0, 6)}...${val.slice(-4)}`;
20
+ }
21
+ /**
22
+ * Recursively scans JSON payloads for leaked credentials and replaces matched
23
+ * secret substrings cleanly with `[REDACTED:<TAG>]`.
24
+ */
25
+ export function redactSecretsInValue(value, path = '$') {
26
+ const matches = [];
27
+ const walk = (node, curPath) => {
28
+ if (typeof node === 'string') {
29
+ if (node.includes('[REDACTED:'))
30
+ return node;
31
+ let next = node;
32
+ for (const pat of SECRET_PATTERNS) {
33
+ pat.regex.lastIndex = 0;
34
+ if (pat.rule === 'DB / URI Password') {
35
+ next = next.replace(pat.regex, (full, user, pass) => {
36
+ if (pass.startsWith('${') || pass.startsWith('[REDACTED:'))
37
+ return full;
38
+ matches.push({ rule: pat.rule, preview: maskPreview(pass), path: curPath });
39
+ return `://${user}:[REDACTED:${pat.tag}]@`;
40
+ });
41
+ }
42
+ else if (pat.rule === 'Bearer Token') {
43
+ next = next.replace(pat.regex, (full) => {
44
+ if (full.includes('${') || full.includes('[REDACTED:'))
45
+ return full;
46
+ matches.push({ rule: pat.rule, preview: maskPreview(full), path: curPath });
47
+ return `Bearer [REDACTED:${pat.tag}]`;
48
+ });
49
+ }
50
+ else {
51
+ next = next.replace(pat.regex, (full) => {
52
+ matches.push({ rule: pat.rule, preview: maskPreview(full), path: curPath });
53
+ return `[REDACTED:${pat.tag}]`;
54
+ });
55
+ }
56
+ }
57
+ return next;
58
+ }
59
+ if (Array.isArray(node)) {
60
+ return node.map((item, idx) => walk(item, `${curPath}[${idx}]`));
61
+ }
62
+ if (node && typeof node === 'object') {
63
+ const out = {};
64
+ for (const [k, v] of Object.entries(node)) {
65
+ out[k] = walk(v, `${curPath}.${k}`);
66
+ }
67
+ return out;
68
+ }
69
+ return node;
70
+ };
71
+ return { value: walk(value, path), matches };
72
+ }
73
+ const DESTRUCTIVE_RULES = [
74
+ {
75
+ rule: 'destructive-rm',
76
+ reason: 'Recursive force deletion (`rm -rf` on root/system/home paths)',
77
+ regex: /\brm\s+-[a-z]*r[a-z]*f[a-z]*\s+(?:\/|~|\*|\.\.)|\brm\s+-[a-z]*f[a-z]*r[a-z]*\s+(?:\/|~|\*|\.\.)/i,
78
+ },
79
+ {
80
+ rule: 'pipe-to-shell',
81
+ reason: 'Remote script piped directly into shell (`curl/wget | sh/bash`)',
82
+ regex: /\b(?:curl|wget)\b[^|\n]*\|\s*(?:ba)?sh\b/i,
83
+ },
84
+ {
85
+ rule: 'disk-format',
86
+ reason: 'Low-level filesystem/device overwrite (`mkfs` / `dd if=`)',
87
+ regex: /\b(?:mkfs(?:\.[a-z0-9]+)?|dd\s+if=)\b/i,
88
+ },
89
+ {
90
+ rule: 'fork-bomb',
91
+ reason: 'Shell fork bomb pattern',
92
+ regex: /:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;?\s*:/,
93
+ },
94
+ {
95
+ rule: 'destructive-sql',
96
+ reason: 'Destructive SQL statement (`DROP TABLE/DATABASE` or `TRUNCATE TABLE`)',
97
+ regex: /\b(?:DROP\s+(?:TABLE|DATABASE|SCHEMA)|TRUNCATE\s+TABLE)\b/i,
98
+ },
99
+ {
100
+ rule: 'sensitive-ssh-aws-file',
101
+ reason: 'Direct access to SSH private key, AWS credentials, /etc/shadow, or .env.production',
102
+ regex: /(?:~\/\.ssh\/id_(?:rsa|ed25519)|\.aws\/credentials|\/etc\/shadow|\B\.env\.production\b|\B\.env\.local\b)/i,
103
+ },
104
+ ];
105
+ /**
106
+ * Evaluates an outgoing `tools/call` invocation against destructive shell/SQL/credential rules.
107
+ */
108
+ export function evaluateToolCallPolicy(toolName, args, blockDestructive) {
109
+ if (!blockDestructive)
110
+ return { blocked: false };
111
+ const haystack = `${toolName}\n${typeof args === 'string' ? args : JSON.stringify(args ?? {})}`;
112
+ for (const r of DESTRUCTIVE_RULES) {
113
+ const m = haystack.match(r.regex);
114
+ if (m) {
115
+ return {
116
+ blocked: true,
117
+ rule: r.rule,
118
+ reason: r.reason,
119
+ matched: m[0].slice(0, 80),
120
+ };
121
+ }
122
+ }
123
+ return { blocked: false };
124
+ }
125
+ /**
126
+ * Fast zero-dependency token estimator (~3.7 chars per token + JSON structural punctuation).
127
+ */
128
+ export function estimateTokens(text) {
129
+ const trimmed = text.trim();
130
+ if (!trimmed)
131
+ return 0;
132
+ const words = trimmed.split(/\s+/).length;
133
+ const charEst = Math.ceil(trimmed.length / 3.7);
134
+ const symbolBonus = (trimmed.match(/[{}\[\]():;"'<>=/\\|]/g) ?? []).length * 0.22;
135
+ return Math.max(words, Math.round(charEst + symbolBonus));
136
+ }
@@ -0,0 +1,47 @@
1
+ import type { Readable, Writable } from 'node:stream';
2
+ export interface ProxyOptions {
3
+ redact: boolean;
4
+ blockDestructive: boolean;
5
+ quiet?: boolean;
6
+ logFile?: string;
7
+ stderr?: Writable;
8
+ }
9
+ export interface SessionStats {
10
+ totalRequests: number;
11
+ toolCalls: number;
12
+ blockedCalls: number;
13
+ redactedSecrets: number;
14
+ toolCount: number;
15
+ schemaTokens: number;
16
+ payloadTokens: number;
17
+ }
18
+ export interface AuditRecord {
19
+ ts: string;
20
+ direction: 'client->server' | 'server->client' | 'firewall';
21
+ method: string;
22
+ tool?: string;
23
+ status: 'allowed' | 'blocked' | 'redacted' | 'response';
24
+ latencyMs?: number;
25
+ tokens?: number;
26
+ redactedRules?: string[];
27
+ blockRule?: string;
28
+ }
29
+ /**
30
+ * Attaches transparent JSON-RPC 2.0 inspection, secret redaction, token accounting,
31
+ * and destructive-policy enforcement between client streams and an MCP server's stdio pipes.
32
+ */
33
+ export declare function attachProxyStreams(clientIn: Readable, clientOut: Writable, serverIn: Writable, serverOut: Readable, opts: ProxyOptions): {
34
+ stats: SessionStats;
35
+ flushDone: Promise<void>;
36
+ };
37
+ /**
38
+ * Spawns a real child MCP server and wraps its stdio pipes inside mcp-xray.
39
+ */
40
+ export declare function runStdioProxy(command: string, args: string[], opts: ProxyOptions): Promise<number>;
41
+ export declare function summarizeAuditLog(jsonl: string): {
42
+ events: number;
43
+ blocked: number;
44
+ redacted: number;
45
+ totalTokens: number;
46
+ toolsSeen: string[];
47
+ };
package/dist/proxy.js ADDED
@@ -0,0 +1,271 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import readline from 'node:readline';
4
+ import { evaluateToolCallPolicy, estimateTokens, redactSecretsInValue } from './policy.js';
5
+ const ANSI = {
6
+ reset: '\x1b[0m',
7
+ green: '\x1b[38;2;154;248;172m',
8
+ mid: '\x1b[38;2;99;194;123m',
9
+ dim: '\x1b[38;2;88;130;100m',
10
+ ink: '\x1b[38;2;228;245;232m',
11
+ warn: '\x1b[38;2;255;214;102m',
12
+ red: '\x1b[38;2;255;107;107m',
13
+ };
14
+ function nowTag() {
15
+ return new Date().toISOString().slice(11, 23);
16
+ }
17
+ /**
18
+ * Attaches transparent JSON-RPC 2.0 inspection, secret redaction, token accounting,
19
+ * and destructive-policy enforcement between client streams and an MCP server's stdio pipes.
20
+ */
21
+ export function attachProxyStreams(clientIn, clientOut, serverIn, serverOut, opts) {
22
+ const errOut = opts.stderr ?? process.stderr;
23
+ const pending = new Map();
24
+ const stats = {
25
+ totalRequests: 0,
26
+ toolCalls: 0,
27
+ blockedCalls: 0,
28
+ redactedSecrets: 0,
29
+ toolCount: 0,
30
+ schemaTokens: 0,
31
+ payloadTokens: 0,
32
+ };
33
+ const log = (line) => {
34
+ if (!opts.quiet)
35
+ errOut.write(`${line}\n`);
36
+ };
37
+ const recordAudit = (rec) => {
38
+ if (!opts.logFile)
39
+ return;
40
+ try {
41
+ fs.appendFileSync(opts.logFile, `${JSON.stringify(rec)}\n`, 'utf8');
42
+ }
43
+ catch {
44
+ // Never crash proxied MCP traffic on audit file failure
45
+ }
46
+ };
47
+ log(`${ANSI.green}[mcp-xray]${ANSI.reset} ${ANSI.dim}live stdio MITM attached (redact=${opts.redact}, blockDestructive=${opts.blockDestructive})${ANSI.reset}`);
48
+ const rlClient = readline.createInterface({ input: clientIn, crlfDelay: Infinity });
49
+ const rlServer = readline.createInterface({ input: serverOut, crlfDelay: Infinity });
50
+ const clientDone = new Promise((resolve) => {
51
+ rlClient.on('line', (line) => {
52
+ const trimmed = line.trim();
53
+ if (!trimmed)
54
+ return;
55
+ let msg;
56
+ try {
57
+ msg = JSON.parse(trimmed);
58
+ }
59
+ catch {
60
+ serverIn.write(`${line}\n`);
61
+ return;
62
+ }
63
+ const id = msg.id;
64
+ const method = typeof msg.method === 'string' ? msg.method : undefined;
65
+ if (method) {
66
+ stats.totalRequests++;
67
+ const params = (msg.params ?? {});
68
+ const toolName = method === 'tools/call' && typeof params.name === 'string' ? params.name : undefined;
69
+ if (id !== undefined) {
70
+ pending.set(id, { method, toolName, startedAt: Date.now() });
71
+ }
72
+ if (method === 'tools/call' && toolName) {
73
+ stats.toolCalls++;
74
+ const decision = evaluateToolCallPolicy(toolName, params.arguments, opts.blockDestructive);
75
+ if (decision.blocked) {
76
+ stats.blockedCalls++;
77
+ log(`${ANSI.dim}${nowTag()}${ANSI.reset} ${ANSI.red}[BLOCK]${ANSI.reset} ${ANSI.ink}${toolName}${ANSI.reset} rule=${ANSI.warn}${decision.rule}${ANSI.reset} match=${ANSI.dim}${decision.matched}${ANSI.reset}`);
78
+ recordAudit({
79
+ ts: new Date().toISOString(),
80
+ direction: 'firewall',
81
+ method,
82
+ tool: toolName,
83
+ status: 'blocked',
84
+ blockRule: decision.rule,
85
+ });
86
+ if (id !== undefined) {
87
+ pending.delete(id);
88
+ const errResp = {
89
+ jsonrpc: '2.0',
90
+ id,
91
+ error: {
92
+ code: -32001,
93
+ message: `[mcp-xray] Blocked by firewall policy (${decision.rule}): ${decision.reason}`,
94
+ },
95
+ };
96
+ clientOut.write(`${JSON.stringify(errResp)}\n`);
97
+ }
98
+ return;
99
+ }
100
+ let forwardMsg = msg;
101
+ let redactionCount = 0;
102
+ let rules = [];
103
+ if (opts.redact && params.arguments !== undefined) {
104
+ const { value, matches } = redactSecretsInValue(params.arguments, 'args');
105
+ if (matches.length > 0) {
106
+ redactionCount = matches.length;
107
+ rules = [...new Set(matches.map((m) => m.rule))];
108
+ stats.redactedSecrets += matches.length;
109
+ forwardMsg = {
110
+ ...msg,
111
+ params: { ...params, arguments: value },
112
+ };
113
+ }
114
+ }
115
+ const reqTokens = estimateTokens(JSON.stringify(forwardMsg.params ?? {}));
116
+ stats.payloadTokens += reqTokens;
117
+ if (redactionCount > 0) {
118
+ log(`${ANSI.dim}${nowTag()}${ANSI.reset} ${ANSI.warn}[REDACT->]${ANSI.reset} ${ANSI.ink}${toolName}${ANSI.reset} scrubbed ${redactionCount} secret(s) (${rules.join(', ')}) ~${reqTokens} tok`);
119
+ }
120
+ else {
121
+ log(`${ANSI.dim}${nowTag()}${ANSI.reset} ${ANSI.green}[CALL ->]${ANSI.reset} ${ANSI.ink}${toolName}${ANSI.reset} ${ANSI.dim}(~${reqTokens} tok)${ANSI.reset}`);
122
+ }
123
+ recordAudit({
124
+ ts: new Date().toISOString(),
125
+ direction: 'client->server',
126
+ method,
127
+ tool: toolName,
128
+ status: redactionCount > 0 ? 'redacted' : 'allowed',
129
+ tokens: reqTokens,
130
+ redactedRules: rules.length > 0 ? rules : undefined,
131
+ });
132
+ serverIn.write(`${JSON.stringify(forwardMsg)}\n`);
133
+ return;
134
+ }
135
+ }
136
+ serverIn.write(`${line}\n`);
137
+ });
138
+ rlClient.on('close', () => {
139
+ try {
140
+ serverIn.end();
141
+ }
142
+ catch {
143
+ // Ignore already closed stream
144
+ }
145
+ resolve();
146
+ });
147
+ });
148
+ const serverDone = new Promise((resolve) => {
149
+ rlServer.on('line', (line) => {
150
+ const trimmed = line.trim();
151
+ if (!trimmed)
152
+ return;
153
+ let msg;
154
+ try {
155
+ msg = JSON.parse(trimmed);
156
+ }
157
+ catch {
158
+ clientOut.write(`${line}\n`);
159
+ return;
160
+ }
161
+ const id = msg.id;
162
+ const reqInfo = id !== undefined ? pending.get(id) : undefined;
163
+ if (id !== undefined)
164
+ pending.delete(id);
165
+ const latencyMs = reqInfo ? Date.now() - reqInfo.startedAt : undefined;
166
+ if (reqInfo?.method === 'tools/list' && msg.result && typeof msg.result === 'object') {
167
+ const resultObj = msg.result;
168
+ const tools = Array.isArray(resultObj.tools) ? resultObj.tools : [];
169
+ const schemaTok = estimateTokens(JSON.stringify(tools));
170
+ stats.toolCount = tools.length;
171
+ stats.schemaTokens += schemaTok;
172
+ log(`${ANSI.dim}${nowTag()}${ANSI.reset} ${ANSI.mid}[SCHEMA]${ANSI.reset} exposed ${ANSI.green}${tools.length}${ANSI.reset} tools = ${ANSI.warn}~${schemaTok.toLocaleString()} tokens${ANSI.reset}/turn context tax (${latencyMs ?? 0}ms)`);
173
+ recordAudit({
174
+ ts: new Date().toISOString(),
175
+ direction: 'server->client',
176
+ method: 'tools/list',
177
+ status: 'response',
178
+ latencyMs,
179
+ tokens: schemaTok,
180
+ });
181
+ clientOut.write(`${JSON.stringify(msg)}\n`);
182
+ return;
183
+ }
184
+ let outMsg = msg;
185
+ let rules = [];
186
+ let redactedNow = 0;
187
+ if (opts.redact && msg.result !== undefined) {
188
+ const { value, matches } = redactSecretsInValue(msg.result, 'result');
189
+ if (matches.length > 0) {
190
+ redactedNow = matches.length;
191
+ rules = [...new Set(matches.map((m) => m.rule))];
192
+ stats.redactedSecrets += matches.length;
193
+ outMsg = { ...msg, result: value };
194
+ }
195
+ }
196
+ const respTok = estimateTokens(JSON.stringify(outMsg.result ?? outMsg.error ?? {}));
197
+ stats.payloadTokens += respTok;
198
+ if (reqInfo?.method === 'tools/call') {
199
+ if (redactedNow > 0) {
200
+ log(`${ANSI.dim}${nowTag()}${ANSI.reset} ${ANSI.warn}[<-REDACT]${ANSI.reset} ${ANSI.ink}${reqInfo.toolName ?? 'tool'}${ANSI.reset} scrubbed ${ANSI.warn}${redactedNow} leaked secret(s)${ANSI.reset} [${rules.join(', ')}] (${latencyMs ?? 0}ms, ~${respTok} tok)`);
201
+ }
202
+ else {
203
+ log(`${ANSI.dim}${nowTag()}${ANSI.reset} ${ANSI.dim}[<- RESP]${ANSI.reset} ${ANSI.ink}${reqInfo.toolName ?? 'tool'}${ANSI.reset} ${ANSI.dim}(${latencyMs ?? 0}ms, ~${respTok} tok)${ANSI.reset}`);
204
+ }
205
+ recordAudit({
206
+ ts: new Date().toISOString(),
207
+ direction: 'server->client',
208
+ method: 'tools/call',
209
+ tool: reqInfo.toolName,
210
+ status: redactedNow > 0 ? 'redacted' : 'response',
211
+ latencyMs,
212
+ tokens: respTok,
213
+ redactedRules: rules.length > 0 ? rules : undefined,
214
+ });
215
+ }
216
+ clientOut.write(`${JSON.stringify(outMsg)}\n`);
217
+ });
218
+ rlServer.on('close', () => resolve());
219
+ });
220
+ const flushDone = Promise.all([clientDone, serverDone]).then(() => {
221
+ log(`${ANSI.green}[mcp-xray summary]${ANSI.reset} tools=${stats.toolCount} schema_tax=~${stats.schemaTokens}tok · calls=${stats.toolCalls} · ${ANSI.red}blocked=${stats.blockedCalls}${ANSI.reset} · ${ANSI.warn}redacted=${stats.redactedSecrets}${ANSI.reset} · payload=~${stats.payloadTokens}tok`);
222
+ });
223
+ return { stats, flushDone };
224
+ }
225
+ /**
226
+ * Spawns a real child MCP server and wraps its stdio pipes inside mcp-xray.
227
+ */
228
+ export async function runStdioProxy(command, args, opts) {
229
+ const child = spawn(command, args, {
230
+ stdio: ['pipe', 'pipe', 'inherit'],
231
+ shell: process.platform === 'win32',
232
+ });
233
+ const { flushDone } = attachProxyStreams(process.stdin, process.stdout, child.stdin, child.stdout, opts);
234
+ const exitCode = await new Promise((resolve) => {
235
+ child.on('exit', (code) => resolve(code ?? 0));
236
+ child.on('error', (err) => {
237
+ process.stderr.write(`[mcp-xray] Failed to spawn "${command}": ${err.message}\n`);
238
+ resolve(1);
239
+ });
240
+ });
241
+ await flushDone;
242
+ return exitCode;
243
+ }
244
+ export function summarizeAuditLog(jsonl) {
245
+ let events = 0;
246
+ let blocked = 0;
247
+ let redacted = 0;
248
+ let totalTokens = 0;
249
+ const tools = new Set();
250
+ for (const line of jsonl.split(/\r?\n/)) {
251
+ const trimmed = line.trim();
252
+ if (!trimmed)
253
+ continue;
254
+ try {
255
+ const rec = JSON.parse(trimmed);
256
+ events++;
257
+ if (rec.status === 'blocked')
258
+ blocked++;
259
+ if (rec.status === 'redacted')
260
+ redacted++;
261
+ if (typeof rec.tokens === 'number')
262
+ totalTokens += rec.tokens;
263
+ if (rec.tool)
264
+ tools.add(rec.tool);
265
+ }
266
+ catch {
267
+ // Ignore malformed line
268
+ }
269
+ }
270
+ return { events, blocked, redacted, totalTokens, toolsSeen: [...tools] };
271
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@posewalker/mcp-xray",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Live stdio JSON-RPC firewall, secret leak redactor, and schema token profiler for MCP servers (Claude Code, Cursor, Codex, Hermes). Zero runtime dependencies.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/bulasmam/mcp-xray.git"
13
+ },
14
+ "homepage": "https://devpose.net/mcp-converter",
15
+ "bin": {
16
+ "mcp-xray": "dist/cli.js"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "keywords": [
24
+ "mcp",
25
+ "model-context-protocol",
26
+ "security",
27
+ "firewall",
28
+ "claude-code",
29
+ "cursor",
30
+ "ai-agents",
31
+ "secret-scanner"
32
+ ],
33
+ "scripts": {
34
+ "build": "tsc",
35
+ "test": "vitest run",
36
+ "demo": "node dist/cli.js demo",
37
+ "prepublishOnly": "npm run build && npm test"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^22.15.3",
41
+ "typescript": "^5.8.3",
42
+ "vitest": "^3.1.2"
43
+ },
44
+ "engines": {
45
+ "node": ">=18.0.0"
46
+ }
47
+ }