mirror of
https://github.com/arsvendg/Stirling-PDF.git
synced 2026-07-16 11:23:10 +02:00
Add MCP server with OAuth/API-key auth (#6570)
Adds an optional MCP server (proprietary module) that exposes Stirling's PDF operations and AI capabilities to MCP clients. Off by default, zero footprint when disabled. ### What - New `/mcp` endpoint: streamable-HTTP + JSON-RPC 2.0; 8 tools (describe_operation, pages/convert/misc/security category tools, AI, upload, download). - Runs real operations over an internal loopback; results returned inline as base64 (small) or by fileId (large). ### Auth (two modes) - OAuth2 resource server: RFC 9728 protected-resource metadata, RFC 8707 audience binding, JWKS, `mcp.tools.read/write` scopes; binds each token to a provisioned Stirling account. - API-key mode: reuses Stirling per-user `X-API-KEY` (no IdP needed). ### Security - Per-user file ownership in FileStorage: async/queued writes scoped to the submitting user; legacy/owner-less files stay readable. - Admin allow/block list controls which operations are exposed. - Python engine gated behind a shared secret (`X-Engine-Auth`). - MCP filter chain is isolated and cannot weaken the main app's security. - Hardened: no upstream error-body leakage, log injection sanitized, fileId path/sidecar enumeration blocked. ### Config / footprint - Disabled by default (`mcp.enabled=false`); all beans `@ConditionalOnProperty`. --- ## Checklist ### General - [ ] I have read the [Contribution Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md) - [ ] I have read the [Stirling-PDF Developer Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md) (if applicable) - [ ] I have read the [How to add new languages to Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md) (if applicable) - [ ] I have performed a self-review of my own code - [ ] My changes generate no new warnings ### Documentation - [ ] I have updated relevant docs on [Stirling-PDF's doc repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/) (if functionality has heavily changed) - [ ] I have read the section [Add New Translation Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags) (for new translation tags only) ### Translations (if applicable) - [ ] I ran [`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md) ### UI Changes (if applicable) - [ ] Screenshots or videos demonstrating the UI changes are attached (e.g., as comments or direct attachments in the PR) ### Testing (if applicable) - [ ] I have run `task check` to verify linters, typechecks, and tests pass - [ ] I have tested my changes locally. Refer to the [Testing Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing) for more details.
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Real MCP client validation via the official @modelcontextprotocol/sdk over streamable HTTP.
|
||||
*
|
||||
* Auth header (non-interactive):
|
||||
* MCP_BEARER=<jwt> -> Authorization: Bearer <jwt> (oauth)
|
||||
* MCP_APIKEY=<key> -> X-API-KEY: <key> (apikey)
|
||||
* Env: MCP_URL (default http://localhost:8080/mcp), MODE (output label). Exit 0 = passed.
|
||||
*/
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
|
||||
const url = process.env.MCP_URL || "http://localhost:8080/mcp";
|
||||
const mode = process.env.MODE || "oauth";
|
||||
const bearer = process.env.MCP_BEARER;
|
||||
const apikey = process.env.MCP_APIKEY;
|
||||
|
||||
const headers = {};
|
||||
if (bearer) headers["Authorization"] = `Bearer ${bearer}`;
|
||||
if (apikey) headers["X-API-KEY"] = apikey;
|
||||
|
||||
function fail(msg) {
|
||||
console.error(`[${mode}] FAIL: ${msg}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const REQUIRED = [
|
||||
"stirling_describe_operation",
|
||||
"stirling_convert",
|
||||
"stirling_pages",
|
||||
"stirling_misc",
|
||||
"stirling_security",
|
||||
"stirling_upload",
|
||||
"stirling_download",
|
||||
];
|
||||
|
||||
const transport = new StreamableHTTPClientTransport(new URL(url), {
|
||||
requestInit: { headers },
|
||||
});
|
||||
const client = new Client(
|
||||
{ name: "stirling-mcp-validator", version: "1.0.0" },
|
||||
{ capabilities: {} },
|
||||
);
|
||||
|
||||
try {
|
||||
// connect() performs the initialize handshake (version negotiation + capabilities)
|
||||
await client.connect(transport);
|
||||
|
||||
const { tools } = await client.listTools();
|
||||
const names = tools.map((t) => t.name).sort();
|
||||
for (const r of REQUIRED) {
|
||||
if (!names.includes(r)) fail(`tools/list missing ${r} (got: ${names.join(", ")})`);
|
||||
}
|
||||
|
||||
const res = await client.callTool({
|
||||
name: "stirling_describe_operation",
|
||||
arguments: { operation: "add-password" },
|
||||
});
|
||||
if (!JSON.stringify(res).includes("parametersSchema")) {
|
||||
fail(`describe_operation returned no parametersSchema: ${JSON.stringify(res).slice(0, 300)}`);
|
||||
}
|
||||
|
||||
// File I/O round-trip: upload bytes, then download them back unchanged.
|
||||
const original = "hello mcp round-trip";
|
||||
const up = await client.callTool({
|
||||
name: "stirling_upload",
|
||||
arguments: { file: Buffer.from(original, "utf8").toString("base64"), fileName: "hello.txt" },
|
||||
});
|
||||
const upMatch = JSON.stringify(up).match(/fileId=([A-Za-z0-9_-]+)/);
|
||||
if (!upMatch) fail(`stirling_upload returned no fileId: ${JSON.stringify(up).slice(0, 200)}`);
|
||||
const fileId = upMatch[1];
|
||||
|
||||
const down = await client.callTool({ name: "stirling_download", arguments: { fileId } });
|
||||
const resBlock = (down.content || []).find((b) => b.type === "resource");
|
||||
if (!resBlock?.resource?.blob) {
|
||||
fail(`stirling_download returned no resource blob: ${JSON.stringify(down).slice(0, 200)}`);
|
||||
}
|
||||
const roundTripped = Buffer.from(resBlock.resource.blob, "base64").toString("utf8");
|
||||
if (roundTripped !== original) {
|
||||
fail(`upload/download round-trip mismatch: got "${roundTripped}"`);
|
||||
}
|
||||
|
||||
// A category tool with no file must surface an honest error, not a fake success.
|
||||
const cat = await client.callTool({
|
||||
name: "stirling_security",
|
||||
arguments: { operation: "add-password" },
|
||||
});
|
||||
if (cat.isError !== true) {
|
||||
fail(`stirling_security with no file should report isError, got: ${JSON.stringify(cat).slice(0, 200)}`);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[${mode}] OK: real MCP SDK client connected, negotiated protocol, listed ${names.length} tools, ` +
|
||||
`describe_operation returned a schema, upload/download round-trip matched, category tool returned isError.`,
|
||||
);
|
||||
console.log(`[${mode}] tools: ${names.join(", ")}`);
|
||||
await client.close();
|
||||
process.exit(0);
|
||||
} catch (e) {
|
||||
fail(`${e?.stack || e?.message || e}`);
|
||||
}
|
||||
Reference in New Issue
Block a user