Created
October 12, 2025 07:16
-
-
Save kuc-arc-f/c6c1405d268beaa5e07579fe96fa8962 to your computer and use it in GitHub Desktop.
node.js call , GoLang 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/go-mcp-server-4.exe"); | |
const result1 = await client.call( | |
"tools/call", | |
{ | |
name: "purchase_item", | |
arguments: {name: "green-tea", price: 140}, | |
}, | |
); | |
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