@burdenoff/mcp-libs 2026.1112.1 → 2026.1118.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{core-zmkvPNsI.js → context-CNN-D9dE.js} +78 -606
- package/dist/context-CNN-D9dE.js.map +1 -0
- package/dist/{core-BKgeqlnN.cjs → context-DE1SuHyv.cjs} +87 -741
- package/dist/context-DE1SuHyv.cjs.map +1 -0
- package/dist/core/auth/memory-store.d.ts +2 -0
- package/dist/core/auth/store.d.ts +1 -0
- package/dist/core/context.d.ts +2 -1
- package/dist/core/index.cjs +19 -16
- package/dist/core/index.d.ts +2 -1
- package/dist/core/index.js +3 -2
- package/dist/core/tool-governance.d.ts +1 -1
- package/dist/core-AqyC7YJc.js +605 -0
- package/dist/core-AqyC7YJc.js.map +1 -0
- package/dist/core-Es_IX0FS.cjs +748 -0
- package/dist/core-Es_IX0FS.cjs.map +1 -0
- package/dist/index.cjs +4 -3
- package/dist/index.js +3 -2
- package/dist/{legacy-auth-BdSPFaEf.js → legacy-auth-DK_-m6hi.js} +2 -2
- package/dist/{legacy-auth-BdSPFaEf.js.map → legacy-auth-DK_-m6hi.js.map} +1 -1
- package/dist/{legacy-auth-C66oObd-.cjs → legacy-auth-Sk9KJHLW.cjs} +4 -4
- package/dist/{legacy-auth-C66oObd-.cjs.map → legacy-auth-Sk9KJHLW.cjs.map} +1 -1
- package/dist/modules/adaptercloud/index.cjs +1 -1
- package/dist/modules/adaptercloud/index.js +1 -1
- package/dist/modules/artistrybase/index.cjs +1 -1
- package/dist/modules/artistrybase/index.js +1 -1
- package/dist/modules/assethandler/index.cjs +1 -1
- package/dist/modules/assethandler/index.js +1 -1
- package/dist/modules/atheletebridge/index.cjs +1 -1
- package/dist/modules/atheletebridge/index.js +1 -1
- package/dist/modules/auth/index.cjs +4 -3
- package/dist/modules/auth/index.cjs.map +1 -1
- package/dist/modules/auth/index.js +3 -2
- package/dist/modules/auth/index.js.map +1 -1
- package/dist/modules/bigconsole/index.cjs +1 -1
- package/dist/modules/bigconsole/index.js +1 -1
- package/dist/modules/billing/index.cjs +1 -1
- package/dist/modules/billing/index.js +1 -1
- package/dist/modules/botmanor/index.cjs +1 -1
- package/dist/modules/botmanor/index.js +1 -1
- package/dist/modules/brainyrich/index.cjs +1 -1
- package/dist/modules/brainyrich/index.js +1 -1
- package/dist/modules/buildmyiq/index.cjs +1 -1
- package/dist/modules/buildmyiq/index.js +1 -1
- package/dist/modules/channels/index.cjs +1 -1
- package/dist/modules/channels/index.js +1 -1
- package/dist/modules/collabkin/index.cjs +1 -1
- package/dist/modules/collabkin/index.js +1 -1
- package/dist/modules/comradecircle/index.cjs +1 -1
- package/dist/modules/comradecircle/index.js +1 -1
- package/dist/modules/conversations/index.cjs +1 -1
- package/dist/modules/conversations/index.js +1 -1
- package/dist/modules/coolandlovely/index.cjs +1 -1
- package/dist/modules/coolandlovely/index.js +1 -1
- package/dist/modules/cosmicintersection/index.cjs +1 -1
- package/dist/modules/cosmicintersection/index.js +1 -1
- package/dist/modules/crewfoundry/index.cjs +1 -1
- package/dist/modules/crewfoundry/index.js +1 -1
- package/dist/modules/devportal/index.cjs +1 -1
- package/dist/modules/devportal/index.js +1 -1
- package/dist/modules/ecoimpacthub/index.cjs +1 -1
- package/dist/modules/ecoimpacthub/index.js +1 -1
- package/dist/modules/eventfullymanaged/index.cjs +1 -1
- package/dist/modules/eventfullymanaged/index.js +1 -1
- package/dist/modules/export/index.cjs +1 -1
- package/dist/modules/export/index.js +1 -1
- package/dist/modules/files/index.cjs +1 -1
- package/dist/modules/files/index.js +1 -1
- package/dist/modules/fluidgrids/extended-operations.d.ts +1 -1
- package/dist/modules/fluidgrids/index.cjs +6 -7
- package/dist/modules/fluidgrids/index.cjs.map +1 -1
- package/dist/modules/fluidgrids/index.js +6 -7
- package/dist/modules/fluidgrids/index.js.map +1 -1
- package/dist/modules/ggnomad/index.cjs +1 -1
- package/dist/modules/ggnomad/index.js +1 -1
- package/dist/modules/govcitizenhub/index.cjs +1 -1
- package/dist/modules/govcitizenhub/index.js +1 -1
- package/dist/modules/groups/index.cjs +1 -1
- package/dist/modules/groups/index.js +1 -1
- package/dist/modules/headshotmarketing/index.cjs +1 -1
- package/dist/modules/headshotmarketing/index.js +1 -1
- package/dist/modules/health/index.cjs +1 -1
- package/dist/modules/health/index.js +1 -1
- package/dist/modules/healthybowl/index.cjs +1 -1
- package/dist/modules/healthybowl/index.js +1 -1
- package/dist/modules/hookmovies/index.cjs +1 -1
- package/dist/modules/hookmovies/index.js +1 -1
- package/dist/modules/housingvista/index.cjs +1 -1
- package/dist/modules/housingvista/index.js +1 -1
- package/dist/modules/integrations/index.cjs +1 -1
- package/dist/modules/integrations/index.js +1 -1
- package/dist/modules/intelwatchtower/index.cjs +1 -1
- package/dist/modules/intelwatchtower/index.js +1 -1
- package/dist/modules/kadaikodi/index.cjs +1 -1
- package/dist/modules/kadaikodi/index.js +1 -1
- package/dist/modules/labsofscience/index.cjs +1 -1
- package/dist/modules/labsofscience/index.js +1 -1
- package/dist/modules/manufacturedops/index.cjs +1 -1
- package/dist/modules/manufacturedops/index.js +1 -1
- package/dist/modules/movethewheels/index.cjs +1 -1
- package/dist/modules/movethewheels/index.js +1 -1
- package/dist/modules/mybodyshield/index.cjs +1 -1
- package/dist/modules/mybodyshield/index.js +1 -1
- package/dist/modules/notifications/index.cjs +1 -1
- package/dist/modules/notifications/index.js +1 -1
- package/dist/modules/organizations/index.cjs +1 -1
- package/dist/modules/organizations/index.js +1 -1
- package/dist/modules/planmagnet/index.cjs +1 -1
- package/dist/modules/planmagnet/index.js +1 -1
- package/dist/modules/products/index.cjs +1 -1
- package/dist/modules/products/index.js +1 -1
- package/dist/modules/proserviceworld/index.cjs +1 -1
- package/dist/modules/proserviceworld/index.js +1 -1
- package/dist/modules/rbac/index.cjs +1 -1
- package/dist/modules/rbac/index.js +1 -1
- package/dist/modules/sandbox/index.cjs +1 -1
- package/dist/modules/sandbox/index.js +1 -1
- package/dist/modules/scheduler/index.cjs +1 -1
- package/dist/modules/scheduler/index.js +1 -1
- package/dist/modules/security/index.cjs +1 -1
- package/dist/modules/security/index.js +1 -1
- package/dist/modules/semanticfed/index.cjs +1 -1
- package/dist/modules/semanticfed/index.js +1 -1
- package/dist/modules/store/index.cjs +1 -1
- package/dist/modules/store/index.js +1 -1
- package/dist/modules/subscriberbot/index.cjs +1 -1
- package/dist/modules/subscriberbot/index.js +1 -1
- package/dist/modules/support/index.cjs +1 -1
- package/dist/modules/support/index.js +1 -1
- package/dist/modules/tags/index.cjs +1 -1
- package/dist/modules/tags/index.js +1 -1
- package/dist/modules/technospam/index.cjs +1 -1
- package/dist/modules/technospam/index.js +1 -1
- package/dist/modules/theculturepost/index.cjs +1 -1
- package/dist/modules/theculturepost/index.js +1 -1
- package/dist/modules/theglobalfuel/index.cjs +1 -1
- package/dist/modules/theglobalfuel/index.js +1 -1
- package/dist/modules/timecampus/index.cjs +1 -1
- package/dist/modules/timecampus/index.js +1 -1
- package/dist/modules/tours/index.cjs +1 -1
- package/dist/modules/tours/index.js +1 -1
- package/dist/modules/vibecontrols/index.cjs +2 -2
- package/dist/modules/vibecontrols/index.js +2 -2
- package/dist/modules/workspaces/index.cjs +1 -1
- package/dist/modules/workspaces/index.js +1 -1
- package/dist/transports/hosted.d.ts +33 -0
- package/dist/transports/index.cjs +3 -1
- package/dist/transports/index.d.ts +1 -0
- package/dist/transports/index.js +2 -2
- package/dist/transports-CWPyypes.js +478 -0
- package/dist/transports-CWPyypes.js.map +1 -0
- package/dist/transports-LHVn9JhI.cjs +537 -0
- package/dist/transports-LHVn9JhI.cjs.map +1 -0
- package/package.json +4 -3
- package/dist/core-BKgeqlnN.cjs.map +0 -1
- package/dist/core-zmkvPNsI.js.map +0 -1
- package/dist/transports-BUwYHMg1.js +0 -206
- package/dist/transports-BUwYHMg1.js.map +0 -1
- package/dist/transports-Cz4PCHmm.cjs +0 -253
- package/dist/transports-Cz4PCHmm.cjs.map +0 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { startStdioServer, type StdioOptions } from './stdio.js';
|
|
2
2
|
export { startHttpServer, createHttpApp, type HttpServerOptions, type CreateServerFn, } from './http.js';
|
|
3
|
+
export { createHostedMcpHandler, checkBearerToken, type HostedAuth, type HostedMcpOptions, } from './hosted.js';
|
|
3
4
|
export { parseCorsOrigins, isAuthorizedRequest, requireAuthorizedRequest, isValidSessionId, assertTransportAuthConfigured, } from './security.js';
|
package/dist/transports/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as assertTransportAuthConfigured, c as parseCorsOrigins, i as startHttpServer, l as requireAuthorizedRequest, n as createHostedMcpHandler, o as isAuthorizedRequest, r as createHttpApp, s as isValidSessionId, t as checkBearerToken, u as startStdioServer } from "../transports-CWPyypes.js";
|
|
2
2
|
|
|
3
|
-
export { assertTransportAuthConfigured, createHttpApp, isAuthorizedRequest, isValidSessionId, parseCorsOrigins, requireAuthorizedRequest, startHttpServer, startStdioServer };
|
|
3
|
+
export { assertTransportAuthConfigured, checkBearerToken, createHostedMcpHandler, createHttpApp, isAuthorizedRequest, isValidSessionId, parseCorsOrigins, requireAuthorizedRequest, startHttpServer, startStdioServer };
|
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
import { _ as decodeJwtPayload, n as contextForRequest } from "./context-CNN-D9dE.js";
|
|
2
|
+
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
6
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
7
|
+
|
|
8
|
+
// src/transports/stdio.ts
|
|
9
|
+
/**
|
|
10
|
+
* Stdio transport — connects an existing McpServer over process.stdin/stdout.
|
|
11
|
+
*
|
|
12
|
+
* Stdio reserves stdout for JSON-RPC; ALL diagnostic output must go to stderr.
|
|
13
|
+
* Modules that use ctx.logger are safe; raw console.log is not.
|
|
14
|
+
*/
|
|
15
|
+
async function startStdioServer(server, ctx, _opts = {}) {
|
|
16
|
+
ctx.logger.info("Starting MCP server with stdio transport", {
|
|
17
|
+
name: ctx.serverName,
|
|
18
|
+
version: ctx.serverVersion
|
|
19
|
+
});
|
|
20
|
+
const transport = new StdioServerTransport();
|
|
21
|
+
await server.connect(transport);
|
|
22
|
+
ctx.logger.info("MCP stdio server started");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// src/transports/security.ts
|
|
26
|
+
const SESSION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
27
|
+
function parseCorsOrigins(origins) {
|
|
28
|
+
if (Array.isArray(origins)) return origins;
|
|
29
|
+
const value = origins?.trim();
|
|
30
|
+
if (!value || value === "*") return ["http://127.0.0.1", "http://localhost"];
|
|
31
|
+
return value.split(",").map((origin) => origin.trim()).filter(Boolean);
|
|
32
|
+
}
|
|
33
|
+
function isAuthorizedRequest(req, apiKey) {
|
|
34
|
+
return req.headers.authorization === `Bearer ${apiKey}` || req.headers["x-api-key"] === apiKey;
|
|
35
|
+
}
|
|
36
|
+
function requireAuthorizedRequest(req, res, apiKey) {
|
|
37
|
+
if (!apiKey) {
|
|
38
|
+
res.status(503).json({ error: "Transport authentication is not configured" });
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
if (!isAuthorizedRequest(req, apiKey)) {
|
|
42
|
+
res.status(401).json({ error: "Unauthorized" });
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
function assertTransportAuthConfigured(transport, apiKey) {
|
|
48
|
+
if ((transport === "sse" || transport === "http") && !apiKey) throw new Error("MCP_API_KEY must be configured for HTTP/SSE transports");
|
|
49
|
+
}
|
|
50
|
+
function isValidSessionId(sessionId) {
|
|
51
|
+
return SESSION_ID_PATTERN.test(sessionId);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/transports/http.ts
|
|
55
|
+
/**
|
|
56
|
+
* HTTP transport — Streamable HTTP via Express + CORS.
|
|
57
|
+
*
|
|
58
|
+
* express + cors are OPTIONAL peer deps; we dynamic-import them so stdio-only
|
|
59
|
+
* consumers don't pay the install cost.
|
|
60
|
+
*
|
|
61
|
+
* Ported from vibecontrols-mcp/src/transports/http-simple.ts. Notable:
|
|
62
|
+
* - DNS-rebinding protection ON by default (don't relax!)
|
|
63
|
+
* - Per-session UUID transport instances (multi-client multiplex)
|
|
64
|
+
* - Optional API-key auth (Bearer or X-API-Key)
|
|
65
|
+
*
|
|
66
|
+
* NOTE: each new MCP session re-runs the createServerFn to mint a fresh
|
|
67
|
+
* server instance. The shell passes a factory so each session gets its own
|
|
68
|
+
* registered tools/resources/prompts (current vibecontrols-mcp pattern).
|
|
69
|
+
*/
|
|
70
|
+
/**
|
|
71
|
+
* Build an Express app exposing /mcp + /health endpoints. The createServerFn
|
|
72
|
+
* is invoked once per new MCP session.
|
|
73
|
+
*/
|
|
74
|
+
async function createHttpApp(ctx, createServerFn, options = {}) {
|
|
75
|
+
const expressMod = await import("express");
|
|
76
|
+
const corsMod = await import("cors");
|
|
77
|
+
const express = expressMod.default ?? expressMod;
|
|
78
|
+
const cors = corsMod.default ?? corsMod;
|
|
79
|
+
const cfg = ctx.config.read();
|
|
80
|
+
const app = express();
|
|
81
|
+
app.use(express.json());
|
|
82
|
+
if (options.enableCors !== false) {
|
|
83
|
+
const corsOrigins = options.corsOrigins ?? cfg.corsOrigins;
|
|
84
|
+
app.use(cors({
|
|
85
|
+
origin: parseCorsOrigins(corsOrigins),
|
|
86
|
+
exposedHeaders: ["Mcp-Session-Id"],
|
|
87
|
+
allowedHeaders: [
|
|
88
|
+
"Content-Type",
|
|
89
|
+
"Authorization",
|
|
90
|
+
"X-API-Key",
|
|
91
|
+
"mcp-session-id"
|
|
92
|
+
]
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
95
|
+
const transports = {};
|
|
96
|
+
const apiKey = options.apiKey ?? cfg.apiKey;
|
|
97
|
+
app.post("/mcp", async (req, res) => {
|
|
98
|
+
if (!requireAuthorizedRequest(req, res, apiKey)) return;
|
|
99
|
+
try {
|
|
100
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
101
|
+
let transport;
|
|
102
|
+
if (sessionId && !isValidSessionId(sessionId)) {
|
|
103
|
+
res.status(400).json({
|
|
104
|
+
jsonrpc: "2.0",
|
|
105
|
+
error: {
|
|
106
|
+
code: -32e3,
|
|
107
|
+
message: "Bad Request: Invalid session ID provided"
|
|
108
|
+
},
|
|
109
|
+
id: null
|
|
110
|
+
});
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (sessionId && transports[sessionId]) transport = transports[sessionId];
|
|
114
|
+
else if (!sessionId && isInitializeRequest(req.body)) {
|
|
115
|
+
transport = new StreamableHTTPServerTransport({
|
|
116
|
+
sessionIdGenerator: () => randomUUID(),
|
|
117
|
+
onsessioninitialized: (sid) => {
|
|
118
|
+
transports[sid] = transport;
|
|
119
|
+
ctx.logger.info("New MCP session initialized", { sessionId: sid });
|
|
120
|
+
},
|
|
121
|
+
enableDnsRebindingProtection: options.enableDnsRebindingProtection ?? true,
|
|
122
|
+
allowedHosts: options.allowedHosts ?? cfg.allowedHosts.split(",")
|
|
123
|
+
});
|
|
124
|
+
transport.onclose = () => {
|
|
125
|
+
if (transport.sessionId) {
|
|
126
|
+
delete transports[transport.sessionId];
|
|
127
|
+
ctx.logger.info("MCP session closed", { sessionId: transport.sessionId });
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
await createServerFn().connect(transport);
|
|
131
|
+
} else {
|
|
132
|
+
res.status(400).json({
|
|
133
|
+
jsonrpc: "2.0",
|
|
134
|
+
error: {
|
|
135
|
+
code: -32e3,
|
|
136
|
+
message: "Bad Request: No valid session ID provided"
|
|
137
|
+
},
|
|
138
|
+
id: null
|
|
139
|
+
});
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
await transport.handleRequest(req, res, req.body);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
ctx.logger.error("Error handling MCP request", { error: error instanceof Error ? error.message : String(error) });
|
|
145
|
+
if (!res.headersSent) res.status(500).json({
|
|
146
|
+
jsonrpc: "2.0",
|
|
147
|
+
error: {
|
|
148
|
+
code: -32603,
|
|
149
|
+
message: "Internal server error"
|
|
150
|
+
},
|
|
151
|
+
id: null
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
const handleSessionRequest = async (req, res) => {
|
|
156
|
+
if (!requireAuthorizedRequest(req, res, apiKey)) return;
|
|
157
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
158
|
+
if (!sessionId || !isValidSessionId(sessionId) || !transports[sessionId]) {
|
|
159
|
+
res.status(400).send("Invalid or missing session ID");
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
await transports[sessionId].handleRequest(req, res);
|
|
163
|
+
};
|
|
164
|
+
app.get("/mcp", handleSessionRequest);
|
|
165
|
+
app.delete("/mcp", handleSessionRequest);
|
|
166
|
+
app.get("/health", (_req, res) => {
|
|
167
|
+
res.json({
|
|
168
|
+
status: "healthy",
|
|
169
|
+
server: ctx.serverName,
|
|
170
|
+
version: ctx.serverVersion,
|
|
171
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
172
|
+
uptime: process.uptime(),
|
|
173
|
+
activeSessions: Object.keys(transports).length
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
return app;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Start the HTTP transport. The shell passes a factory because each new MCP
|
|
180
|
+
* session needs a fresh server instance with its own per-session state.
|
|
181
|
+
*/
|
|
182
|
+
async function startHttpServer(ctx, createServerFn, options = {}) {
|
|
183
|
+
const cfg = ctx.config.read();
|
|
184
|
+
const port = options.port ?? cfg.httpPort;
|
|
185
|
+
const host = options.host ?? cfg.host;
|
|
186
|
+
ctx.logger.info("Starting MCP server with HTTP transport", {
|
|
187
|
+
port,
|
|
188
|
+
host,
|
|
189
|
+
name: ctx.serverName,
|
|
190
|
+
version: ctx.serverVersion
|
|
191
|
+
});
|
|
192
|
+
const app = await createHttpApp(ctx, createServerFn, options);
|
|
193
|
+
await new Promise((resolve, reject) => {
|
|
194
|
+
app.listen(port, host, (err) => {
|
|
195
|
+
if (err) reject(err);
|
|
196
|
+
else {
|
|
197
|
+
ctx.logger.info("MCP HTTP server started", {
|
|
198
|
+
port,
|
|
199
|
+
host
|
|
200
|
+
});
|
|
201
|
+
resolve();
|
|
202
|
+
}
|
|
203
|
+
}).on("error", reject);
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// src/transports/hosted.ts
|
|
208
|
+
/**
|
|
209
|
+
* Hosted MCP transport (BOFF-15144): one public, multi-user MCP endpoint that
|
|
210
|
+
* Claude, ChatGPT and other remote MCP clients connect to with OAuth.
|
|
211
|
+
*
|
|
212
|
+
* - Stateless Streamable HTTP: every POST /mcp gets its own server, context
|
|
213
|
+
* and transport (no session id, JSON responses), so requests from different
|
|
214
|
+
* users never share credentials and any replica can serve any request.
|
|
215
|
+
* - OAuth 2.1 protected resource (RFC 9728): `/.well-known/oauth-protected-resource`
|
|
216
|
+
* names the authorization server. A request without a usable bearer token is
|
|
217
|
+
* answered 401 with `WWW-Authenticate: Bearer resource_metadata="..."`, which
|
|
218
|
+
* is how MCP clients discover where to sign the user in.
|
|
219
|
+
* - The token is checked here only for shape, type, expiry and audience. This
|
|
220
|
+
* server never authorizes anything itself: it forwards the user's token to
|
|
221
|
+
* the platform gateways, which verify the signature, the delegation and the
|
|
222
|
+
* user's role on every GraphQL call.
|
|
223
|
+
*
|
|
224
|
+
* Framework-free: a `(Request) => Promise<Response>` handler, served with
|
|
225
|
+
* `Bun.serve` (or any Web-standard server) by the product shell.
|
|
226
|
+
*/
|
|
227
|
+
const READ_SCOPE = "delegation:read";
|
|
228
|
+
const WRITE_SCOPES = /* @__PURE__ */ new Set(["delegation:write", "agent:act"]);
|
|
229
|
+
/** Tolerate small clock differences between the auth service and this pod. */
|
|
230
|
+
const CLOCK_SKEW_SECONDS = 30;
|
|
231
|
+
const MAX_BODY_BYTES = 4194304;
|
|
232
|
+
const CORS_HEADERS = Object.freeze({
|
|
233
|
+
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
234
|
+
"Access-Control-Allow-Headers": "Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Last-Event-ID",
|
|
235
|
+
"Access-Control-Expose-Headers": "WWW-Authenticate, Mcp-Session-Id, MCP-Protocol-Version",
|
|
236
|
+
"Access-Control-Max-Age": "600"
|
|
237
|
+
});
|
|
238
|
+
/** Decode and sanity-check a bearer token. The gateways do the real verification. */
|
|
239
|
+
function checkBearerToken(header, resourceUrl, nowSeconds) {
|
|
240
|
+
const token = (header?.match(/^Bearer\s+(\S+)$/i))?.[1];
|
|
241
|
+
if (!token) return {
|
|
242
|
+
ok: false,
|
|
243
|
+
reason: "missing"
|
|
244
|
+
};
|
|
245
|
+
const claims = decodeJwtPayload(token);
|
|
246
|
+
if (!claims) return {
|
|
247
|
+
ok: false,
|
|
248
|
+
reason: "invalid",
|
|
249
|
+
description: "malformed token"
|
|
250
|
+
};
|
|
251
|
+
if (claims["type"] !== "app_as_user") return {
|
|
252
|
+
ok: false,
|
|
253
|
+
reason: "invalid",
|
|
254
|
+
description: "not a connector token"
|
|
255
|
+
};
|
|
256
|
+
const exp = claims["exp"];
|
|
257
|
+
if (typeof exp !== "number" || exp + CLOCK_SKEW_SECONDS <= nowSeconds) return {
|
|
258
|
+
ok: false,
|
|
259
|
+
reason: "invalid",
|
|
260
|
+
description: "token expired"
|
|
261
|
+
};
|
|
262
|
+
const aud = claims["aud"];
|
|
263
|
+
if (!(Array.isArray(aud) ? aud : [aud]).includes(resourceUrl)) return {
|
|
264
|
+
ok: false,
|
|
265
|
+
reason: "invalid",
|
|
266
|
+
description: "token was issued for another resource"
|
|
267
|
+
};
|
|
268
|
+
const sub = claims["sub"];
|
|
269
|
+
if (typeof sub !== "string" || !sub) return {
|
|
270
|
+
ok: false,
|
|
271
|
+
reason: "invalid",
|
|
272
|
+
description: "token has no subject"
|
|
273
|
+
};
|
|
274
|
+
const scopes = Array.isArray(claims["scopes"]) ? claims["scopes"].filter((s) => typeof s === "string") : [];
|
|
275
|
+
const workspaceId = claims["workspace_id"];
|
|
276
|
+
const act = claims["act"];
|
|
277
|
+
return {
|
|
278
|
+
ok: true,
|
|
279
|
+
auth: {
|
|
280
|
+
token,
|
|
281
|
+
userId: sub,
|
|
282
|
+
...typeof workspaceId === "string" ? { workspaceId } : {},
|
|
283
|
+
scopes,
|
|
284
|
+
readOnly: scopes.includes(READ_SCOPE) && !scopes.some((s) => WRITE_SCOPES.has(s)),
|
|
285
|
+
...typeof act?.clientId === "string" ? { clientId: act.clientId } : {},
|
|
286
|
+
expiresAt: exp
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
function metadataUrl(resourceUrl) {
|
|
291
|
+
return `${new URL(resourceUrl).origin}/.well-known/oauth-protected-resource`;
|
|
292
|
+
}
|
|
293
|
+
var BodyTooLargeError = class extends Error {};
|
|
294
|
+
/** Read and parse a JSON body, refusing more than `max` bytes even without Content-Length. */
|
|
295
|
+
async function readBoundedJson(request, max) {
|
|
296
|
+
if (!request.body) throw new SyntaxError("empty body");
|
|
297
|
+
const reader = request.body.getReader();
|
|
298
|
+
const chunks = [];
|
|
299
|
+
let size = 0;
|
|
300
|
+
for (;;) {
|
|
301
|
+
const { done, value } = await reader.read();
|
|
302
|
+
if (done) break;
|
|
303
|
+
size += value.byteLength;
|
|
304
|
+
if (size > max) {
|
|
305
|
+
await reader.cancel();
|
|
306
|
+
throw new BodyTooLargeError();
|
|
307
|
+
}
|
|
308
|
+
chunks.push(value);
|
|
309
|
+
}
|
|
310
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
311
|
+
}
|
|
312
|
+
/** Whether a request body is a JSON-RPC initialize (single or batched). */
|
|
313
|
+
function containsInitialize(body) {
|
|
314
|
+
return (Array.isArray(body) ? body : [body]).some((message) => !!message && typeof message === "object" && message.method === "initialize");
|
|
315
|
+
}
|
|
316
|
+
function createHostedMcpHandler(options) {
|
|
317
|
+
const now = options.now ?? Date.now;
|
|
318
|
+
const resourcePath = new URL(options.resourceUrl).pathname;
|
|
319
|
+
const metadataLink = metadataUrl(options.resourceUrl);
|
|
320
|
+
const allowedOrigins = new Set(options.allowedOrigins ?? []);
|
|
321
|
+
const logger = options.baseContext.logger;
|
|
322
|
+
const resourceMetadata = {
|
|
323
|
+
resource: options.resourceUrl,
|
|
324
|
+
authorization_servers: options.authorizationServers,
|
|
325
|
+
scopes_supported: options.scopesSupported ?? [READ_SCOPE, "delegation:write"],
|
|
326
|
+
bearer_methods_supported: ["header"],
|
|
327
|
+
resource_name: options.resourceName
|
|
328
|
+
};
|
|
329
|
+
const withCors = (response, origin) => {
|
|
330
|
+
const headers = new Headers(response.headers);
|
|
331
|
+
for (const [name, value] of Object.entries(CORS_HEADERS)) headers.set(name, value);
|
|
332
|
+
headers.set("Access-Control-Allow-Origin", origin && allowedOrigins.has(origin) ? origin : "*");
|
|
333
|
+
headers.append("Vary", "Origin");
|
|
334
|
+
return new Response(response.body, {
|
|
335
|
+
status: response.status,
|
|
336
|
+
headers
|
|
337
|
+
});
|
|
338
|
+
};
|
|
339
|
+
const json = (status, body, extra = {}) => new Response(JSON.stringify(body), {
|
|
340
|
+
status,
|
|
341
|
+
headers: {
|
|
342
|
+
"Content-Type": "application/json",
|
|
343
|
+
"Cache-Control": "no-store",
|
|
344
|
+
...extra
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
const unauthorized = (reason, description) => {
|
|
348
|
+
const params = [`resource_metadata="${metadataLink}"`];
|
|
349
|
+
if (reason === "invalid") {
|
|
350
|
+
params.push("error=\"invalid_token\"");
|
|
351
|
+
if (description) params.push(`error_description="${description}"`);
|
|
352
|
+
}
|
|
353
|
+
return json(401, {
|
|
354
|
+
jsonrpc: "2.0",
|
|
355
|
+
error: {
|
|
356
|
+
code: -32001,
|
|
357
|
+
message: "Authentication required"
|
|
358
|
+
},
|
|
359
|
+
id: null
|
|
360
|
+
}, { "WWW-Authenticate": `Bearer ${params.join(", ")}` });
|
|
361
|
+
};
|
|
362
|
+
const handleMcpPost = async (request) => {
|
|
363
|
+
if (Number(request.headers.get("content-length") ?? "0") > MAX_BODY_BYTES) return json(413, {
|
|
364
|
+
jsonrpc: "2.0",
|
|
365
|
+
error: {
|
|
366
|
+
code: -32600,
|
|
367
|
+
message: "Request too large"
|
|
368
|
+
},
|
|
369
|
+
id: null
|
|
370
|
+
});
|
|
371
|
+
const check = checkBearerToken(request.headers.get("authorization"), options.resourceUrl, Math.floor(now() / 1e3));
|
|
372
|
+
if (!check.ok) return unauthorized(check.reason, check.description);
|
|
373
|
+
const { auth } = check;
|
|
374
|
+
let body;
|
|
375
|
+
try {
|
|
376
|
+
body = await readBoundedJson(request, MAX_BODY_BYTES);
|
|
377
|
+
} catch (error) {
|
|
378
|
+
if (error instanceof BodyTooLargeError) return json(413, {
|
|
379
|
+
jsonrpc: "2.0",
|
|
380
|
+
error: {
|
|
381
|
+
code: -32600,
|
|
382
|
+
message: "Request too large"
|
|
383
|
+
},
|
|
384
|
+
id: null
|
|
385
|
+
});
|
|
386
|
+
return json(400, {
|
|
387
|
+
jsonrpc: "2.0",
|
|
388
|
+
error: {
|
|
389
|
+
code: -32700,
|
|
390
|
+
message: "Parse error"
|
|
391
|
+
},
|
|
392
|
+
id: null
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
const ctx = contextForRequest(options.baseContext, {
|
|
396
|
+
accessToken: auth.token,
|
|
397
|
+
refreshToken: "",
|
|
398
|
+
...auth.workspaceId ? { workspaceId: auth.workspaceId } : {}
|
|
399
|
+
});
|
|
400
|
+
if (options.preflight && containsInitialize(body)) {
|
|
401
|
+
let accepted;
|
|
402
|
+
try {
|
|
403
|
+
accepted = await options.preflight(ctx, auth);
|
|
404
|
+
} catch (error) {
|
|
405
|
+
logger.error("Hosted MCP preflight failed", { error: error instanceof Error ? error.message : String(error) });
|
|
406
|
+
return json(503, {
|
|
407
|
+
jsonrpc: "2.0",
|
|
408
|
+
error: {
|
|
409
|
+
code: -32603,
|
|
410
|
+
message: "Platform temporarily unavailable"
|
|
411
|
+
},
|
|
412
|
+
id: null
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
if (!accepted) return unauthorized("invalid", "token no longer accepted");
|
|
416
|
+
}
|
|
417
|
+
const server = options.createServer(ctx, auth);
|
|
418
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
419
|
+
sessionIdGenerator: void 0,
|
|
420
|
+
enableJsonResponse: true
|
|
421
|
+
});
|
|
422
|
+
try {
|
|
423
|
+
await server.connect(transport);
|
|
424
|
+
return await transport.handleRequest(request, { parsedBody: body });
|
|
425
|
+
} finally {
|
|
426
|
+
await server.close().catch(() => void 0);
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
return async (request) => {
|
|
430
|
+
const url = new URL(request.url);
|
|
431
|
+
const origin = request.headers.get("origin");
|
|
432
|
+
const method = request.method.toUpperCase();
|
|
433
|
+
if (url.pathname === "/health" && method === "GET") return json(200, {
|
|
434
|
+
status: "healthy",
|
|
435
|
+
server: options.baseContext.serverName,
|
|
436
|
+
version: options.baseContext.serverVersion
|
|
437
|
+
});
|
|
438
|
+
if (url.pathname === "/.well-known/oauth-protected-resource" || url.pathname === `/.well-known/oauth-protected-resource${resourcePath}`) {
|
|
439
|
+
if (method === "OPTIONS") return withCors(new Response(null, { status: 204 }), origin);
|
|
440
|
+
if (method !== "GET") return withCors(json(405, { error: "method not allowed" }, { Allow: "GET" }), origin);
|
|
441
|
+
return withCors(json(200, resourceMetadata, { "Cache-Control": "public, max-age=300" }), origin);
|
|
442
|
+
}
|
|
443
|
+
if (url.pathname !== resourcePath) return json(404, { error: "not found" });
|
|
444
|
+
if (origin && !allowedOrigins.has(origin)) return json(403, {
|
|
445
|
+
jsonrpc: "2.0",
|
|
446
|
+
error: {
|
|
447
|
+
code: -32e3,
|
|
448
|
+
message: "Origin not allowed"
|
|
449
|
+
},
|
|
450
|
+
id: null
|
|
451
|
+
});
|
|
452
|
+
if (method === "OPTIONS") return withCors(new Response(null, { status: 204 }), origin);
|
|
453
|
+
if (method !== "POST") return withCors(json(405, {
|
|
454
|
+
jsonrpc: "2.0",
|
|
455
|
+
error: {
|
|
456
|
+
code: -32e3,
|
|
457
|
+
message: "Method not allowed"
|
|
458
|
+
},
|
|
459
|
+
id: null
|
|
460
|
+
}, { Allow: "POST, OPTIONS" }), origin);
|
|
461
|
+
try {
|
|
462
|
+
return withCors(await handleMcpPost(request), origin);
|
|
463
|
+
} catch (error) {
|
|
464
|
+
logger.error("Hosted MCP request failed", { error: error instanceof Error ? error.message : String(error) });
|
|
465
|
+
return withCors(json(500, {
|
|
466
|
+
jsonrpc: "2.0",
|
|
467
|
+
error: {
|
|
468
|
+
code: -32603,
|
|
469
|
+
message: "Internal server error"
|
|
470
|
+
},
|
|
471
|
+
id: null
|
|
472
|
+
}), origin);
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
export { assertTransportAuthConfigured as a, parseCorsOrigins as c, startHttpServer as i, requireAuthorizedRequest as l, createHostedMcpHandler as n, isAuthorizedRequest as o, createHttpApp as r, isValidSessionId as s, checkBearerToken as t, startStdioServer as u };
|
|
478
|
+
//# sourceMappingURL=transports-CWPyypes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transports-CWPyypes.js","names":[],"sources":["../src/transports/stdio.ts","../src/transports/security.ts","../src/transports/http.ts","../src/transports/hosted.ts"],"sourcesContent":["/**\n * Stdio transport — connects an existing McpServer over process.stdin/stdout.\n *\n * Stdio reserves stdout for JSON-RPC; ALL diagnostic output must go to stderr.\n * Modules that use ctx.logger are safe; raw console.log is not.\n */\n\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { McpContext } from '../core/context.js';\n\nexport interface StdioOptions {\n /** No-op hook for symmetry with HTTP options. */\n signal?: AbortSignal;\n}\n\nexport async function startStdioServer(\n server: McpServer,\n ctx: McpContext,\n _opts: StdioOptions = {},\n): Promise<void> {\n ctx.logger.info('Starting MCP server with stdio transport', {\n name: ctx.serverName,\n version: ctx.serverVersion,\n });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n\n ctx.logger.info('MCP stdio server started');\n}\n","/**\n * HTTP transport security helpers — ported verbatim from\n * vibecontrols-mcp/src/transports/security.ts.\n *\n * - parseCorsOrigins: comma-separated string → array (defaults to localhost-only)\n * - isAuthorizedRequest: Bearer or X-API-Key header check\n * - requireAuthorizedRequest: 401/503 short-circuit middleware\n * - isValidSessionId: UUID v1-8 pattern guard\n */\n\nimport type { Request, Response } from 'express';\n\nconst SESSION_ID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport function parseCorsOrigins(origins: string | string[] | undefined): string[] {\n if (Array.isArray(origins)) return origins;\n\n const value = origins?.trim();\n if (!value || value === '*') {\n return ['http://127.0.0.1', 'http://localhost'];\n }\n\n return value\n .split(',')\n .map((origin) => origin.trim())\n .filter(Boolean);\n}\n\nexport function isAuthorizedRequest(req: Request, apiKey: string): boolean {\n return req.headers.authorization === `Bearer ${apiKey}` || req.headers['x-api-key'] === apiKey;\n}\n\nexport function requireAuthorizedRequest(\n req: Request,\n res: Response,\n apiKey: string | undefined,\n): boolean {\n if (!apiKey) {\n res.status(503).json({ error: 'Transport authentication is not configured' });\n return false;\n }\n\n if (!isAuthorizedRequest(req, apiKey)) {\n res.status(401).json({ error: 'Unauthorized' });\n return false;\n }\n\n return true;\n}\n\nexport function assertTransportAuthConfigured(\n transport: 'stdio' | 'sse' | 'http',\n apiKey: string | undefined,\n): void {\n if ((transport === 'sse' || transport === 'http') && !apiKey) {\n throw new Error('MCP_API_KEY must be configured for HTTP/SSE transports');\n }\n}\n\nexport function isValidSessionId(sessionId: string): boolean {\n return SESSION_ID_PATTERN.test(sessionId);\n}\n","/**\n * HTTP transport — Streamable HTTP via Express + CORS.\n *\n * express + cors are OPTIONAL peer deps; we dynamic-import them so stdio-only\n * consumers don't pay the install cost.\n *\n * Ported from vibecontrols-mcp/src/transports/http-simple.ts. Notable:\n * - DNS-rebinding protection ON by default (don't relax!)\n * - Per-session UUID transport instances (multi-client multiplex)\n * - Optional API-key auth (Bearer or X-API-Key)\n *\n * NOTE: each new MCP session re-runs the createServerFn to mint a fresh\n * server instance. The shell passes a factory so each session gets its own\n * registered tools/resources/prompts (current vibecontrols-mcp pattern).\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { McpContext } from '../core/context.js';\nimport { isValidSessionId, parseCorsOrigins, requireAuthorizedRequest } from './security.js';\n\nexport interface HttpServerOptions {\n port?: number;\n host?: string;\n apiKey?: string;\n enableCors?: boolean;\n corsOrigins?: string | string[];\n enableDnsRebindingProtection?: boolean;\n allowedHosts?: string[];\n}\n\nexport type CreateServerFn = () => McpServer;\n\n/**\n * Build an Express app exposing /mcp + /health endpoints. The createServerFn\n * is invoked once per new MCP session.\n */\nexport async function createHttpApp(\n ctx: McpContext,\n createServerFn: CreateServerFn,\n options: HttpServerOptions = {},\n): Promise<unknown /* express.Application */> {\n // Dynamic-import express + cors so stdio-only consumers don't pay the cost.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const expressMod = (await import('express' as any)) as any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const corsMod = (await import('cors' as any)) as any;\n\n const express = expressMod.default ?? expressMod;\n const cors = corsMod.default ?? corsMod;\n\n const cfg = ctx.config.read();\n const app = express();\n\n app.use(express.json());\n\n if (options.enableCors !== false) {\n const corsOrigins = options.corsOrigins ?? cfg.corsOrigins;\n app.use(\n cors({\n origin: parseCorsOrigins(corsOrigins),\n exposedHeaders: ['Mcp-Session-Id'],\n allowedHeaders: ['Content-Type', 'Authorization', 'X-API-Key', 'mcp-session-id'],\n }),\n );\n }\n\n const transports: Record<string, StreamableHTTPServerTransport> = {};\n const apiKey = options.apiKey ?? cfg.apiKey;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n app.post('/mcp', async (req: any, res: any) => {\n if (!requireAuthorizedRequest(req, res, apiKey)) return;\n\n try {\n const sessionId = req.headers['mcp-session-id'] as string | undefined;\n let transport: StreamableHTTPServerTransport;\n\n if (sessionId && !isValidSessionId(sessionId)) {\n res.status(400).json({\n jsonrpc: '2.0',\n error: { code: -32000, message: 'Bad Request: Invalid session ID provided' },\n id: null,\n });\n return;\n }\n\n if (sessionId && transports[sessionId]) {\n transport = transports[sessionId];\n } else if (!sessionId && isInitializeRequest(req.body)) {\n transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n onsessioninitialized: (sid) => {\n transports[sid] = transport;\n ctx.logger.info('New MCP session initialized', { sessionId: sid });\n },\n enableDnsRebindingProtection: options.enableDnsRebindingProtection ?? true,\n allowedHosts: options.allowedHosts ?? cfg.allowedHosts.split(','),\n });\n\n transport.onclose = (): void => {\n if (transport.sessionId) {\n delete transports[transport.sessionId];\n ctx.logger.info('MCP session closed', { sessionId: transport.sessionId });\n }\n };\n\n const server = createServerFn();\n await server.connect(transport);\n } else {\n res.status(400).json({\n jsonrpc: '2.0',\n error: { code: -32000, message: 'Bad Request: No valid session ID provided' },\n id: null,\n });\n return;\n }\n\n await transport.handleRequest(req, res, req.body);\n } catch (error) {\n ctx.logger.error('Error handling MCP request', {\n error: error instanceof Error ? error.message : String(error),\n });\n if (!res.headersSent) {\n res.status(500).json({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n });\n }\n }\n });\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const handleSessionRequest = async (req: any, res: any): Promise<void> => {\n if (!requireAuthorizedRequest(req, res, apiKey)) return;\n const sessionId = req.headers['mcp-session-id'] as string | undefined;\n if (!sessionId || !isValidSessionId(sessionId) || !transports[sessionId]) {\n res.status(400).send('Invalid or missing session ID');\n return;\n }\n await transports[sessionId].handleRequest(req, res);\n };\n\n app.get('/mcp', handleSessionRequest);\n app.delete('/mcp', handleSessionRequest);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n app.get('/health', (_req: any, res: any) => {\n res.json({\n status: 'healthy',\n server: ctx.serverName,\n version: ctx.serverVersion,\n timestamp: new Date().toISOString(),\n uptime: process.uptime(),\n activeSessions: Object.keys(transports).length,\n });\n });\n\n return app;\n}\n\n/**\n * Start the HTTP transport. The shell passes a factory because each new MCP\n * session needs a fresh server instance with its own per-session state.\n */\nexport async function startHttpServer(\n ctx: McpContext,\n createServerFn: CreateServerFn,\n options: HttpServerOptions = {},\n): Promise<void> {\n const cfg = ctx.config.read();\n const port = options.port ?? cfg.httpPort;\n const host = options.host ?? cfg.host;\n\n ctx.logger.info('Starting MCP server with HTTP transport', {\n port,\n host,\n name: ctx.serverName,\n version: ctx.serverVersion,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const app = (await createHttpApp(ctx, createServerFn, options)) as any;\n\n await new Promise<void>((resolve, reject) => {\n const server = app.listen(port, host, (err?: Error) => {\n if (err) reject(err);\n else {\n ctx.logger.info('MCP HTTP server started', { port, host });\n resolve();\n }\n });\n server.on('error', reject);\n });\n}\n","/**\n * Hosted MCP transport (BOFF-15144): one public, multi-user MCP endpoint that\n * Claude, ChatGPT and other remote MCP clients connect to with OAuth.\n *\n * - Stateless Streamable HTTP: every POST /mcp gets its own server, context\n * and transport (no session id, JSON responses), so requests from different\n * users never share credentials and any replica can serve any request.\n * - OAuth 2.1 protected resource (RFC 9728): `/.well-known/oauth-protected-resource`\n * names the authorization server. A request without a usable bearer token is\n * answered 401 with `WWW-Authenticate: Bearer resource_metadata=\"...\"`, which\n * is how MCP clients discover where to sign the user in.\n * - The token is checked here only for shape, type, expiry and audience. This\n * server never authorizes anything itself: it forwards the user's token to\n * the platform gateways, which verify the signature, the delegation and the\n * user's role on every GraphQL call.\n *\n * Framework-free: a `(Request) => Promise<Response>` handler, served with\n * `Bun.serve` (or any Web-standard server) by the product shell.\n */\n\nimport { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport { decodeJwtPayload } from '../core/auth/store.js';\nimport { type McpContext, contextForRequest } from '../core/context.js';\n\n/** The connector identity a request carries, decoded from its bearer token. */\nexport interface HostedAuth {\n token: string;\n /** User the connector acts for (`sub`). */\n userId: string;\n /** The one workspace the token is bound to (`workspace_id`). */\n workspaceId?: string;\n /** Delegation scopes, e.g. `delegation:read`, `delegation:write`. */\n scopes: string[];\n /** True when the token cannot change data (`delegation:read` only). */\n readOnly: boolean;\n /** OAuth client id of the connector (`act.clientId`). */\n clientId?: string;\n /** Token expiry, epoch seconds. */\n expiresAt: number;\n}\n\nexport interface HostedMcpOptions {\n /** Shared configuration, logger and product identity. Its auth store is never used. */\n baseContext: McpContext;\n /** Exact resource URL clients connect to and tokens are minted for, e.g. https://mcp.fluidgrids.ai/mcp */\n resourceUrl: string;\n /** Authorization server issuer URLs, e.g. https://auth.burdenoff.com */\n authorizationServers: string[];\n /** Human-readable name in the resource metadata. */\n resourceName: string;\n scopesSupported?: string[];\n /** Build the server for one request. Receives the request's own context. */\n createServer: (ctx: McpContext, auth: HostedAuth) => McpServer;\n /**\n * Optional check on `initialize` that the platform still accepts the token\n * (e.g. a cheap GraphQL query). Resolve false to answer 401 so the client\n * re-runs the OAuth flow; throw to answer 503.\n */\n preflight?: (ctx: McpContext, auth: HostedAuth) => Promise<boolean>;\n /** Browser origins allowed to call /mcp (MCP Inspector etc.). Requests without Origin are always allowed. */\n allowedOrigins?: string[];\n now?: () => number;\n}\n\nconst READ_SCOPE = 'delegation:read';\nconst WRITE_SCOPES = new Set(['delegation:write', 'agent:act']);\n/** Tolerate small clock differences between the auth service and this pod. */\nconst CLOCK_SKEW_SECONDS = 30;\nconst MAX_BODY_BYTES = 4 * 1024 * 1024;\n\nconst CORS_HEADERS: Readonly<Record<string, string>> = Object.freeze({\n 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id, Last-Event-ID',\n 'Access-Control-Expose-Headers': 'WWW-Authenticate, Mcp-Session-Id, MCP-Protocol-Version',\n 'Access-Control-Max-Age': '600',\n});\n\ntype TokenCheck =\n | { ok: true; auth: HostedAuth }\n | { ok: false; reason: 'missing' | 'invalid'; description?: string };\n\n/** Decode and sanity-check a bearer token. The gateways do the real verification. */\nexport function checkBearerToken(\n header: string | null,\n resourceUrl: string,\n nowSeconds: number,\n): TokenCheck {\n const match = header?.match(/^Bearer\\s+(\\S+)$/i);\n const token = match?.[1];\n if (!token) return { ok: false, reason: 'missing' };\n\n const claims = decodeJwtPayload(token);\n if (!claims) return { ok: false, reason: 'invalid', description: 'malformed token' };\n if (claims['type'] !== 'app_as_user') {\n return { ok: false, reason: 'invalid', description: 'not a connector token' };\n }\n const exp = claims['exp'];\n if (typeof exp !== 'number' || exp + CLOCK_SKEW_SECONDS <= nowSeconds) {\n return { ok: false, reason: 'invalid', description: 'token expired' };\n }\n const aud = claims['aud'];\n const audiences = Array.isArray(aud) ? aud : [aud];\n if (!audiences.includes(resourceUrl)) {\n return { ok: false, reason: 'invalid', description: 'token was issued for another resource' };\n }\n const sub = claims['sub'];\n if (typeof sub !== 'string' || !sub) {\n return { ok: false, reason: 'invalid', description: 'token has no subject' };\n }\n\n const scopes = Array.isArray(claims['scopes'])\n ? (claims['scopes'] as unknown[]).filter((s): s is string => typeof s === 'string')\n : [];\n const workspaceId = claims['workspace_id'];\n const act = claims['act'] as { clientId?: unknown } | undefined;\n return {\n ok: true,\n auth: {\n token,\n userId: sub,\n ...(typeof workspaceId === 'string' ? { workspaceId } : {}),\n scopes,\n readOnly: scopes.includes(READ_SCOPE) && !scopes.some((s) => WRITE_SCOPES.has(s)),\n ...(typeof act?.clientId === 'string' ? { clientId: act.clientId } : {}),\n expiresAt: exp,\n },\n };\n}\n\nfunction metadataUrl(resourceUrl: string): string {\n const url = new URL(resourceUrl);\n return `${url.origin}/.well-known/oauth-protected-resource`;\n}\n\nclass BodyTooLargeError extends Error {}\n\n/** Read and parse a JSON body, refusing more than `max` bytes even without Content-Length. */\nasync function readBoundedJson(request: Request, max: number): Promise<unknown> {\n if (!request.body) throw new SyntaxError('empty body');\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > max) {\n await reader.cancel();\n throw new BodyTooLargeError();\n }\n chunks.push(value);\n }\n return JSON.parse(Buffer.concat(chunks).toString('utf8'));\n}\n\n/** Whether a request body is a JSON-RPC initialize (single or batched). */\nfunction containsInitialize(body: unknown): boolean {\n const messages = Array.isArray(body) ? body : [body];\n return messages.some(\n (message) =>\n !!message &&\n typeof message === 'object' &&\n (message as { method?: unknown }).method === 'initialize',\n );\n}\n\nexport function createHostedMcpHandler(\n options: HostedMcpOptions,\n): (request: Request) => Promise<Response> {\n const now = options.now ?? Date.now;\n const resourcePath = new URL(options.resourceUrl).pathname;\n const metadataLink = metadataUrl(options.resourceUrl);\n const allowedOrigins = new Set(options.allowedOrigins ?? []);\n const logger = options.baseContext.logger;\n\n const resourceMetadata = {\n resource: options.resourceUrl,\n authorization_servers: options.authorizationServers,\n scopes_supported: options.scopesSupported ?? [READ_SCOPE, 'delegation:write'],\n bearer_methods_supported: ['header'],\n resource_name: options.resourceName,\n };\n\n const withCors = (response: Response, origin: string | null): Response => {\n const headers = new Headers(response.headers);\n for (const [name, value] of Object.entries(CORS_HEADERS)) headers.set(name, value);\n headers.set('Access-Control-Allow-Origin', origin && allowedOrigins.has(origin) ? origin : '*');\n headers.append('Vary', 'Origin');\n return new Response(response.body, { status: response.status, headers });\n };\n\n const json = (status: number, body: unknown, extra: Record<string, string> = {}): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...extra },\n });\n\n const unauthorized = (reason: 'missing' | 'invalid', description?: string): Response => {\n const params = [`resource_metadata=\"${metadataLink}\"`];\n if (reason === 'invalid') {\n params.push('error=\"invalid_token\"');\n if (description) params.push(`error_description=\"${description}\"`);\n }\n return json(\n 401,\n { jsonrpc: '2.0', error: { code: -32001, message: 'Authentication required' }, id: null },\n { 'WWW-Authenticate': `Bearer ${params.join(', ')}` },\n );\n };\n\n const handleMcpPost = async (request: Request): Promise<Response> => {\n const length = Number(request.headers.get('content-length') ?? '0');\n if (length > MAX_BODY_BYTES) {\n return json(413, {\n jsonrpc: '2.0',\n error: { code: -32600, message: 'Request too large' },\n id: null,\n });\n }\n\n const check = checkBearerToken(\n request.headers.get('authorization'),\n options.resourceUrl,\n Math.floor(now() / 1000),\n );\n if (!check.ok) return unauthorized(check.reason, check.description);\n const { auth } = check;\n\n let body: unknown;\n try {\n body = await readBoundedJson(request, MAX_BODY_BYTES);\n } catch (error) {\n if (error instanceof BodyTooLargeError) {\n return json(413, {\n jsonrpc: '2.0',\n error: { code: -32600, message: 'Request too large' },\n id: null,\n });\n }\n return json(400, {\n jsonrpc: '2.0',\n error: { code: -32700, message: 'Parse error' },\n id: null,\n });\n }\n\n const ctx = contextForRequest(options.baseContext, {\n accessToken: auth.token,\n refreshToken: '',\n ...(auth.workspaceId ? { workspaceId: auth.workspaceId } : {}),\n });\n\n if (options.preflight && containsInitialize(body)) {\n let accepted: boolean;\n try {\n accepted = await options.preflight(ctx, auth);\n } catch (error) {\n logger.error('Hosted MCP preflight failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n return json(503, {\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Platform temporarily unavailable' },\n id: null,\n });\n }\n if (!accepted) return unauthorized('invalid', 'token no longer accepted');\n }\n\n const server = options.createServer(ctx, auth);\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined,\n enableJsonResponse: true,\n });\n try {\n await server.connect(transport);\n return await transport.handleRequest(request, { parsedBody: body });\n } finally {\n await server.close().catch(() => undefined);\n }\n };\n\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const origin = request.headers.get('origin');\n const method = request.method.toUpperCase();\n\n if (url.pathname === '/health' && method === 'GET') {\n return json(200, {\n status: 'healthy',\n server: options.baseContext.serverName,\n version: options.baseContext.serverVersion,\n });\n }\n\n if (\n url.pathname === '/.well-known/oauth-protected-resource' ||\n url.pathname === `/.well-known/oauth-protected-resource${resourcePath}`\n ) {\n if (method === 'OPTIONS') return withCors(new Response(null, { status: 204 }), origin);\n if (method !== 'GET')\n return withCors(json(405, { error: 'method not allowed' }, { Allow: 'GET' }), origin);\n return withCors(\n json(200, resourceMetadata, { 'Cache-Control': 'public, max-age=300' }),\n origin,\n );\n }\n\n if (url.pathname !== resourcePath) {\n return json(404, { error: 'not found' });\n }\n\n // MCP spec: servers must validate Origin to prevent DNS rebinding. Server\n // side clients (Claude, ChatGPT) send none; browser tools must be listed.\n if (origin && !allowedOrigins.has(origin)) {\n return json(403, {\n jsonrpc: '2.0',\n error: { code: -32000, message: 'Origin not allowed' },\n id: null,\n });\n }\n\n if (method === 'OPTIONS') return withCors(new Response(null, { status: 204 }), origin);\n if (method !== 'POST') {\n // Stateless: no server-initiated stream (GET) and no session to end (DELETE).\n return withCors(\n json(\n 405,\n { jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed' }, id: null },\n { Allow: 'POST, OPTIONS' },\n ),\n origin,\n );\n }\n\n try {\n return withCors(await handleMcpPost(request), origin);\n } catch (error) {\n logger.error('Hosted MCP request failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n return withCors(\n json(500, {\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n }),\n origin,\n );\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,eAAsB,iBACpB,QACA,KACA,QAAsB,CAAC,GACR;CACf,IAAI,OAAO,KAAK,4CAA4C;EAC1D,MAAM,IAAI;EACV,SAAS,IAAI;CACf,CAAC;CAED,MAAM,YAAY,IAAI,qBAAqB;CAC3C,MAAM,OAAO,QAAQ,SAAS;CAE9B,IAAI,OAAO,KAAK,0BAA0B;AAC5C;;;AClBA,MAAM,qBACJ;AAEF,SAAgB,iBAAiB,SAAkD;CACjF,IAAI,MAAM,QAAQ,OAAO,GAAG,OAAO;CAEnC,MAAM,QAAQ,SAAS,KAAK;CAC5B,IAAI,CAAC,SAAS,UAAU,KACtB,OAAO,CAAC,oBAAoB,kBAAkB;CAGhD,OAAO,MACJ,MAAM,GAAG,CAAC,CACV,KAAK,WAAW,OAAO,KAAK,CAAC,CAAC,CAC9B,OAAO,OAAO;AACnB;AAEA,SAAgB,oBAAoB,KAAc,QAAyB;CACzE,OAAO,IAAI,QAAQ,kBAAkB,UAAU,YAAY,IAAI,QAAQ,iBAAiB;AAC1F;AAEA,SAAgB,yBACd,KACA,KACA,QACS;CACT,IAAI,CAAC,QAAQ;EACX,IAAI,OAAO,GAAG,CAAC,CAAC,KAAK,EAAE,OAAO,6CAA6C,CAAC;EAC5E,OAAO;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