|
| 1 | +import * as fs from "fs/promises" |
| 2 | +import * as path from "path" |
| 3 | +import { stdin, stdout, stderr } from "process" |
| 4 | + |
| 5 | +type JsonRpcMessage = { |
| 6 | + jsonrpc: "2.0" |
| 7 | + id?: string | number |
| 8 | + method?: string |
| 9 | + params?: { |
| 10 | + name?: string |
| 11 | + arguments?: Record<string, unknown> |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +const workspaceDir = process.argv[2] |
| 16 | +const readyFile = process.env.MCP_TEST_READY_FILE |
| 17 | + |
| 18 | +if (!workspaceDir) { |
| 19 | + stderr.write("Missing workspace directory argument\n") |
| 20 | + process.exit(1) |
| 21 | +} |
| 22 | + |
| 23 | +let buffer = "" |
| 24 | + |
| 25 | +stdin.setEncoding("utf8") |
| 26 | +stdin.on("data", (chunk) => { |
| 27 | + buffer += chunk |
| 28 | + processBuffer().catch((error) => { |
| 29 | + stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`) |
| 30 | + }) |
| 31 | +}) |
| 32 | + |
| 33 | +async function processBuffer() { |
| 34 | + let newlineIndex = buffer.indexOf("\n") |
| 35 | + while (newlineIndex !== -1) { |
| 36 | + const line = buffer.slice(0, newlineIndex).trim() |
| 37 | + buffer = buffer.slice(newlineIndex + 1) |
| 38 | + |
| 39 | + if (line) { |
| 40 | + await handleMessage(JSON.parse(line) as JsonRpcMessage) |
| 41 | + } |
| 42 | + |
| 43 | + newlineIndex = buffer.indexOf("\n") |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +async function handleMessage(message: JsonRpcMessage) { |
| 48 | + if (message.id === undefined) { |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + try { |
| 53 | + switch (message.method) { |
| 54 | + case "initialize": |
| 55 | + sendResult(message.id, { |
| 56 | + protocolVersion: "2024-11-05", |
| 57 | + capabilities: { tools: {} }, |
| 58 | + serverInfo: { name: "test-filesystem-server", version: "1.0.0" }, |
| 59 | + }) |
| 60 | + break |
| 61 | + case "tools/list": |
| 62 | + await markReady() |
| 63 | + sendResult(message.id, { tools: getTools() }) |
| 64 | + break |
| 65 | + case "resources/list": |
| 66 | + sendResult(message.id, { resources: [] }) |
| 67 | + break |
| 68 | + case "resources/templates/list": |
| 69 | + sendResult(message.id, { resourceTemplates: [] }) |
| 70 | + break |
| 71 | + case "tools/call": |
| 72 | + sendResult(message.id, await callTool(message.params?.name, message.params?.arguments ?? {})) |
| 73 | + break |
| 74 | + default: |
| 75 | + sendResult(message.id, {}) |
| 76 | + } |
| 77 | + } catch (error) { |
| 78 | + sendError(message.id, error instanceof Error ? error.message : String(error)) |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +function sendResult(id: string | number, result: unknown) { |
| 83 | + stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`) |
| 84 | +} |
| 85 | + |
| 86 | +function sendError(id: string | number, message: string) { |
| 87 | + stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32603, message } })}\n`) |
| 88 | +} |
| 89 | + |
| 90 | +async function markReady() { |
| 91 | + if (!readyFile) { |
| 92 | + return |
| 93 | + } |
| 94 | + |
| 95 | + await fs.mkdir(path.dirname(readyFile), { recursive: true }) |
| 96 | + await fs.writeFile(readyFile, "ready") |
| 97 | +} |
| 98 | + |
| 99 | +function getTools() { |
| 100 | + const pathInputSchema = { |
| 101 | + type: "object", |
| 102 | + properties: { |
| 103 | + path: { type: "string" }, |
| 104 | + }, |
| 105 | + required: ["path"], |
| 106 | + } |
| 107 | + |
| 108 | + return [ |
| 109 | + { |
| 110 | + name: "read_file", |
| 111 | + description: "Read a file from the test workspace.", |
| 112 | + inputSchema: pathInputSchema, |
| 113 | + }, |
| 114 | + { |
| 115 | + name: "write_file", |
| 116 | + description: "Write a file in the test workspace.", |
| 117 | + inputSchema: { |
| 118 | + type: "object", |
| 119 | + properties: { |
| 120 | + path: { type: "string" }, |
| 121 | + content: { type: "string" }, |
| 122 | + }, |
| 123 | + required: ["path", "content"], |
| 124 | + }, |
| 125 | + }, |
| 126 | + { |
| 127 | + name: "list_directory", |
| 128 | + description: "List a directory in the test workspace.", |
| 129 | + inputSchema: pathInputSchema, |
| 130 | + }, |
| 131 | + { |
| 132 | + name: "directory_tree", |
| 133 | + description: "Return a JSON directory tree for a test workspace path.", |
| 134 | + inputSchema: pathInputSchema, |
| 135 | + }, |
| 136 | + { |
| 137 | + name: "get_file_info", |
| 138 | + description: "Return basic metadata for a file in the test workspace.", |
| 139 | + inputSchema: pathInputSchema, |
| 140 | + }, |
| 141 | + ] |
| 142 | +} |
| 143 | + |
| 144 | +async function callTool(name: string | undefined, args: Record<string, unknown>) { |
| 145 | + const requestedPath = typeof args.path === "string" ? args.path : "" |
| 146 | + |
| 147 | + switch (name) { |
| 148 | + case "read_file": { |
| 149 | + const filePath = resolveWorkspacePath(requestedPath) |
| 150 | + return textResult(await fs.readFile(filePath, "utf8")) |
| 151 | + } |
| 152 | + case "write_file": { |
| 153 | + const filePath = resolveWorkspacePath(requestedPath) |
| 154 | + const content = typeof args.content === "string" ? args.content : "" |
| 155 | + await fs.mkdir(path.dirname(filePath), { recursive: true }) |
| 156 | + await fs.writeFile(filePath, content) |
| 157 | + return textResult(`Successfully wrote to ${requestedPath}`) |
| 158 | + } |
| 159 | + case "list_directory": { |
| 160 | + const directoryPath = resolveWorkspacePath(requestedPath) |
| 161 | + const entries = await fs.readdir(directoryPath, { withFileTypes: true }) |
| 162 | + const listing = entries |
| 163 | + .sort((a, b) => a.name.localeCompare(b.name)) |
| 164 | + .map((entry) => `${entry.isDirectory() ? "[DIR]" : "[FILE]"} ${entry.name}`) |
| 165 | + .join("\n") |
| 166 | + return textResult(listing) |
| 167 | + } |
| 168 | + case "directory_tree": { |
| 169 | + const directoryPath = resolveWorkspacePath(requestedPath) |
| 170 | + return textResult(JSON.stringify(await buildDirectoryTree(directoryPath), null, 2)) |
| 171 | + } |
| 172 | + case "get_file_info": { |
| 173 | + const filePath = resolveWorkspacePath(requestedPath) |
| 174 | + const stats = await fs.stat(filePath) |
| 175 | + return textResult( |
| 176 | + [ |
| 177 | + `size: ${stats.size}`, |
| 178 | + `isFile: ${stats.isFile()}`, |
| 179 | + `isDirectory: ${stats.isDirectory()}`, |
| 180 | + `permissions: ${stats.mode.toString(8)}`, |
| 181 | + ].join("\n"), |
| 182 | + ) |
| 183 | + } |
| 184 | + default: |
| 185 | + throw new Error(`Unknown tool: ${name}`) |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +function textResult(text: string) { |
| 190 | + return { |
| 191 | + content: [{ type: "text", text }], |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +function resolveWorkspacePath(requestedPath: string) { |
| 196 | + const resolvedPath = path.resolve(workspaceDir!, requestedPath) |
| 197 | + const workspaceRoot = path.resolve(workspaceDir!) |
| 198 | + |
| 199 | + if (resolvedPath !== workspaceRoot && !resolvedPath.startsWith(`${workspaceRoot}${path.sep}`)) { |
| 200 | + throw new Error(`Path is outside the test workspace: ${requestedPath}`) |
| 201 | + } |
| 202 | + |
| 203 | + return resolvedPath |
| 204 | +} |
| 205 | + |
| 206 | +async function buildDirectoryTree( |
| 207 | + directoryPath: string, |
| 208 | +): Promise<{ name: string; type: string; children?: unknown[] }> { |
| 209 | + const stats = await fs.stat(directoryPath) |
| 210 | + const node: { name: string; type: string; children?: unknown[] } = { |
| 211 | + name: path.basename(directoryPath), |
| 212 | + type: stats.isDirectory() ? "directory" : "file", |
| 213 | + } |
| 214 | + |
| 215 | + if (!stats.isDirectory()) { |
| 216 | + return node |
| 217 | + } |
| 218 | + |
| 219 | + const entries = await fs.readdir(directoryPath, { withFileTypes: true }) |
| 220 | + node.children = await Promise.all( |
| 221 | + entries |
| 222 | + .sort((a, b) => a.name.localeCompare(b.name)) |
| 223 | + .map((entry) => buildDirectoryTree(path.join(directoryPath, entry.name))), |
| 224 | + ) |
| 225 | + |
| 226 | + return node |
| 227 | +} |
0 commit comments