From 3032f2ea859dba6ad5a49889133e12efe9352de2 Mon Sep 17 00:00:00 2001 From: Michal Pemcak Date: Fri, 7 Aug 2026 08:51:59 +0200 Subject: [PATCH] Switch MCP transport from stdio to Streamable HTTP Mount POST /mcp on the main Express app (stateless Streamable HTTP). Keep optional MCP-only HTTP process via npm run mcp. Update docs. --- .env.example | 4 +++ README.md | 62 +++++++++++++++++------------------- __tests__/mcp-server.test.js | 13 ++++++++ src/index.js | 21 ++++++++++-- src/mcp-http.js | 57 +++++++++++++++++++++++++++++++++ src/mcp.js | 53 +++++++++++++++++------------- 6 files changed, 152 insertions(+), 58 deletions(-) create mode 100644 src/mcp-http.js diff --git a/.env.example b/.env.example index e8e49ec..9783e6b 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,10 @@ BASE_URL=http://webshare-api:3001 WEBSHARE_USERNAME= WEBSHARE_PASSWORD= +# MCP Streamable HTTP (mounted on the main app at POST /mcp) +# MCP_ENABLED=true +# MCP_PATH=/mcp + # Host path mounted into the container (compose.yaml) # DOWNLOAD_HOST_PATH=./data/webshare diff --git a/README.md b/README.md index 2ab7a47..cd601de 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Official Webshare HTTP API documentation: [https://webshare.cz/apidoc/](https:// | **Stream** | `GET /stream/:ident` | Fresh Webshare `file_link` + HTTP 302 to CDN | | **Fake qBittorrent** | `/api/v2/*` | Download client API; streams the HTTPS file to disk | | **Debug** | `GET /resolve/:ident` | JSON with the resolved CDN URL | -| **MCP server** | stdio (`npm run mcp`) | Tools for AI agents: search, resolve links, login check | +| **MCP server** | `POST /mcp` (Streamable HTTP) | Tools for AI agents: search, resolve links, login check | Webshare download links expire after roughly ten minutes, so the torrent never embeds a CDN URL—only a path on this service that resolves a fresh link at fetch time. @@ -26,7 +26,8 @@ src/ torrent.js # bencode + fake torrent + info-hash qbt.js # qBittorrent Web API façade + download queue mcp-server.js # MCP tool registration (shared) - mcp.js # MCP stdio entrypoint for agents + mcp-http.js # Streamable HTTP transport mount for Express + mcp.js # Optional MCP-only HTTP process __tests__/ compose.yaml Dockerfile @@ -49,6 +50,8 @@ Environment variables (required unless noted): | `SONARR_API_KEY` | _(empty)_ | Optional; enables periodic missing-episode search | | `SONARR_SEARCH_INTERVAL_HOURS` | `2` | Interval for that search | | `DOWNLOAD_HOST_PATH` | `./data/webshare` | Host path mounted at `DOWNLOAD_PATH` in Compose | +| `MCP_ENABLED` | `true` | Set to `0`/`false` to disable the MCP HTTP endpoint | +| `MCP_PATH` | `/mcp` | HTTP path for the Streamable HTTP MCP endpoint | Copy `.env.example` and fill in credentials. Do not commit a filled `.env`. @@ -82,7 +85,21 @@ Sonarr hands `.torrent` files to the fake qBittorrent API. This service extracts ## MCP (AI agents) -Exposes Webshare to MCP-compatible clients over **stdio** (stdout is protocol-only; logs go to stderr). +Exposes Webshare to MCP-compatible clients over **Streamable HTTP** (not stdio). + +With `npm start` (or Compose), MCP is available on the same process/port: + +``` +POST http://:3001/mcp +``` + +Optional MCP-only process (no Torznab/qBittorrent): + +```bash +export WEBSHARE_USERNAME=... +export WEBSHARE_PASSWORD=... +npm run mcp # listens on PORT, serves POST /mcp +``` ### Tools @@ -92,43 +109,22 @@ Exposes Webshare to MCP-compatible clients over **stdio** (stdout is protocol-on | `webshare_get_link` | Resolve a temporary CDN URL for a file `ident` | | `webshare_login_check` | Verify credentials against the Webshare API | -### Run - -```bash -export WEBSHARE_USERNAME=... -export WEBSHARE_PASSWORD=... -npm run mcp -# or: npx webshare-mcp (after npm link / global install) -``` - ### Client configuration example -**Claude Desktop / similar** (`mcpServers`): - -```json -{ - "mcpServers": { - "webshare": { - "command": "node", - "args": ["/absolute/path/to/webshare-api/src/mcp.js"], - "env": { - "WEBSHARE_USERNAME": "your-username", - "WEBSHARE_PASSWORD": "your-password" - } - } - } -} -``` - -**Grok / OpenCode-style** (TOML): +**HTTP / Streamable HTTP** (preferred): ```toml [mcp_servers.webshare] -command = "node" -args = ["/absolute/path/to/webshare-api/src/mcp.js"] +url = "http://127.0.0.1:3001/mcp" ``` -Pass `WEBSHARE_USERNAME` and `WEBSHARE_PASSWORD` via the client env settings or a process manager—not in the repo. +```bash +grok mcp add --transport http webshare http://127.0.0.1:3001/mcp +``` + +Credentials stay on the server process (`WEBSHARE_*` env); clients only need the URL. + +The transport is **stateless** Streamable HTTP (POST only). ## Tests diff --git a/__tests__/mcp-server.test.js b/__tests__/mcp-server.test.js index c58e02e..22a0624 100644 --- a/__tests__/mcp-server.test.js +++ b/__tests__/mcp-server.test.js @@ -1,4 +1,6 @@ +const express = require('express'); const { formatSize, createWebshareMcpServer } = require('../src/mcp-server'); +const { registerMcpHttp } = require('../src/mcp-http'); describe('formatSize', () => { it('formats bytes', () => { @@ -17,3 +19,14 @@ describe('createWebshareMcpServer', () => { expect(server.server).toBeDefined(); }); }); + +describe('registerMcpHttp', () => { + it('registers POST /mcp on an express app', () => { + const app = express(); + registerMcpHttp(app, { username: 'u', password: 'p', path: '/mcp' }); + const layer = app._router.stack.find( + (l) => l.route && l.route.path === '/mcp' && l.route.methods.post + ); + expect(layer).toBeTruthy(); + }); +}); diff --git a/src/index.js b/src/index.js index 24c44e6..2b596e4 100644 --- a/src/index.js +++ b/src/index.js @@ -3,11 +3,14 @@ const { WebshareClient } = require('./webshare'); const { caps, feed } = require('./torznab'); const { makeTorrent } = require('./torrent'); const qbt = require('./qbt'); +const { registerMcpHttp } = require('./mcp-http'); const PORT = process.env.PORT || 3001; const BASE_URL = process.env.BASE_URL || `http://localhost:${PORT}`; const USERNAME = process.env.WEBSHARE_USERNAME; const PASSWORD = process.env.WEBSHARE_PASSWORD; +const MCP_PATH = process.env.MCP_PATH || '/mcp'; +const MCP_ENABLED = process.env.MCP_ENABLED !== '0' && process.env.MCP_ENABLED !== 'false'; if (!USERNAME || !PASSWORD) { console.error('WEBSHARE_USERNAME and WEBSHARE_PASSWORD must be set'); @@ -18,7 +21,7 @@ const client = new WebshareClient(USERNAME, PASSWORD); const app = express(); app.use(express.urlencoded({ extended: false })); -app.use(express.json()); +app.use(express.json({ limit: '4mb' })); client.ensureAuth().catch(err => console.error('Initial auth failed:', err.message)); @@ -113,6 +116,15 @@ app.get('/resolve/:ident', async (req, res) => { // ── Fake qBittorrent Web API ────────────────────────────────────────────── qbt.register(app); +// ── MCP Streamable HTTP (AI agents) ─────────────────────────────────────── +if (MCP_ENABLED) { + registerMcpHttp(app, { + username: USERNAME, + password: PASSWORD, + path: MCP_PATH, + }); +} + // ── Automatic missing-episode search ───────────────────────────────────── // Sonarr won't find new downloads without being asked (no RSS support). // Every 2 hours, tell Sonarr to search for all missing monitored episodes. @@ -148,4 +160,9 @@ if (SONARR_KEY) { console.log(`[search] auto missing-episode search every ${SEARCH_INTERVAL / 3600000}h`); } -app.listen(PORT, () => console.log(`webshare-api listening on :${PORT} — base URL: ${BASE_URL}`)); +app.listen(PORT, () => { + console.log(`webshare-api listening on :${PORT} — base URL: ${BASE_URL}`); + if (MCP_ENABLED) { + console.log(`MCP Streamable HTTP: POST ${BASE_URL.replace(/\/$/, '')}${MCP_PATH}`); + } +}); diff --git a/src/mcp-http.js b/src/mcp-http.js new file mode 100644 index 0000000..b9b1b4d --- /dev/null +++ b/src/mcp-http.js @@ -0,0 +1,57 @@ +const { StreamableHTTPServerTransport } = require('@modelcontextprotocol/sdk/server/streamableHttp.js'); +const { createWebshareMcpServer } = require('./mcp-server'); + +/** + * Mount a stateless Streamable HTTP MCP endpoint on an Express app. + * Default path: POST /mcp (MCP Streamable HTTP transport). + * + * @param {import('express').Express} app + * @param {{ username: string, password: string, path?: string }} options + */ +function registerMcpHttp(app, { username, password, path: mountPath = '/mcp' }) { + const handle = async (req, res) => { + // Stateless: one MCP server + transport per request + const server = createWebshareMcpServer({ username, password }); + try { + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + }); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + res.on('close', () => { + try { + transport.close(); + } catch { /* ignore */ } + try { + server.close(); + } catch { /* ignore */ } + }); + } catch (err) { + console.error('MCP HTTP error:', err); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { code: -32603, message: 'Internal server error' }, + id: null, + }); + } + } + }; + + app.post(mountPath, handle); + + // Streamable HTTP clients may probe GET/DELETE; this deployment is POST-only (stateless). + const methodNotAllowed = (req, res) => { + res.status(405).json({ + jsonrpc: '2.0', + error: { code: -32000, message: 'Method not allowed. Use POST for Streamable HTTP (stateless).' }, + id: null, + }); + }; + app.get(mountPath, methodNotAllowed); + app.delete(mountPath, methodNotAllowed); + + console.log(`MCP Streamable HTTP enabled at POST ${mountPath}`); +} + +module.exports = { registerMcpHttp }; diff --git a/src/mcp.js b/src/mcp.js index 88ec0c0..1b13924 100755 --- a/src/mcp.js +++ b/src/mcp.js @@ -1,32 +1,39 @@ #!/usr/bin/env node /** - * MCP stdio entrypoint for AI agents. + * Optional standalone HTTP process that only serves MCP (no Torznab / qBittorrent). + * Prefer `npm start` (main app) which mounts MCP at POST /mcp on the same port. * - * Configure clients with: - * command: node - * args: ["…/webshare-api/src/mcp.js"] - * env: { WEBSHARE_USERNAME, WEBSHARE_PASSWORD } - * - * Do not write application logs to stdout — it is reserved for the MCP protocol. + * Env: + * WEBSHARE_USERNAME, WEBSHARE_PASSWORD (required) + * PORT (default 3001) + * MCP_PATH (default /mcp) */ -const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js'); -const { createWebshareMcpServer } = require('./mcp-server'); +const express = require('express'); +const { registerMcpHttp } = require('./mcp-http'); -async function main() { - const username = process.env.WEBSHARE_USERNAME; - const password = process.env.WEBSHARE_PASSWORD; - if (!username || !password) { - console.error('WEBSHARE_USERNAME and WEBSHARE_PASSWORD must be set'); - process.exit(1); - } +const PORT = process.env.PORT || 3001; +const MCP_PATH = process.env.MCP_PATH || '/mcp'; +const USERNAME = process.env.WEBSHARE_USERNAME; +const PASSWORD = process.env.WEBSHARE_PASSWORD; - const server = createWebshareMcpServer({ username, password }); - const transport = new StdioServerTransport(); - await server.connect(transport); - console.error('webshare-api MCP server running on stdio'); +if (!USERNAME || !PASSWORD) { + console.error('WEBSHARE_USERNAME and WEBSHARE_PASSWORD must be set'); + process.exit(1); } -main().catch((err) => { - console.error('MCP server failed:', err); - process.exit(1); +const app = express(); +app.use(express.json({ limit: '4mb' })); + +app.get('/health', (req, res) => { + res.json({ ok: true, mcp: MCP_PATH }); +}); + +registerMcpHttp(app, { + username: USERNAME, + password: PASSWORD, + path: MCP_PATH, +}); + +app.listen(PORT, () => { + console.log(`webshare-api MCP (HTTP) listening on :${PORT}${MCP_PATH}`); });