Created
October 12, 2025 01:55
-
-
Save kuc-arc-f/2d2e3f3f44c14b5ae2e810c89ee54cc1 to your computer and use it in GitHub Desktop.
node.js call , Rust MCP Server JSON-RPC 2.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { spawn } from "child_process"; | |
class RpcClient { | |
constructor(command) { | |
this.proc = spawn(command); | |
this.idCounter = 1; | |
this.pending = new Map(); | |
this.proc.stdout.setEncoding("utf8"); | |
this.proc.stdout.on("data", (data) => this._handleData(data)); | |
this.proc.stderr.on("data", (err) => console.error("Rust stderr:", err.toString())); | |
this.proc.on("exit", (code) => console.log(`Rust server exited (${code})`)); | |
} | |
_handleData(data) { | |
// 複数行対応 | |
data.split("\n").forEach((line) => { | |
if (!line.trim()) return; | |
try { | |
const msg = JSON.parse(line); | |
if (msg.id && this.pending.has(msg.id)) { | |
const { resolve } = this.pending.get(msg.id); | |
this.pending.delete(msg.id); | |
resolve(msg.result); | |
} | |
} catch (e) { | |
//console.error("JSON parse error:", e, line); | |
} | |
}); | |
} | |
call(method, params = {}) { | |
const id = this.idCounter++; | |
const payload = { | |
jsonrpc: "2.0", | |
id, | |
method, | |
params, | |
}; | |
return new Promise((resolve, reject) => { | |
this.pending.set(id, { resolve, reject }); | |
this.proc.stdin.write(JSON.stringify(payload) + "\n"); | |
}); | |
} | |
close() { | |
this.proc.kill(); | |
} | |
} | |
// ----------------------------- | |
// 実行例 | |
// ----------------------------- | |
async function main() { | |
const client = new RpcClient("/path/mcp_4/target/release/rust_mcp_server_4.exe"); | |
const result1 = await client.call( | |
"tools/call", | |
{ | |
name: "purchase", | |
arguments: {name: "green-tea", price: 110}, | |
}, | |
); | |
console.log("add結果:", result1); | |
client.close(); | |
} | |
main().catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment