Created
May 25, 2025 02:41
-
-
Save CoffeeVampir3/bcaa76f9ae2719c83aee46161f4af1a1 to your computer and use it in GitHub Desktop.
server
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 express from "npm:express"; | |
import { randomUUID } from "node:crypto"; | |
import { McpServer } from "npm:@modelcontextprotocol/sdk/server/mcp.js"; | |
import { StreamableHTTPServerTransport } from "npm:@modelcontextprotocol/sdk/server/streamableHttp.js"; | |
import { z } from "npm:zod"; | |
const PORT = 3000; | |
const MCP_ENDPOINT = "/mcp"; | |
const app = express(); | |
app.use(express.json()); | |
const server = new McpServer({ | |
name: "Calculator Server", | |
version: "1.0.0", | |
}); | |
server.tool( | |
"add", | |
{ | |
a: z.number().describe("First number to add"), | |
b: z.number().describe("Second number to add"), | |
}, | |
async ({ a, b }) => { | |
console.log(`Adding ${a} and ${b}`); | |
return { | |
content: [{ type: "text", text: `The result is ${a + b}` }], | |
}; | |
}, | |
); | |
const transport = new StreamableHTTPServerTransport({ | |
sessionIdGenerator: () => randomUUID(), | |
onsessioninitialized: (sid) => { | |
console.log(`Session initialized: ${sid}`); | |
}, | |
}); | |
await server.connect(transport); | |
console.log("MCP Server connected to transport"); | |
async function handleRequest(req, res) { | |
console.log(`Handling MCP request`); | |
console.log(`Request body:`, JSON.stringify(req.body, null, 2)); | |
try { | |
await transport.handleRequest(req, res, req.body); | |
} catch (error) { | |
console.error('Error handling MCP request:', error); | |
res.status(500).json({ | |
jsonrpc: "2.0", | |
error: { | |
code: -32603, | |
message: "Internal error: " + error.message, | |
}, | |
id: req.body?.id || null, | |
}); | |
} | |
} | |
app.post(MCP_ENDPOINT, handleRequest); | |
app.get(MCP_ENDPOINT, handleRequest); | |
app.delete(MCP_ENDPOINT, handleRequest); | |
app.listen(PORT, () => { | |
console.log(`MCP Server listening on port ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment