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.
This commit is contained in:
@@ -3,6 +3,10 @@ BASE_URL=http://webshare-api:3001
|
|||||||
WEBSHARE_USERNAME=
|
WEBSHARE_USERNAME=
|
||||||
WEBSHARE_PASSWORD=
|
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)
|
# Host path mounted into the container (compose.yaml)
|
||||||
# DOWNLOAD_HOST_PATH=./data/webshare
|
# DOWNLOAD_HOST_PATH=./data/webshare
|
||||||
|
|
||||||
|
|||||||
62
README.md
62
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 |
|
| **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 |
|
| **Fake qBittorrent** | `/api/v2/*` | Download client API; streams the HTTPS file to disk |
|
||||||
| **Debug** | `GET /resolve/:ident` | JSON with the resolved CDN URL |
|
| **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.
|
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
|
torrent.js # bencode + fake torrent + info-hash
|
||||||
qbt.js # qBittorrent Web API façade + download queue
|
qbt.js # qBittorrent Web API façade + download queue
|
||||||
mcp-server.js # MCP tool registration (shared)
|
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__/
|
__tests__/
|
||||||
compose.yaml
|
compose.yaml
|
||||||
Dockerfile
|
Dockerfile
|
||||||
@@ -49,6 +50,8 @@ Environment variables (required unless noted):
|
|||||||
| `SONARR_API_KEY` | _(empty)_ | Optional; enables periodic missing-episode search |
|
| `SONARR_API_KEY` | _(empty)_ | Optional; enables periodic missing-episode search |
|
||||||
| `SONARR_SEARCH_INTERVAL_HOURS` | `2` | Interval for that search |
|
| `SONARR_SEARCH_INTERVAL_HOURS` | `2` | Interval for that search |
|
||||||
| `DOWNLOAD_HOST_PATH` | `./data/webshare` | Host path mounted at `DOWNLOAD_PATH` in Compose |
|
| `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`.
|
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)
|
## 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://<host>: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
|
### 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_get_link` | Resolve a temporary CDN URL for a file `ident` |
|
||||||
| `webshare_login_check` | Verify credentials against the Webshare API |
|
| `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
|
### Client configuration example
|
||||||
|
|
||||||
**Claude Desktop / similar** (`mcpServers`):
|
**HTTP / Streamable HTTP** (preferred):
|
||||||
|
|
||||||
```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):
|
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[mcp_servers.webshare]
|
[mcp_servers.webshare]
|
||||||
command = "node"
|
url = "http://127.0.0.1:3001/mcp"
|
||||||
args = ["/absolute/path/to/webshare-api/src/mcp.js"]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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
|
## Tests
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
|
const express = require('express');
|
||||||
const { formatSize, createWebshareMcpServer } = require('../src/mcp-server');
|
const { formatSize, createWebshareMcpServer } = require('../src/mcp-server');
|
||||||
|
const { registerMcpHttp } = require('../src/mcp-http');
|
||||||
|
|
||||||
describe('formatSize', () => {
|
describe('formatSize', () => {
|
||||||
it('formats bytes', () => {
|
it('formats bytes', () => {
|
||||||
@@ -17,3 +19,14 @@ describe('createWebshareMcpServer', () => {
|
|||||||
expect(server.server).toBeDefined();
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
21
src/index.js
21
src/index.js
@@ -3,11 +3,14 @@ const { WebshareClient } = require('./webshare');
|
|||||||
const { caps, feed } = require('./torznab');
|
const { caps, feed } = require('./torznab');
|
||||||
const { makeTorrent } = require('./torrent');
|
const { makeTorrent } = require('./torrent');
|
||||||
const qbt = require('./qbt');
|
const qbt = require('./qbt');
|
||||||
|
const { registerMcpHttp } = require('./mcp-http');
|
||||||
|
|
||||||
const PORT = process.env.PORT || 3001;
|
const PORT = process.env.PORT || 3001;
|
||||||
const BASE_URL = process.env.BASE_URL || `http://localhost:${PORT}`;
|
const BASE_URL = process.env.BASE_URL || `http://localhost:${PORT}`;
|
||||||
const USERNAME = process.env.WEBSHARE_USERNAME;
|
const USERNAME = process.env.WEBSHARE_USERNAME;
|
||||||
const PASSWORD = process.env.WEBSHARE_PASSWORD;
|
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) {
|
if (!USERNAME || !PASSWORD) {
|
||||||
console.error('WEBSHARE_USERNAME and WEBSHARE_PASSWORD must be set');
|
console.error('WEBSHARE_USERNAME and WEBSHARE_PASSWORD must be set');
|
||||||
@@ -18,7 +21,7 @@ const client = new WebshareClient(USERNAME, PASSWORD);
|
|||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
app.use(express.urlencoded({ extended: false }));
|
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));
|
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 ──────────────────────────────────────────────
|
// ── Fake qBittorrent Web API ──────────────────────────────────────────────
|
||||||
qbt.register(app);
|
qbt.register(app);
|
||||||
|
|
||||||
|
// ── MCP Streamable HTTP (AI agents) ───────────────────────────────────────
|
||||||
|
if (MCP_ENABLED) {
|
||||||
|
registerMcpHttp(app, {
|
||||||
|
username: USERNAME,
|
||||||
|
password: PASSWORD,
|
||||||
|
path: MCP_PATH,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// ── Automatic missing-episode search ─────────────────────────────────────
|
// ── Automatic missing-episode search ─────────────────────────────────────
|
||||||
// Sonarr won't find new downloads without being asked (no RSS support).
|
// Sonarr won't find new downloads without being asked (no RSS support).
|
||||||
// Every 2 hours, tell Sonarr to search for all missing monitored episodes.
|
// 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`);
|
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}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
57
src/mcp-http.js
Normal file
57
src/mcp-http.js
Normal file
@@ -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 };
|
||||||
53
src/mcp.js
53
src/mcp.js
@@ -1,32 +1,39 @@
|
|||||||
#!/usr/bin/env node
|
#!/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:
|
* Env:
|
||||||
* command: node
|
* WEBSHARE_USERNAME, WEBSHARE_PASSWORD (required)
|
||||||
* args: ["…/webshare-api/src/mcp.js"]
|
* PORT (default 3001)
|
||||||
* env: { WEBSHARE_USERNAME, WEBSHARE_PASSWORD }
|
* MCP_PATH (default /mcp)
|
||||||
*
|
|
||||||
* Do not write application logs to stdout — it is reserved for the MCP protocol.
|
|
||||||
*/
|
*/
|
||||||
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
|
const express = require('express');
|
||||||
const { createWebshareMcpServer } = require('./mcp-server');
|
const { registerMcpHttp } = require('./mcp-http');
|
||||||
|
|
||||||
async function main() {
|
const PORT = process.env.PORT || 3001;
|
||||||
const username = process.env.WEBSHARE_USERNAME;
|
const MCP_PATH = process.env.MCP_PATH || '/mcp';
|
||||||
const password = process.env.WEBSHARE_PASSWORD;
|
const USERNAME = process.env.WEBSHARE_USERNAME;
|
||||||
if (!username || !password) {
|
const PASSWORD = process.env.WEBSHARE_PASSWORD;
|
||||||
console.error('WEBSHARE_USERNAME and WEBSHARE_PASSWORD must be set');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const server = createWebshareMcpServer({ username, password });
|
if (!USERNAME || !PASSWORD) {
|
||||||
const transport = new StdioServerTransport();
|
console.error('WEBSHARE_USERNAME and WEBSHARE_PASSWORD must be set');
|
||||||
await server.connect(transport);
|
process.exit(1);
|
||||||
console.error('webshare-api MCP server running on stdio');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch((err) => {
|
const app = express();
|
||||||
console.error('MCP server failed:', err);
|
app.use(express.json({ limit: '4mb' }));
|
||||||
process.exit(1);
|
|
||||||
|
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}`);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user