(host: string, port: number)
| 7 | import { program } from "commander"; |
| 8 | |
| 9 | const startSseServer = async (host: string, port: number) => { |
| 10 | const app = express(); |
| 11 | const server = createMcpServer(); |
| 12 | |
| 13 | const authToken = process.env.MOBILEMCP_AUTH; |
| 14 | if (!authToken) { |
| 15 | error("WARNING: MOBILEMCP_AUTH is not set. The SSE server will accept unauthenticated connections. Set MOBILEMCP_AUTH to require Bearer token authentication."); |
| 16 | } |
| 17 | |
| 18 | if (authToken) { |
| 19 | app.use((req, res, next) => { |
| 20 | if (req.headers.authorization !== `Bearer ${authToken}`) { |
| 21 | res.status(401).json({ error: "Unauthorized" }); |
| 22 | return; |
| 23 | } |
| 24 | |
| 25 | next(); |
| 26 | }); |
| 27 | } |
| 28 | |
| 29 | // Block cross-origin requests — MCP clients are not browsers |
| 30 | app.use((req, res, next) => { |
| 31 | if (req.headers.origin) { |
| 32 | res.status(403).json({ error: "Cross-origin requests are not allowed" }); |
| 33 | return; |
| 34 | } |
| 35 | |
| 36 | if (req.method === "OPTIONS") { |
| 37 | res.status(403).end(); |
| 38 | return; |
| 39 | } |
| 40 | |
| 41 | next(); |
| 42 | }); |
| 43 | |
| 44 | let transport: SSEServerTransport | null = null; |
| 45 | |
| 46 | app.post("/mcp", (req, res) => { |
| 47 | if (transport) { |
| 48 | transport.handlePostMessage(req, res); |
| 49 | } |
| 50 | }); |
| 51 | |
| 52 | app.get("/mcp", (req, res) => { |
| 53 | if (transport) { |
| 54 | res.status(409).json({ error: "Another client is already connected. Disconnect the existing client first." }); |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | transport = new SSEServerTransport("/mcp", res); |
| 59 | |
| 60 | transport.onclose = () => { |
| 61 | transport = null; |
| 62 | }; |
| 63 | |
| 64 | server.connect(transport); |
| 65 | }); |
| 66 |
no test coverage detected