mcp-fs-shell-windows 0.2.19 → 0.2.29

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 (39) hide show
  1. package/LICENSE +2 -1
  2. package/README.md +352 -190
  3. package/dist/analyze_project/handler.js +62 -0
  4. package/dist/analyze_project/schema.js +5 -0
  5. package/dist/browser/browserActions.js +128 -0
  6. package/dist/browser/fuzzySearch.js +49 -0
  7. package/dist/browser/handler.js +227 -0
  8. package/dist/browser/launcher.js +103 -0
  9. package/dist/browser/schema.js +37 -0
  10. package/dist/browser/session.js +14 -0
  11. package/dist/compat/handler.js +254 -0
  12. package/dist/compat/schema.js +97 -0
  13. package/dist/gh/handler.js +406 -0
  14. package/dist/gh/schema.js +36 -0
  15. package/dist/git/handler.js +209 -0
  16. package/dist/git/schema.js +23 -0
  17. package/dist/launch_file/handler.js +3 -1
  18. package/dist/query_database/handler.js +27 -0
  19. package/dist/query_database/schema.js +5 -0
  20. package/dist/rag/handler.js +103 -0
  21. package/dist/rag/helpers.js +126 -0
  22. package/dist/rag/schema.js +16 -0
  23. package/dist/read_document/handler.js +61 -0
  24. package/dist/read_document/schema.js +4 -0
  25. package/dist/run_javascript/handler.js +124 -0
  26. package/dist/run_javascript/schema.js +28 -0
  27. package/dist/server.js +885 -1
  28. package/dist/shell/handler.js +14 -6
  29. package/dist/subagent/handler.js +752 -0
  30. package/dist/subagent/handoffMessage.js +56 -0
  31. package/dist/subagent/schema.js +18 -0
  32. package/dist/subagent/subAgentToolCallParser.js +491 -0
  33. package/dist/subagent/toolCallValidator.js +97 -0
  34. package/dist/system/handler.js +239 -0
  35. package/dist/system/schema.js +21 -0
  36. package/dist/web/ddgParse.js +51 -0
  37. package/dist/web/handler.js +286 -0
  38. package/dist/web/schema.js +18 -0
  39. package/package.json +22 -2
@@ -0,0 +1,27 @@
1
+ // query_database/handler.ts — read-only SQLite queries (MCP filesystem fork).
2
+ //
3
+ // Port of the Beledarian query_database tool (beledarians-lm-studio-tools
4
+ // src/toolsProvider.ts), with one substitution: the reference uses the native
5
+ // better-sqlite3 module; this fork runs on system Node which ships the built-in
6
+ // node:sqlite module (DatabaseSync), so no native dependency is added. Same
7
+ // behavior: naive write-statement block, open READONLY, prepare + all(), close,
8
+ // return { results } or { error }.
9
+ import { DatabaseSync } from "node:sqlite";
10
+ import { validatePath } from "../helpers/path.js";
11
+ export async function handleQueryDatabase(dbPath, query, allowedDirectories) {
12
+ const fpath = await validatePath(dbPath, allowedDirectories);
13
+ // Safety: Attempt to block write operations (naive check)
14
+ if (/^\s*(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|REPLACE)\b/i.test(query)) {
15
+ return JSON.stringify({ error: "Only SELECT/read queries are allowed for safety." });
16
+ }
17
+ try {
18
+ const db = new DatabaseSync(fpath, { readOnly: true });
19
+ const stmt = db.prepare(query);
20
+ const results = stmt.all();
21
+ db.close();
22
+ return JSON.stringify({ results });
23
+ }
24
+ catch (e) {
25
+ return JSON.stringify({ error: `Database query failed: ${e instanceof Error ? e.message : String(e)}` });
26
+ }
27
+ }
@@ -0,0 +1,5 @@
1
+ import { z } from "zod";
2
+ export const QueryDatabaseArgsSchema = z.object({
3
+ db_path: z.string(),
4
+ query: z.string(),
5
+ });
@@ -0,0 +1,103 @@
1
+ // rag/handler.ts — RAG tools (MCP filesystem fork).
2
+ //
3
+ // Port of the Beledarian rag_local_files (beledarians-lm-studio-tools
4
+ // src/toolsProvider.ts L2389-2463) and rag_web_content (L1706-1754) tools.
5
+ // Same behavior throughout: rag_local_files recursively scans up to 50 text
6
+ // files, chunks on blank lines (>20 chars), keeps chunks scoring above
7
+ // cosine similarity 0.4, and returns the top 10 with {file, score, content}
8
+ // (score as a 3-decimal string, exactly like the reference). rag_web_content
9
+ // fetches the URL, converts to plain text with html-to-text (the same
10
+ // options the fork's fetch_web_content tool uses), and returns the top 5
11
+ // chunks from performRagOnText. Embedding goes through the LM Studio
12
+ // /v1/embeddings endpoint (see helpers.ts) instead of the SDK client.
13
+ import fs from "fs/promises";
14
+ import path from "path";
15
+ import { validatePath } from "../helpers/path.js";
16
+ import { chunkText, cosineSimilarity, embedStrings, performRagOnText } from "./helpers.js";
17
+ export async function handleRagLocalFiles(query, searchPath, filePattern, allowedDirectories) {
18
+ try {
19
+ const targetDir = await validatePath(searchPath ?? ".", allowedDirectories);
20
+ const entries = await fs.readdir(targetDir, { recursive: true, withFileTypes: true });
21
+ const textFiles = entries.filter((e) => e.isFile() && !e.name.match(/\.(png|jpg|jpeg|gif|ico|exe|dll|bin)$/i));
22
+ // Filter by pattern if provided
23
+ const filteredFiles = filePattern
24
+ ? textFiles.filter((e) => e.name.includes(filePattern) || path.join(e.parentPath, e.name).includes(filePattern))
25
+ : textFiles;
26
+ // Limit to avoid massive reads. In a real 'Gemini Flow' robust
27
+ // implementation, we'd use an index. Here we'll read top 50 files max to be safe.
28
+ const filesToScan = filteredFiles.slice(0, 50);
29
+ let allChunks = [];
30
+ const [queryEmbedding] = await embedStrings([query]);
31
+ for (const file of filesToScan) {
32
+ try {
33
+ const fullPath = path.join(file.parentPath, file.name);
34
+ const content = await fs.readFile(fullPath, "utf-8");
35
+ // reuse chunking logic
36
+ const chunks = chunkText(content);
37
+ if (chunks.length === 0)
38
+ continue;
39
+ // Batch embed chunks for this file
40
+ const chunkEmbeddings = await embedStrings(chunks);
41
+ chunks.forEach((chunk, i) => {
42
+ const score = cosineSimilarity(queryEmbedding, chunkEmbeddings[i]);
43
+ if (score > 0.4) { // Threshold
44
+ allChunks.push({ chunk, score, file: file.name });
45
+ }
46
+ });
47
+ }
48
+ catch {
49
+ // ignore read errors
50
+ }
51
+ }
52
+ // Sort all chunks
53
+ allChunks.sort((a, b) => b.score - a.score);
54
+ return JSON.stringify({
55
+ query,
56
+ results: allChunks.slice(0, 10).map((c) => ({
57
+ file: c.file,
58
+ score: c.score.toFixed(3),
59
+ content: c.chunk,
60
+ })),
61
+ });
62
+ }
63
+ catch (error) {
64
+ return JSON.stringify({
65
+ error: `Local RAG failed: ${error instanceof Error ? error.message : String(error)}`,
66
+ });
67
+ }
68
+ }
69
+ export async function handleRagWebContent(url, query) {
70
+ try {
71
+ // 1. Fetch content
72
+ const response = await fetch(url);
73
+ if (!response.ok) {
74
+ throw new Error(`HTTP error! status: ${response.status}`);
75
+ }
76
+ let text = await response.text();
77
+ // Same text extraction the fork's fetch_web_content tool uses
78
+ const { compile } = await import("html-to-text");
79
+ const compiledConvert = compile({
80
+ wordwrap: false,
81
+ selectors: [
82
+ { selector: "a", options: { ignoreHref: true } },
83
+ { selector: "img", format: "skip" },
84
+ ],
85
+ });
86
+ text = compiledConvert(text);
87
+ if (text.length === 0) {
88
+ return JSON.stringify({ error: "Could not extract any text from the URL." });
89
+ }
90
+ // 2. Perform RAG
91
+ const ragResults = await performRagOnText(text, query);
92
+ return JSON.stringify({
93
+ url: url,
94
+ query: query,
95
+ relevant_chunks: ragResults,
96
+ });
97
+ }
98
+ catch (error) {
99
+ return JSON.stringify({
100
+ error: `Failed during RAG web search: ${error instanceof Error ? error.message : String(error)}`,
101
+ });
102
+ }
103
+ }
@@ -0,0 +1,126 @@
1
+ // rag/helpers.ts — shared RAG helpers (MCP filesystem fork).
2
+ //
3
+ // Port of the Beledarian RAG core (beledarians-lm-studio-tools
4
+ // src/toolsProvider.ts: cosineSimilarity L76-84, performRagOnText L86-110),
5
+ // with one substitution: the reference embeds through the LM Studio SDK
6
+ // client; this fork runs on plain Node, so embedding is a fetch against
7
+ // LM Studio's OpenAI-compatible API: POST http://127.0.0.1:1234/v1/embeddings
8
+ // with JSON { model, input: [strings] } and (when a token is available)
9
+ // Authorization: Bearer <token>. The token is read from MCP_API_TOKEN_FILE
10
+ // (or, when unset, the reference machine's overnight pipeline token file);
11
+ // if that file is missing or empty the request is sent keyless. The endpoint
12
+ // is MCP_RAG_EMBED_URL when set. All thresholds, chunking, and top-N
13
+ // behavior are identical
14
+ // to the reference.
15
+ import fs from "fs";
16
+ const DEFAULT_EMBEDDINGS_URL = "http://127.0.0.1:1234/v1/embeddings";
17
+ // Reference machine's overnight pipeline token file (kept for back-compat;
18
+ // on other machines the file is simply absent -> keyless request).
19
+ const LEGACY_TOKEN_FILE = "C:/Users/Gerar/.beledarians-llm-toolbox/workspace/overnight/lm_api_token.txt";
20
+ // Env overrides (v0.2.29 publish portability). When unset, behavior on the
21
+ // reference machine is unchanged.
22
+ function getEmbeddingsUrl() {
23
+ const o = process.env.MCP_RAG_EMBED_URL;
24
+ return o && o.trim() ? o.trim() : DEFAULT_EMBEDDINGS_URL;
25
+ }
26
+ function getTokenFile() {
27
+ const o = process.env.MCP_API_TOKEN_FILE;
28
+ return o && o.trim() ? o.trim() : LEGACY_TOKEN_FILE;
29
+ }
30
+ const DEFAULT_EMBED_MODEL = "text-embedding-nomic-embed-text-v1.5";
31
+ // Read the API token fresh on every call (small file; rotation stays live).
32
+ function readApiKey() {
33
+ try {
34
+ const token = fs.readFileSync(getTokenFile(), "utf-8").trim();
35
+ return token.length > 0 ? token : null;
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ // Env override for the embedding model id (LM Studio resolves model ids the
42
+ // same way for the /v1/embeddings endpoint).
43
+ function getEmbedModel() {
44
+ const override = process.env.MCP_RAG_EMBED_MODEL;
45
+ return override && override.trim().length > 0 ? override.trim() : DEFAULT_EMBED_MODEL;
46
+ }
47
+ // Embed a batch of strings. Response shape: {data: [{embedding: number[], index}]}.
48
+ // Results are mapped back to input order by `index`. One retry (2 attempts)
49
+ // on transient network/API errors with a short backoff — the first embedding
50
+ // call of a session can trigger an auto-load of the embedding model on its
51
+ // own llama-server, which takes a few seconds.
52
+ export async function embedStrings(strings) {
53
+ if (strings.length === 0)
54
+ return [];
55
+ let lastError = null;
56
+ for (let attempt = 0; attempt < 2; attempt++) {
57
+ try {
58
+ const headers = {
59
+ "Content-Type": "application/json",
60
+ };
61
+ const token = readApiKey();
62
+ if (token)
63
+ headers["Authorization"] = `Bearer ${token}`;
64
+ const res = await fetch(getEmbeddingsUrl(), {
65
+ method: "POST",
66
+ headers,
67
+ body: JSON.stringify({ model: getEmbedModel(), input: strings }),
68
+ });
69
+ if (!res.ok) {
70
+ const body = await res.text().catch(() => "");
71
+ throw new Error(`embeddings HTTP ${res.status}: ${body.slice(0, 300)}`);
72
+ }
73
+ const data = await res.json();
74
+ if (!data || !Array.isArray(data.data)) {
75
+ throw new Error("embeddings response missing data array");
76
+ }
77
+ const byIndex = new Map();
78
+ for (const item of data.data) {
79
+ byIndex.set(item.index, item.embedding);
80
+ }
81
+ return strings.map((_, i) => {
82
+ const e = byIndex.get(i);
83
+ if (!Array.isArray(e) || e.length === 0) {
84
+ throw new Error(`embeddings response missing embedding for index ${i}`);
85
+ }
86
+ return e;
87
+ });
88
+ }
89
+ catch (e) {
90
+ lastError = e;
91
+ await new Promise((r) => setTimeout(r, 2000));
92
+ }
93
+ }
94
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
95
+ }
96
+ // Helper function for cosine similarity (identical to the reference).
97
+ export function cosineSimilarity(vecA, vecB) {
98
+ const dotProduct = vecA.reduce((acc, val, i) => acc + val * vecB[i], 0);
99
+ const magA = Math.sqrt(vecA.reduce((acc, val) => acc + val * val, 0));
100
+ const magB = Math.sqrt(vecB.reduce((acc, val) => acc + val * val, 0));
101
+ if (magA === 0 || magB === 0) {
102
+ return 0;
103
+ }
104
+ return dotProduct / (magA * magB);
105
+ }
106
+ // Paragraph-based chunking (identical to the reference): split on blank
107
+ // lines, keep chunks with more than 20 non-whitespace characters.
108
+ export function chunkText(text) {
109
+ return text.split(/\n\s*\n/).filter((chunk) => chunk.trim().length > 20);
110
+ }
111
+ // Main RAG-on-text helper (identical behavior to the reference:
112
+ // chunk, embed query + chunks, cosine similarity, sort, top 5).
113
+ export async function performRagOnText(text, query) {
114
+ const chunks = chunkText(text);
115
+ if (chunks.length === 0) {
116
+ return [{ chunk: text.substring(0, 4000), score: 1 }];
117
+ }
118
+ const [queryEmbedding] = await embedStrings([query]);
119
+ const chunkEmbeddings = await embedStrings(chunks);
120
+ const similarities = chunkEmbeddings.map((chunkEmb, i) => ({
121
+ chunk: chunks[i],
122
+ score: cosineSimilarity(queryEmbedding, chunkEmb),
123
+ }));
124
+ similarities.sort((a, b) => b.score - a.score);
125
+ return similarities.slice(0, 5); // Return top 5
126
+ }
@@ -0,0 +1,16 @@
1
+ import { z } from "zod";
2
+ export const RagLocalFilesArgsSchema = z.object({
3
+ query: z.string().describe("The search query to match file contents against"),
4
+ path: z
5
+ .string()
6
+ .optional()
7
+ .describe("Root directory to search (default: the server process's working directory). Must be within an allowed directory."),
8
+ file_pattern: z
9
+ .string()
10
+ .optional()
11
+ .describe("File pattern to include (e.g. '.ts', 'src/'). Default: all text files."),
12
+ });
13
+ export const RagWebContentArgsSchema = z.object({
14
+ url: z.string().describe("The URL to fetch"),
15
+ query: z.string().describe("The query to find relevant content for"),
16
+ });
@@ -0,0 +1,61 @@
1
+ // read_document/handler.ts — read content from PDF or DOCX files (MCP filesystem fork).
2
+ //
3
+ // Port of the Beledarian read_document tool (beledarians-lm-studio-tools
4
+ // src/toolsProvider.ts). PDF via pdf-parse v2 class-based API
5
+ // (new PDFParse({ data }) -> getText() / getInfo() / destroy()); DOCX via
6
+ // mammoth extractRawText. The DOMMatrix polyfill is required by pdf-parse v2
7
+ // (pdfjs) in a bare Node environment and is ported VERBATIM from the reference.
8
+ import { readFile } from "fs/promises";
9
+ import { validatePath } from "../helpers/path.js";
10
+ // Polyfill DOMMatrix for pdf-parse v2 (required for node environment)
11
+ function ensureDomMatrix() {
12
+ if (typeof global.DOMMatrix === "undefined") {
13
+ global.DOMMatrix = class DOMMatrix {
14
+ constructor(arg) {
15
+ this.a = 1;
16
+ this.b = 0;
17
+ this.c = 0;
18
+ this.d = 1;
19
+ this.e = 0;
20
+ this.f = 0;
21
+ if (Array.isArray(arg)) {
22
+ this.a = arg[0];
23
+ this.b = arg[1];
24
+ this.c = arg[2];
25
+ this.d = arg[3];
26
+ this.e = arg[4];
27
+ this.f = arg[5];
28
+ }
29
+ }
30
+ };
31
+ }
32
+ }
33
+ export async function handleReadDocument(filePath, allowedDirectories) {
34
+ const fpath = await validatePath(filePath, allowedDirectories);
35
+ const ext = fpath.split('.').pop()?.toLowerCase();
36
+ try {
37
+ if (ext === 'pdf') {
38
+ ensureDomMatrix();
39
+ // Dynamically import pdf-parse v2 (ESM equivalent of the reference's require)
40
+ const { PDFParse } = await import("pdf-parse");
41
+ const dataBuffer = await readFile(fpath);
42
+ // Use new class-based API
43
+ const parser = new PDFParse({ data: dataBuffer });
44
+ const textResult = await parser.getText();
45
+ const infoResult = await parser.getInfo(); // Optional: get metadata
46
+ await parser.destroy(); // Cleanup
47
+ return JSON.stringify({ content: textResult.text, metadata: infoResult.info });
48
+ }
49
+ else if (ext === 'docx') {
50
+ const mammoth = await import("mammoth");
51
+ const result = await mammoth.extractRawText({ path: fpath });
52
+ return JSON.stringify({ content: result.value, messages: result.messages });
53
+ }
54
+ else {
55
+ return JSON.stringify({ error: "Unsupported document format. Use read_file for text files." });
56
+ }
57
+ }
58
+ catch (e) {
59
+ return JSON.stringify({ error: `Failed to read document: ${e instanceof Error ? e.message : String(e)}` });
60
+ }
61
+ }
@@ -0,0 +1,4 @@
1
+ import { z } from "zod";
2
+ export const ReadDocumentArgsSchema = z.object({
3
+ file_path: z.string(),
4
+ });
@@ -0,0 +1,124 @@
1
+ // run_javascript/handler.ts — unrestricted JS/TS snippet execution (MCP filesystem fork).
2
+ //
3
+ // Runs a snippet on the Deno runtime with FULL permissions (no sandbox):
4
+ // the script may read/write anywhere the server user can reach (drive letters
5
+ // and UNC paths), use the network, read the environment, spawn processes, and
6
+ // import arbitrary modules (node:*, npm:*, https:*). This is the "free"
7
+ // counterpart to the other run_javascript tools, which confine snippets to a
8
+ // working directory with net/env/sys/run/ffi denied.
9
+ //
10
+ // Engine resolution (first hit wins; result is cached):
11
+ // 1. $DENO_PATH env var (absolute path to a deno binary)
12
+ // 2. <ancestor>/.internal/utils/deno(.exe) walking up from the server CWD
13
+ // (LM Studio bundles deno at <home>/.internal/utils)
14
+ // 3. <user home>/.lmstudio/.internal/utils/deno(.exe)
15
+ // 4. deno on PATH
16
+ //
17
+ // Reuses the shell layer's spawn/capture machinery (runCaptured + caps).
18
+ import fsp from "fs/promises";
19
+ import fs from "fs";
20
+ import nodePath from "path";
21
+ import os from "os";
22
+ import crypto from "crypto";
23
+ import { RUN_JS_MAX_TIMEOUT_SEC } from "./schema.js";
24
+ import { cap, CAP_OK, CAP_ERR, SHELL_JOBS_DIR, ensureJobsDir, resolveCwd, runCaptured, } from "../shell/handler.js";
25
+ function denoName() {
26
+ return process.platform === "win32" ? "deno.exe" : "deno";
27
+ }
28
+ let cachedDenoPath;
29
+ export function resolveDenoPath() {
30
+ if (cachedDenoPath !== undefined)
31
+ return cachedDenoPath;
32
+ let found = null;
33
+ // 1. explicit override
34
+ const env = process.env.DENO_PATH;
35
+ if (env && fs.existsSync(env))
36
+ found = env;
37
+ // 2. walk up from the server CWD: <dir>/.internal/utils/deno(.exe)
38
+ if (!found) {
39
+ let dir = process.cwd();
40
+ for (let i = 0; i < 8 && !found; i++) {
41
+ const candidate = nodePath.join(dir, ".internal", "utils", denoName());
42
+ if (fs.existsSync(candidate))
43
+ found = candidate;
44
+ const parent = nodePath.dirname(dir);
45
+ if (parent === dir)
46
+ break;
47
+ dir = parent;
48
+ }
49
+ }
50
+ // 3. typical LM Studio user install: <home>/.lmstudio/.internal/utils/deno(.exe)
51
+ if (!found) {
52
+ const candidate = nodePath.join(os.homedir(), ".lmstudio", ".internal", "utils", denoName());
53
+ if (fs.existsSync(candidate))
54
+ found = candidate;
55
+ }
56
+ // 4. PATH lookup
57
+ if (!found) {
58
+ const dirs = (process.env.PATH ?? "").split(nodePath.delimiter).filter(Boolean);
59
+ for (const d of dirs) {
60
+ const candidate = nodePath.join(d, denoName());
61
+ if (fs.existsSync(candidate)) {
62
+ found = candidate;
63
+ break;
64
+ }
65
+ }
66
+ }
67
+ cachedDenoPath = found;
68
+ return found;
69
+ }
70
+ export async function handleRunJavascriptFree(javascript, timeoutSeconds, cwd) {
71
+ const deno = resolveDenoPath();
72
+ if (!deno) {
73
+ throw new Error("No Deno runtime found. Set the DENO_PATH environment variable to a deno binary, " +
74
+ "install deno on PATH, or run this server from inside an LM Studio installation " +
75
+ "(which bundles deno at <home>/.internal/utils/deno.exe).");
76
+ }
77
+ const abs = await resolveCwd(cwd);
78
+ await ensureJobsDir();
79
+ const file = nodePath.join(SHELL_JOBS_DIR, `js-${Date.now().toString(36)}-${crypto.randomBytes(3).toString("hex")}.ts`);
80
+ await fsp.writeFile(file, javascript, "utf-8");
81
+ const timeout = Math.min(Math.max(timeoutSeconds ?? 5, 0.1), RUN_JS_MAX_TIMEOUT_SEC);
82
+ const started = Date.now();
83
+ try {
84
+ const r = await runCaptured(deno, [
85
+ "run",
86
+ "--no-prompt",
87
+ "--allow-read",
88
+ "--allow-write",
89
+ "--allow-net",
90
+ "--allow-env",
91
+ "--allow-sys",
92
+ "--allow-run",
93
+ "--allow-ffi",
94
+ "--allow-import",
95
+ file,
96
+ ], {
97
+ cwd: abs,
98
+ timeoutMs: timeout * 1000,
99
+ env: { ...process.env, NO_COLOR: "true" },
100
+ });
101
+ const durationMs = Date.now() - started;
102
+ if (r.spawnError) {
103
+ throw new Error(`Failed to launch deno: ${r.spawnError}`);
104
+ }
105
+ if (r.timedOut) {
106
+ throw new Error(`Process timed out after ${timeout}s.\nSTDOUT:\n${cap(r.stdout, CAP_ERR)}\nSTDERR:\n${cap(r.stderr, CAP_ERR)}`);
107
+ }
108
+ if (r.code !== 0) {
109
+ throw new Error(`Process exited with code ${r.code ?? "unknown"}.\nSTDOUT:\n${cap(r.stdout, CAP_ERR)}\nSTDERR:\n${cap(r.stderr, CAP_ERR)}`);
110
+ }
111
+ return JSON.stringify({
112
+ exitCode: 0,
113
+ stdout: cap(r.stdout, CAP_OK),
114
+ stderr: cap(r.stderr, CAP_OK),
115
+ timedOut: false,
116
+ duration_ms: durationMs,
117
+ cwd: abs,
118
+ deno,
119
+ });
120
+ }
121
+ finally {
122
+ await fsp.unlink(file).catch(() => undefined);
123
+ }
124
+ }
@@ -0,0 +1,28 @@
1
+ // run_javascript/schema.ts — argument schema for the unrestricted JS/TS execution tool.
2
+ // (MCP filesystem fork: the "free" run_javascript — no working-directory sandbox.)
3
+ import { z } from "zod";
4
+ // Unlike the shell tools (28 s cap), this tool may run up to 60 s: the MCP
5
+ // client request window was measured >63 s (a ~63 s in-harness tool call
6
+ // survived, 2026-08-29), and 60 s matches the sibling run_javascript tools.
7
+ export const RUN_JS_MAX_TIMEOUT_SEC = 60;
8
+ // ---------------------------------------------------------------------------
9
+ // Tool description (verbatim — pasted into server.ts ListTools entry):
10
+ //
11
+ // run_javascript_free:
12
+ // "Run a JavaScript/TypeScript code snippet on the Deno runtime with UNRESTRICTED permissions: full filesystem read/write (any drive or UNC path the server user can reach), network access, environment variables, child processes, and arbitrary imports (node:*, npm:*, https:*) — unlike the other run_javascript tools, there is no working-directory sandbox. The code is written to a temp .ts file and run; returns exit code, stdout, and stderr. Default 5 s timeout, max 60 s; optional cwd (defaults to the shell_cwd default). Non-zero exit or timeout returns an error that still includes the captured output. Requires a Deno binary: $DENO_PATH, <LM Studio home>/.internal/utils/deno(.exe) (found by walking up from the server CWD or the user home), or deno on PATH."
13
+ // ---------------------------------------------------------------------------
14
+ export const RunJavascriptFreeArgsSchema = z.object({
15
+ javascript: z
16
+ .string()
17
+ .describe("JavaScript (or TypeScript) code to execute. Runs as a Deno script: Deno.* APIs, console.log, and imports (node:*, npm:*, https:*) all work."),
18
+ timeout_seconds: z
19
+ .number()
20
+ .min(0.1)
21
+ .max(RUN_JS_MAX_TIMEOUT_SEC)
22
+ .optional()
23
+ .describe("Timeout in seconds (default: 5, max: 60)."),
24
+ cwd: z
25
+ .string()
26
+ .optional()
27
+ .describe("Working directory for the snippet (default: the shell_cwd default)."),
28
+ });