add ability to connect manually

This commit is contained in:
Ashwin Bhat
2024-10-08 08:20:18 -07:00
parent 38e1c8b2b9
commit 1095e48c44
2 changed files with 119 additions and 65 deletions

View File

@@ -7,18 +7,25 @@ const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
const mcpClient = new McpClient("MyApp", "1.0.0");
await mcpClient.connectStdio(
"/Users/ashwin/.nvm/versions/node/v18.20.4/bin/node",
["/Users/ashwin/code/example-servers/build/everything/index.js"],
);
let mcpClient: McpClient | null = null;
wss.on("connection", (ws: WebSocket) => {
ws.on("message", async (message: string) => {
try {
const command = JSON.parse(message);
if (command.type === "listResources") {
if (command.type === "connect" && command.command && command.args) {
mcpClient = new McpClient("MyApp", "1.0.0");
await mcpClient.connectStdio(command.command, command.args);
ws.send(JSON.stringify({ type: "connected" }));
} else if (!mcpClient) {
ws.send(
JSON.stringify({
type: "error",
message: "Not connected to MCP server",
}),
);
} else if (command.type === "listResources") {
const resources = await mcpClient.listResources();
ws.send(JSON.stringify({ type: "resources", data: resources }));
} else if (command.type === "readResource" && command.uri) {
@@ -58,6 +65,8 @@ server.listen(PORT, () => {
// Close the client when the server is shutting down
process.on("SIGINT", async () => {
await mcpClient.close();
if (mcpClient) {
await mcpClient.close();
}
process.exit();
});