Files
orangecat/mcp-servers/shell-server.js
CatoandClaude Opus 5.5 452d2b663c fix(mcp-servers): six of seven servers never started; convert them to ESM (#1491)
* fix(mcp-servers): six of seven servers never started; convert them to ESM

mcp-servers/package.json declares "type": "module", but fs, git, lint,
shell, supabase and vitest called require() and died on their first line
with "require is not defined in ES module scope". Only github-server.js,
which already used import, ran. They now use ESM imports, as
github-server.js does. The "plain CommonJS" lint waiver in two of them
was wrong and is removed, along with fs-server's unused fsSync import.

Once they started, every tool call that returned data failed too: the
results were { type: 'json', json: ... }, which is not an MCP content
type, so the SDK rejected them (-32602). They now return
{ type: 'text', text: JSON.stringify(..., null, 2) }, as github-server
does.

fs-server imports glob and supabase-server imports @supabase/supabase-js,
but neither was declared, so they resolved from the app's node_modules
only when it happened to be installed. Both are now declared. glob is
^14.0.3, because glob 11 carries GHSA-3g3m-2fjr-6pw4 and the minimatch
advisory; list_files works unchanged on 14.

New mcp-servers/smoke.mjs (npm run smoke): starts every *-server.js,
sends initialize, notifications/initialized and tools/list over stdio,
and calls one read-only tool on fs, git, lint and shell. Main: 1/7.
This branch: 7/7.

The rest of the diff in these files is eslint --fix and prettier, which
lint-staged applies to any staged file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* fix(mcp-servers): close stat-then-read race in fs-server (CodeQL)

read_file stat()ed the path, then readFile()d it again by name, so the
size check could apply to a different file than the one read (CodeQL
js/file-system-race, high). It now opens one handle and stats and reads
through it. delete_file had the same stat-then-unlink shape. unlink
never removes a directory, so it now calls unlink directly and maps
ENOENT to not_found and EISDIR/EPERM to the old refusal.

Checked over MCP: read ok, too-large refused, missing file errors,
delete ok then not_found, directory refused, path escape refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-31 05:32:48 +01:00

137 lines
3.8 KiB
JavaScript

#!/usr/bin/env node
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { spawn } from 'child_process';
import path from 'path';
const ALLOWED = new Set([
'npm',
'npx',
'node',
'next',
'vitest',
'playwright',
'eslint',
'prettier',
'rg',
'echo',
]);
function resolveCwd(cwd) {
const root = process.cwd();
const full = path.resolve(root, cwd || '.');
const rel = path.relative(root, full);
if (rel.startsWith('..') || path.isAbsolute(rel)) {
throw new Error('cwd escapes workspace');
}
return full;
}
function runCommand(cmd, args, opt = {}) {
return new Promise(resolve => {
const start = Date.now();
const child = spawn(cmd, args, { cwd: opt.cwd, env: process.env, shell: false });
let stdout = '';
let stderr = '';
let finished = false;
const killTimer = setTimeout(() => {
if (!finished) {
finished = true;
child.kill('SIGKILL');
resolve({ code: -1, stdout, stderr: stderr + `\nTimed out after ${opt.timeout}ms` });
}
}, opt.timeout || 60000);
child.stdout.on('data', d => {
stdout += d.toString();
});
child.stderr.on('data', d => {
stderr += d.toString();
});
child.on('close', code => {
if (finished) {
return;
}
finished = true;
clearTimeout(killTimer);
resolve({ code, stdout, stderr, ms: Date.now() - start });
});
});
}
class ShellServer {
constructor() {
this.server = new Server(
{ name: 'shell-server', version: '1.0.0' },
{ capabilities: { tools: {} } }
);
this.setup();
}
setup() {
this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: 'run',
description: 'Run an allowed command with arguments',
inputSchema: {
type: 'object',
required: ['cmd'],
properties: {
cmd: { type: 'string' },
args: { type: 'array', items: { type: ['string', 'number', 'boolean'] } },
cwd: { type: 'string' },
timeout: { type: 'number', default: 60000 },
},
},
},
],
}));
this.server.setRequestHandler(CallToolRequestSchema, async req => {
const name = req.params.name;
const a = req.params.arguments || {};
try {
switch (name) {
case 'run': {
const program = String(a.cmd);
if (!ALLOWED.has(program)) {
throw new Error(`Command not allowed: ${program}`);
}
const cwd = resolveCwd(a.cwd || '.');
const args = Array.isArray(a.args) ? a.args.map(String) : [];
const res = await runCommand(program, args, { cwd, timeout: a.timeout || 60000 });
return {
content: [
{
type: 'text',
text: JSON.stringify(
{ code: res.code, stdout: res.stdout, stderr: res.stderr, ms: res.ms },
null,
2
),
},
],
};
}
default:
return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };
}
} catch (err) {
return {
content: [{ type: 'text', text: `❌ ${name} error: ${err?.message || String(err)}` }],
isError: true,
};
}
});
}
async run() {
const transport = new StdioServerTransport();
await this.server.connect(transport);
console.error('Shell MCP Server running on stdio');
}
}
new ShellServer().run();