@agent-deck/backend 1.11.9 → 2.1.0
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/.tsbuildinfo +1 -1
- package/dist/audit/store.d.ts +43 -0
- package/dist/audit/store.d.ts.map +1 -0
- package/dist/audit/store.js +128 -0
- package/dist/audit/store.js.map +1 -0
- package/dist/auth/client-grants.d.ts +2 -2
- package/dist/auth/client-grants.d.ts.map +1 -1
- package/dist/auth/client-grants.js +0 -1
- package/dist/auth/client-grants.js.map +1 -1
- package/dist/auth/hosted-mode.d.ts +16 -0
- package/dist/auth/hosted-mode.d.ts.map +1 -0
- package/dist/auth/hosted-mode.js +136 -0
- package/dist/auth/hosted-mode.js.map +1 -0
- package/dist/auth/owner-auth.d.ts +24 -0
- package/dist/auth/owner-auth.d.ts.map +1 -0
- package/dist/auth/owner-auth.js +68 -0
- package/dist/auth/owner-auth.js.map +1 -0
- package/dist/auth/request-limiter.d.ts +17 -0
- package/dist/auth/request-limiter.d.ts.map +1 -0
- package/dist/auth/request-limiter.js +47 -0
- package/dist/auth/request-limiter.js.map +1 -0
- package/dist/cli-runtime.d.ts +2 -2
- package/dist/container-entrypoint.d.ts +2 -0
- package/dist/container-entrypoint.d.ts.map +1 -0
- package/dist/container-entrypoint.js +52 -0
- package/dist/container-entrypoint.js.map +1 -0
- package/dist/export-import/export-bundle.d.ts +2 -2
- package/dist/export-import/export-bundle.d.ts.map +1 -1
- package/dist/export-import/export-bundle.js +4 -2
- package/dist/export-import/export-bundle.js.map +1 -1
- package/dist/export-import/import-bundle.d.ts.map +1 -1
- package/dist/export-import/import-bundle.js +15 -3
- package/dist/export-import/import-bundle.js.map +1 -1
- package/dist/index.js +18 -15
- package/dist/index.js.map +1 -1
- package/dist/lib/destination-guard.d.ts +32 -0
- package/dist/lib/destination-guard.d.ts.map +1 -0
- package/dist/lib/destination-guard.js +238 -0
- package/dist/lib/destination-guard.js.map +1 -0
- package/dist/lib/fatal.d.ts +4 -4
- package/dist/lib/fatal.d.ts.map +1 -1
- package/dist/lib/fatal.js +36 -16
- package/dist/lib/fatal.js.map +1 -1
- package/dist/lib/graceful-shutdown.d.ts +26 -0
- package/dist/lib/graceful-shutdown.d.ts.map +1 -0
- package/dist/lib/graceful-shutdown.js +92 -0
- package/dist/lib/graceful-shutdown.js.map +1 -0
- package/dist/lib/mcp-oauth-discovery.d.ts.map +1 -1
- package/dist/lib/mcp-oauth-discovery.js +9 -4
- package/dist/lib/mcp-oauth-discovery.js.map +1 -1
- package/dist/lib/structured-console.d.ts +3 -0
- package/dist/lib/structured-console.d.ts.map +1 -0
- package/dist/lib/structured-console.js +29 -0
- package/dist/lib/structured-console.js.map +1 -0
- package/dist/mcp-index.js +2 -14
- package/dist/mcp-index.js.map +1 -1
- package/dist/mcp-server.d.ts +164 -3
- package/dist/mcp-server.d.ts.map +1 -1
- package/dist/mcp-server.js +496 -42
- package/dist/mcp-server.js.map +1 -1
- package/dist/mcp-tools/elicitation.d.ts +13 -4
- package/dist/mcp-tools/elicitation.d.ts.map +1 -1
- package/dist/mcp-tools/elicitation.js +34 -14
- package/dist/mcp-tools/elicitation.js.map +1 -1
- package/dist/mcp-tools/register.d.ts.map +1 -1
- package/dist/mcp-tools/register.js +59 -5
- package/dist/mcp-tools/register.js.map +1 -1
- package/dist/models/database.d.ts.map +1 -1
- package/dist/models/database.js +18 -5
- package/dist/models/database.js.map +1 -1
- package/dist/routes/agent-grants.d.ts.map +1 -1
- package/dist/routes/agent-grants.js +19 -3
- package/dist/routes/agent-grants.js.map +1 -1
- package/dist/routes/audit.d.ts +5 -0
- package/dist/routes/audit.d.ts.map +1 -0
- package/dist/routes/audit.js +33 -0
- package/dist/routes/audit.js.map +1 -0
- package/dist/routes/decks.d.ts.map +1 -1
- package/dist/routes/decks.js +27 -0
- package/dist/routes/decks.js.map +1 -1
- package/dist/routes/mcp.d.ts.map +1 -1
- package/dist/routes/mcp.js +5 -4
- package/dist/routes/mcp.js.map +1 -1
- package/dist/routes/trusted-session.d.ts +2 -0
- package/dist/routes/trusted-session.d.ts.map +1 -1
- package/dist/routes/trusted-session.js +132 -0
- package/dist/routes/trusted-session.js.map +1 -1
- package/dist/server/cors-origins.d.ts.map +1 -1
- package/dist/server/cors-origins.js +19 -0
- package/dist/server/cors-origins.js.map +1 -1
- package/dist/server/degraded.d.ts +15 -0
- package/dist/server/degraded.d.ts.map +1 -0
- package/dist/server/degraded.js +55 -0
- package/dist/server/degraded.js.map +1 -0
- package/dist/server/graceful-shutdown.fixture.d.ts +2 -0
- package/dist/server/graceful-shutdown.fixture.d.ts.map +1 -0
- package/dist/server/graceful-shutdown.fixture.js +52 -0
- package/dist/server/graceful-shutdown.fixture.js.map +1 -0
- package/dist/server/health.d.ts +21 -0
- package/dist/server/health.d.ts.map +1 -0
- package/dist/server/health.js +65 -0
- package/dist/server/health.js.map +1 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +49 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/icon-resolver.d.ts.map +1 -1
- package/dist/services/icon-resolver.js +2 -1
- package/dist/services/icon-resolver.js.map +1 -1
- package/dist/services/mcp-client-manager.d.ts.map +1 -1
- package/dist/services/mcp-client-manager.js +3 -0
- package/dist/services/mcp-client-manager.js.map +1 -1
- package/dist/services/mcp-discovery-service.d.ts.map +1 -1
- package/dist/services/mcp-discovery-service.js +2 -1
- package/dist/services/mcp-discovery-service.js.map +1 -1
- package/dist/services/oauth-manager.d.ts.map +1 -1
- package/dist/services/oauth-manager.js +12 -7
- package/dist/services/oauth-manager.js.map +1 -1
- package/dist/services/service-manager.d.ts.map +1 -1
- package/dist/services/service-manager.js +15 -4
- package/dist/services/service-manager.js.map +1 -1
- package/dist/store/atomic-write.d.ts.map +1 -1
- package/dist/store/atomic-write.js +44 -3
- package/dist/store/atomic-write.js.map +1 -1
- package/dist/store/deck-codec.d.ts +9 -0
- package/dist/store/deck-codec.d.ts.map +1 -1
- package/dist/store/deck-codec.js +64 -1
- package/dist/store/deck-codec.js.map +1 -1
- package/dist/store/deck-file.d.ts +3 -3
- package/dist/store/deck-file.d.ts.map +1 -1
- package/dist/store/deck-file.js +4 -3
- package/dist/store/deck-file.js.map +1 -1
- package/dist/store/index.d.ts +1 -0
- package/dist/store/index.d.ts.map +1 -1
- package/dist/store/index.js +1 -0
- package/dist/store/index.js.map +1 -1
- package/dist/store/migrate-v1-to-v2.d.ts +22 -0
- package/dist/store/migrate-v1-to-v2.d.ts.map +1 -0
- package/dist/store/migrate-v1-to-v2.js +167 -0
- package/dist/store/migrate-v1-to-v2.js.map +1 -0
- package/dist/store/migrate.js +2 -2
- package/dist/store/migrate.js.map +1 -1
- package/dist/store/reindex.d.ts.map +1 -1
- package/dist/store/reindex.js +16 -6
- package/dist/store/reindex.js.map +1 -1
- package/dist/store/startup.d.ts.map +1 -1
- package/dist/store/startup.js +13 -0
- package/dist/store/startup.js.map +1 -1
- package/dist/store/writer.d.ts.map +1 -1
- package/dist/store/writer.js +7 -3
- package/dist/store/writer.js.map +1 -1
- package/dist/trusted-session/route-policy-registry.d.ts.map +1 -1
- package/dist/trusted-session/route-policy-registry.js +9 -1
- package/dist/trusted-session/route-policy-registry.js.map +1 -1
- package/dist/trusted-session/store.d.ts +10 -2
- package/dist/trusted-session/store.d.ts.map +1 -1
- package/dist/trusted-session/store.js +41 -13
- package/dist/trusted-session/store.js.map +1 -1
- package/dist/vault/secret-store.d.ts +8 -0
- package/dist/vault/secret-store.d.ts.map +1 -1
- package/dist/vault/secret-store.js +17 -1
- package/dist/vault/secret-store.js.map +1 -1
- package/package.json +2 -2
- package/static-ui/assets/index-DMqzTrRe.css +1 -0
- package/static-ui/assets/index-ynIby2JK.js +251 -0
- package/static-ui/index.html +2 -2
- package/static-ui/assets/index-CQf3Vouc.css +0 -1
- package/static-ui/assets/index-sENM6Awe.js +0 -235
package/dist/mcp-server.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.AgentDeckMCPServer = exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR = exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS = exports.MCP_REQUIRE_BEARER_ENV_VAR = void 0;
|
|
6
|
+
exports.AgentDeckMCPServer = exports.DEFAULT_UNREGISTER_CONCURRENCY = exports.DEFAULT_TRANSPORT_SWEEP_INTERVAL_MS = exports.DEFAULT_TRANSPORT_IDLE_TTL_MS = exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR = exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS = exports.MCP_INITIALIZE_RATE_WINDOW_MS = exports.MCP_INITIALIZE_RATE_LIMIT = exports.MCP_REQUIRE_BEARER_ENV_VAR = void 0;
|
|
7
7
|
exports.isBearerGrantRequired = isBearerGrantRequired;
|
|
8
8
|
exports.resolveLiveTouchKeepAliveMs = resolveLiveTouchKeepAliveMs;
|
|
9
9
|
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
@@ -25,6 +25,8 @@ const elicitation_1 = require("./mcp-tools/elicitation");
|
|
|
25
25
|
const profile_1 = require("./mcp-tools/profile");
|
|
26
26
|
const mcp_unassigned_1 = require("./mcp-unassigned");
|
|
27
27
|
const stub_sync_1 = require("./playbooks/stub-sync");
|
|
28
|
+
const request_limiter_1 = require("./auth/request-limiter");
|
|
29
|
+
const store_1 = require("./audit/store");
|
|
28
30
|
function readWorkspaceRootHeader(req) {
|
|
29
31
|
const raw = req.headers[shared_1.AGENT_DECK_WORKSPACE_HEADER];
|
|
30
32
|
const value = typeof raw === 'string' ? raw.trim() : '';
|
|
@@ -46,6 +48,16 @@ function readCorrelationIdHeader(req) {
|
|
|
46
48
|
const value = typeof raw === 'string' ? raw.trim() : '';
|
|
47
49
|
return value || undefined;
|
|
48
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* NOT-191: whether the request comes from a heartbeat-capable bridge. The
|
|
53
|
+
* marker rides every request the new bridge sends (handshake, tool calls,
|
|
54
|
+
* pulses, stream, close); legacy clients never send it, so absence means
|
|
55
|
+
* "unknown/legacy" and keeps the server-owned keep-alive touch.
|
|
56
|
+
*/
|
|
57
|
+
function hasBridgeLivenessHeader(req) {
|
|
58
|
+
const raw = req.headers[shared_1.AGENT_DECK_BRIDGE_LIVENESS_HEADER];
|
|
59
|
+
return typeof raw === 'string' && raw.trim() === shared_1.AGENT_DECK_BRIDGE_LIVENESS_V1;
|
|
60
|
+
}
|
|
49
61
|
/**
|
|
50
62
|
* NOT-318: hosted-mode flag. When `AGENT_DECK_MCP_REQUIRE_BEARER=1`, every
|
|
51
63
|
* `/mcp` request requires a valid per-agent grant secret, regardless of
|
|
@@ -56,6 +68,8 @@ function readCorrelationIdHeader(req) {
|
|
|
56
68
|
* bearer-free with zero config change.
|
|
57
69
|
*/
|
|
58
70
|
exports.MCP_REQUIRE_BEARER_ENV_VAR = 'AGENT_DECK_MCP_REQUIRE_BEARER';
|
|
71
|
+
exports.MCP_INITIALIZE_RATE_LIMIT = 30;
|
|
72
|
+
exports.MCP_INITIALIZE_RATE_WINDOW_MS = 60_000;
|
|
59
73
|
function isBearerGrantRequired(raw = process.env[exports.MCP_REQUIRE_BEARER_ENV_VAR]) {
|
|
60
74
|
return raw === '1' || raw?.trim().toLowerCase() === 'true';
|
|
61
75
|
}
|
|
@@ -86,6 +100,24 @@ function readBearerToken(req) {
|
|
|
86
100
|
*/
|
|
87
101
|
exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS = 5 * 60_000;
|
|
88
102
|
exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR = 'AGENT_DECK_MCP_LIVE_TOUCH_KEEPALIVE_MS';
|
|
103
|
+
/**
|
|
104
|
+
* NOT-191: idle retention for MCP transport sessions. A session with no
|
|
105
|
+
* client traffic — no tool calls, no heartbeat pulse — is closed and fully
|
|
106
|
+
* cleaned once it has been idle this long. Twenty-four hours keeps a laptop
|
|
107
|
+
* asleep overnight recoverable (the bridge re-initializes on wake) while
|
|
108
|
+
* still reclaiming transports abandoned by crashed hosts. Kept separate
|
|
109
|
+
* from the 30-minute live-display lease on purpose: the display is what the
|
|
110
|
+
* status line reads, the transport is just retained state.
|
|
111
|
+
*/
|
|
112
|
+
exports.DEFAULT_TRANSPORT_IDLE_TTL_MS = 24 * 60 * 60_000;
|
|
113
|
+
/** Cadence of the idle-transport sweep. */
|
|
114
|
+
exports.DEFAULT_TRANSPORT_SWEEP_INTERVAL_MS = 60_000;
|
|
115
|
+
/**
|
|
116
|
+
* NOT-191: bound on concurrent live-display unregisters, shared by the idle
|
|
117
|
+
* sweep and server shutdown so a mass expiry cannot fan out into hundreds of
|
|
118
|
+
* simultaneous backend calls.
|
|
119
|
+
*/
|
|
120
|
+
exports.DEFAULT_UNREGISTER_CONCURRENCY = 8;
|
|
89
121
|
function resolveLiveTouchKeepAliveMs(raw, staleMs) {
|
|
90
122
|
const fallback = staleMs > 0
|
|
91
123
|
? Math.max(1, Math.min(exports.DEFAULT_LIVE_TOUCH_KEEPALIVE_MS, Math.floor(staleMs / 3)))
|
|
@@ -118,8 +150,51 @@ class AgentDeckMCPServer {
|
|
|
118
150
|
lastTouchAtMs = new Map();
|
|
119
151
|
/** NOT-309: keep-alive timer proving idle-but-connected sessions still live. */
|
|
120
152
|
liveTouchKeepAliveTimer = null;
|
|
121
|
-
/**
|
|
122
|
-
|
|
153
|
+
/**
|
|
154
|
+
* NOT-191: session cleanups in flight, keyed by MCP session id. Doubles as
|
|
155
|
+
* the re-entrancy guard — `transport.onclose` and the sweep/stop paths all
|
|
156
|
+
* funnel through `startCleanupSession`, and a second call for the same id
|
|
157
|
+
* joins the first instead of unregistering twice. Resolves to whether the
|
|
158
|
+
* live-display unregister succeeded (for aggregate batch summaries).
|
|
159
|
+
*/
|
|
160
|
+
cleanupTasks = new Map();
|
|
161
|
+
/** NOT-191: clock for activity/TTL bookkeeping (tests inject a fake clock). */
|
|
162
|
+
nowFn;
|
|
163
|
+
/** NOT-191: idle bound for transport retention (24h default; `0` disables). */
|
|
164
|
+
transportIdleTtlMs;
|
|
165
|
+
/** NOT-191: cadence of the idle-transport sweep (`0` disables the timer). */
|
|
166
|
+
transportSweepIntervalMs;
|
|
167
|
+
/** NOT-191: bound on concurrent live-display unregisters (sweep + shutdown). */
|
|
168
|
+
unregisterConcurrency;
|
|
169
|
+
/** NOT-191: bound on one live-display unregister (option or env override). */
|
|
170
|
+
unregisterTimeoutMsValue;
|
|
171
|
+
/** NOT-191: keep-alive override (tests); otherwise the env resolution wins. */
|
|
172
|
+
liveTouchKeepAliveMsOverride;
|
|
173
|
+
/**
|
|
174
|
+
* NOT-191: last real client traffic per session — tool calls, handshakes,
|
|
175
|
+
* stream connects, heartbeat pulses. Server-generated keep-alive touches
|
|
176
|
+
* never write here, so they cannot extend transport retention.
|
|
177
|
+
*/
|
|
178
|
+
lastClientActivityAtMs = new Map();
|
|
179
|
+
/** NOT-191: sessions whose bridge owns the heartbeat (no server touch needed). */
|
|
180
|
+
heartbeatCapableSessions = new Set();
|
|
181
|
+
/** NOT-191: POST requests currently inside `transport.handleRequest` per session. */
|
|
182
|
+
inFlightRequests = new Map();
|
|
183
|
+
/**
|
|
184
|
+
* NOT-191: sessions whose `DELETE` arrived while a host request was in
|
|
185
|
+
* flight. The close is deferred — never executed under running work — and
|
|
186
|
+
* runs when the last in-flight request lands or the next sweep finds the
|
|
187
|
+
* session idle.
|
|
188
|
+
*/
|
|
189
|
+
pendingSessionClose = new Set();
|
|
190
|
+
/** NOT-191: idle-transport sweep timer. */
|
|
191
|
+
transportSweepTimer = null;
|
|
192
|
+
/** NOT-191: re-entrancy guard so a slow sweep never overlaps the next tick. */
|
|
193
|
+
transportSweepRunning = false;
|
|
194
|
+
/** NOT-191: unregister semaphore state; `unregisterPeak` is read by tests. */
|
|
195
|
+
unregisterActive = 0;
|
|
196
|
+
unregisterPeak = 0;
|
|
197
|
+
unregisterWaiters = [];
|
|
123
198
|
/** Changes on every process start — how a client detects it outlived the server. */
|
|
124
199
|
instanceId = (0, node_crypto_1.randomUUID)();
|
|
125
200
|
startedAt = new Date().toISOString();
|
|
@@ -146,14 +221,30 @@ class AgentDeckMCPServer {
|
|
|
146
221
|
grantStoreOverride;
|
|
147
222
|
/** Lazily opened grant store for hosted mode (shared backend database file). */
|
|
148
223
|
grantStoreCache = null;
|
|
224
|
+
auditStoreOverride;
|
|
225
|
+
auditStoreCache = null;
|
|
226
|
+
sharedSecurityDb = null;
|
|
227
|
+
initializeLimiter;
|
|
149
228
|
constructor(port = 3001, backendUrl = 'http://localhost:8000', toolProfile, host = '127.0.0.1', options) {
|
|
150
229
|
this.port = port;
|
|
151
230
|
this.backendUrl = backendUrl;
|
|
152
231
|
this.toolProfile = toolProfile ?? (0, profile_1.resolveMcpToolProfile)();
|
|
153
232
|
this.host = host;
|
|
154
233
|
this.grantStoreOverride = options?.grantStore;
|
|
234
|
+
this.auditStoreOverride = options?.auditStore;
|
|
235
|
+
this.initializeLimiter = new request_limiter_1.RequestLimiter(exports.MCP_INITIALIZE_RATE_WINDOW_MS, options?.now);
|
|
236
|
+
this.nowFn = options?.now ?? Date.now;
|
|
237
|
+
this.transportIdleTtlMs = options?.transportIdleTtlMs ?? exports.DEFAULT_TRANSPORT_IDLE_TTL_MS;
|
|
238
|
+
this.transportSweepIntervalMs =
|
|
239
|
+
options?.transportSweepIntervalMs ?? exports.DEFAULT_TRANSPORT_SWEEP_INTERVAL_MS;
|
|
240
|
+
this.unregisterConcurrency = options?.unregisterConcurrency ?? exports.DEFAULT_UNREGISTER_CONCURRENCY;
|
|
241
|
+
this.unregisterTimeoutMsValue =
|
|
242
|
+
options?.unregisterTimeoutMs ?? AgentDeckMCPServer.unregisterTimeoutMs();
|
|
243
|
+
this.liveTouchKeepAliveMsOverride = options?.liveTouchKeepAliveMs;
|
|
155
244
|
this.app = (0, express_1.default)();
|
|
156
|
-
this.app.use(
|
|
245
|
+
this.app.use(process.env.AGENT_DECK_HOSTED_MODE === '1'
|
|
246
|
+
? express_1.default.json({ limit: 1024 * 1024 })
|
|
247
|
+
: express_1.default.json());
|
|
157
248
|
this.setupRoutes();
|
|
158
249
|
this.sessionBinding = new mcp_session_binding_1.McpSessionBindingStore({
|
|
159
250
|
workspace: process.env.AGENT_DECK_WORKSPACE,
|
|
@@ -175,13 +266,29 @@ class AgentDeckMCPServer {
|
|
|
175
266
|
}
|
|
176
267
|
try {
|
|
177
268
|
const dbPath = process.env.AGENT_DECK_DB_PATH?.trim() || (0, paths_1.resolveDatabasePath)();
|
|
178
|
-
this.
|
|
269
|
+
this.sharedSecurityDb ??= new better_sqlite3_1.default(dbPath);
|
|
270
|
+
this.grantStoreCache = new client_grants_1.ClientGrantStore(this.sharedSecurityDb);
|
|
179
271
|
return this.grantStoreCache;
|
|
180
272
|
}
|
|
181
273
|
catch {
|
|
182
274
|
return null;
|
|
183
275
|
}
|
|
184
276
|
}
|
|
277
|
+
getAuditStore() {
|
|
278
|
+
if (this.auditStoreOverride !== undefined)
|
|
279
|
+
return this.auditStoreOverride;
|
|
280
|
+
if (this.auditStoreCache)
|
|
281
|
+
return this.auditStoreCache;
|
|
282
|
+
try {
|
|
283
|
+
const dbPath = process.env.AGENT_DECK_DB_PATH?.trim() || (0, paths_1.resolveDatabasePath)();
|
|
284
|
+
this.sharedSecurityDb ??= new better_sqlite3_1.default(dbPath);
|
|
285
|
+
this.auditStoreCache = new store_1.AuditStore(this.sharedSecurityDb);
|
|
286
|
+
return this.auditStoreCache;
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
185
292
|
/**
|
|
186
293
|
* NOT-318: authenticate one bearer token to a grant principal. Every
|
|
187
294
|
* failure mode (missing store, malformed, unknown id, secret mismatch,
|
|
@@ -206,12 +313,19 @@ class AgentDeckMCPServer {
|
|
|
206
313
|
* One McpServer per transport session. Tools/resources close over `sessionId`
|
|
207
314
|
* so concurrent requests cannot steal another session's backend authority.
|
|
208
315
|
*/
|
|
209
|
-
createMcpServer(sessionId) {
|
|
316
|
+
async createMcpServer(sessionId) {
|
|
210
317
|
const unassigned = this.sessionBinding.isUnassigned(sessionId);
|
|
318
|
+
let instructions;
|
|
319
|
+
if (unassigned) {
|
|
320
|
+
instructions = mcp_unassigned_1.UNASSIGNED_DECK_MESSAGE;
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
instructions = await this.resolveInitializeInstructions(sessionId);
|
|
324
|
+
}
|
|
211
325
|
this.mcpServerForRegistration = new mcp_js_1.McpServer({
|
|
212
326
|
name: "agent-deck-server",
|
|
213
327
|
version: (0, version_1.getAgentDeckVersion)(),
|
|
214
|
-
},
|
|
328
|
+
}, instructions ? { instructions } : undefined);
|
|
215
329
|
this.setupTools(sessionId);
|
|
216
330
|
if (!unassigned) {
|
|
217
331
|
this.setupResources(sessionId);
|
|
@@ -220,6 +334,30 @@ class AgentDeckMCPServer {
|
|
|
220
334
|
this.mcpServerForRegistration = undefined;
|
|
221
335
|
return server;
|
|
222
336
|
}
|
|
337
|
+
/**
|
|
338
|
+
* NOT-375: initialize-time server instructions for an assigned deck.
|
|
339
|
+
* The bound deck's non-empty operating instructions ride the initialize
|
|
340
|
+
* response as a bootstrap hint where the SDK/host surfaces them; empty
|
|
341
|
+
* instructions omit the field. This value is frozen at connect time and
|
|
342
|
+
* never updates after a hot deck switch — `get_session_context` is the
|
|
343
|
+
* authoritative live read. Any failure here falls back to no instructions
|
|
344
|
+
* rather than failing the handshake; the bootstrap tool call surfaces the
|
|
345
|
+
* underlying deck error instead.
|
|
346
|
+
*/
|
|
347
|
+
async resolveInitializeInstructions(sessionId) {
|
|
348
|
+
const binding = this.sessionBinding.getBinding(sessionId);
|
|
349
|
+
if (!binding.deckId && !binding.runtimeSessionId) {
|
|
350
|
+
return undefined;
|
|
351
|
+
}
|
|
352
|
+
try {
|
|
353
|
+
const deck = await this.callBackendAPI('/api/scope/deck', {}, sessionId);
|
|
354
|
+
const value = deck?.operatingInstructions;
|
|
355
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
return undefined;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
223
361
|
async fetchDeck(deckId, sessionId) {
|
|
224
362
|
const deck = await fetch(`${this.backendUrl}/api/decks/${deckId}`, {
|
|
225
363
|
headers: this.sessionBinding.getAgentHeaders(sessionId),
|
|
@@ -277,6 +415,25 @@ class AgentDeckMCPServer {
|
|
|
277
415
|
}
|
|
278
416
|
}
|
|
279
417
|
static TOUCH_DEBOUNCE_MS = 5_000;
|
|
418
|
+
/** NOT-191: injected clock for activity/TTL bookkeeping. */
|
|
419
|
+
nowMs() {
|
|
420
|
+
return this.nowFn();
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* NOT-191: record real client traffic — a tool call, handshake, stream
|
|
424
|
+
* connect, or heartbeat pulse — as transport activity, and adopt the
|
|
425
|
+
* bridge-liveness capability whenever the marker is present. Called only
|
|
426
|
+
* for authenticated requests on a live session; server-generated
|
|
427
|
+
* keep-alive touches never come through here, so they cannot extend the
|
|
428
|
+
* transport idle TTL. A client pulse also refreshes the display lease via
|
|
429
|
+
* the per-request `touchLiveDisplay` at the same call sites.
|
|
430
|
+
*/
|
|
431
|
+
noteClientActivity(sessionId, req) {
|
|
432
|
+
this.lastClientActivityAtMs.set(sessionId, this.nowMs());
|
|
433
|
+
if (hasBridgeLivenessHeader(req)) {
|
|
434
|
+
this.heartbeatCapableSessions.add(sessionId);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
280
437
|
/**
|
|
281
438
|
* Fire-and-forget lastActivityAt bump; only for sessions this process
|
|
282
439
|
* registered (badge-holding). `force` bypasses the per-request debounce —
|
|
@@ -294,7 +451,7 @@ class AgentDeckMCPServer {
|
|
|
294
451
|
if (!this.badgeBySession.has(sessionId)) {
|
|
295
452
|
return;
|
|
296
453
|
}
|
|
297
|
-
const now =
|
|
454
|
+
const now = this.nowMs();
|
|
298
455
|
if (!force &&
|
|
299
456
|
now - (this.lastTouchAtMs.get(sessionId) ?? 0) < AgentDeckMCPServer.TOUCH_DEBOUNCE_MS) {
|
|
300
457
|
return;
|
|
@@ -303,7 +460,7 @@ class AgentDeckMCPServer {
|
|
|
303
460
|
void this.callBackendAPI(`/api/scope/live-display/${encodeURIComponent(sessionId)}/touch`, {
|
|
304
461
|
method: 'POST',
|
|
305
462
|
headers: { 'Content-Type': 'application/json' },
|
|
306
|
-
body: JSON.stringify({ at: new Date().toISOString() }),
|
|
463
|
+
body: JSON.stringify({ at: new Date(now).toISOString() }),
|
|
307
464
|
}, sessionId)
|
|
308
465
|
.then((result) => {
|
|
309
466
|
// Guard against the close race: a keep-alive touch in flight when
|
|
@@ -333,16 +490,25 @@ class AgentDeckMCPServer {
|
|
|
333
490
|
* no tool calls. Only badge-holding (registered) sessions are touched; the
|
|
334
491
|
* backend ignores touches for sessions it never saw, so unassigned or
|
|
335
492
|
* half-initialized sessions are harmless no-ops by construction.
|
|
493
|
+
*
|
|
494
|
+
* NOT-191: heartbeat-capable sessions are skipped — their bridge owns the
|
|
495
|
+
* pulse now, and a server-generated touch here is what used to defeat the
|
|
496
|
+
* stale sweep for abandoned bridges. Legacy/unknown sessions keep the
|
|
497
|
+
* compatibility touch, but it never counts as transport activity.
|
|
336
498
|
*/
|
|
337
499
|
touchAllLiveDisplays() {
|
|
338
500
|
for (const sessionId of this.sessions.keys()) {
|
|
501
|
+
if (this.heartbeatCapableSessions.has(sessionId)) {
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
339
504
|
this.touchLiveDisplay(sessionId, true);
|
|
340
505
|
}
|
|
341
506
|
}
|
|
342
507
|
startLiveDisplayKeepAlive() {
|
|
343
508
|
this.stopLiveDisplayKeepAlive();
|
|
344
509
|
const staleMs = (0, live_display_registry_1.resolveLiveDisplayStaleMs)(process.env.LIVE_DISPLAY_STALE_MS);
|
|
345
|
-
const intervalMs =
|
|
510
|
+
const intervalMs = this.liveTouchKeepAliveMsOverride ??
|
|
511
|
+
resolveLiveTouchKeepAliveMs(process.env[exports.LIVE_TOUCH_KEEPALIVE_ENV_VAR], staleMs);
|
|
346
512
|
if (intervalMs <= 0) {
|
|
347
513
|
return;
|
|
348
514
|
}
|
|
@@ -358,20 +524,234 @@ class AgentDeckMCPServer {
|
|
|
358
524
|
this.liveTouchKeepAliveTimer = null;
|
|
359
525
|
}
|
|
360
526
|
}
|
|
361
|
-
|
|
527
|
+
/**
|
|
528
|
+
* NOT-191: one live-display unregister, bounded and silent. Returns whether
|
|
529
|
+
* it succeeded; failures aggregate into a single batch summary at the sweep
|
|
530
|
+
* and shutdown call sites instead of one stack trace per session. Runs
|
|
531
|
+
* while the session binding still resolves — `runCleanupSession` clears it
|
|
532
|
+
* only after this returns.
|
|
533
|
+
*/
|
|
534
|
+
async unregisterLiveDisplayQuiet(sessionId) {
|
|
362
535
|
const controller = new AbortController();
|
|
363
|
-
const timer = setTimeout(() => controller.abort(),
|
|
536
|
+
const timer = setTimeout(() => controller.abort(), this.unregisterTimeoutMsValue);
|
|
537
|
+
timer.unref?.();
|
|
364
538
|
try {
|
|
365
|
-
await this.callBackendAPI(`/api/scope/live-display/${encodeURIComponent(sessionId)}`, { method: 'DELETE', signal: controller.signal }, sessionId);
|
|
539
|
+
await this.callBackendAPI(`/api/scope/live-display/${encodeURIComponent(sessionId)}`, { method: 'DELETE', signal: controller.signal }, sessionId, { quiet: true });
|
|
540
|
+
return true;
|
|
366
541
|
}
|
|
367
542
|
catch {
|
|
368
|
-
// Best effort when MCP session closes (includes abort on hung backend).
|
|
543
|
+
// Best effort when an MCP session closes (includes abort on hung backend).
|
|
544
|
+
return false;
|
|
369
545
|
}
|
|
370
546
|
finally {
|
|
371
547
|
clearTimeout(timer);
|
|
372
548
|
}
|
|
373
549
|
}
|
|
374
|
-
|
|
550
|
+
/**
|
|
551
|
+
* NOT-191: run `fn` under the shared unregister semaphore so the idle
|
|
552
|
+
* sweep and server shutdown together never exceed the bound, however many
|
|
553
|
+
* sessions expire at once.
|
|
554
|
+
*/
|
|
555
|
+
async withUnregisterSlot(fn) {
|
|
556
|
+
const limit = Math.max(1, this.unregisterConcurrency);
|
|
557
|
+
while (this.unregisterActive >= limit) {
|
|
558
|
+
await new Promise((resolve) => {
|
|
559
|
+
this.unregisterWaiters.push(resolve);
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
this.unregisterActive += 1;
|
|
563
|
+
this.unregisterPeak = Math.max(this.unregisterPeak, this.unregisterActive);
|
|
564
|
+
try {
|
|
565
|
+
return await fn();
|
|
566
|
+
}
|
|
567
|
+
finally {
|
|
568
|
+
this.unregisterActive -= 1;
|
|
569
|
+
const next = this.unregisterWaiters.shift();
|
|
570
|
+
next?.();
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* NOT-191: one aggregate line for a batch of unregisters — attempted,
|
|
575
|
+
* succeeded, failed — logged only when something failed. A clean batch
|
|
576
|
+
* stays silent; a failing one never logs per-session stacks.
|
|
577
|
+
*/
|
|
578
|
+
logUnregisterSummary(reason, results) {
|
|
579
|
+
const failed = results.filter((ok) => !ok).length;
|
|
580
|
+
if (failed === 0) {
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
console.warn(`[agent-deck] live-display unregister (${reason}): ` +
|
|
584
|
+
`attempted=${results.length} succeeded=${results.length - failed} failed=${failed}`);
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* NOT-191 session cleanup. Every transport/session end funnels through
|
|
588
|
+
* here — `transport.onclose` (clean `DELETE`), the idle sweep, deferred
|
|
589
|
+
* closes, and server shutdown — so no path can strand part of a session's
|
|
590
|
+
* state. Removes the transport/server entry, unregisters the live display
|
|
591
|
+
* under the shared concurrency bound, then disconnects the trusted
|
|
592
|
+
* runtime session (revoking nothing reusable — the grant row stays valid
|
|
593
|
+
* for the next handshake), and finally clears the binding, badge, touch,
|
|
594
|
+
* activity, capability, and in-flight bookkeeping. The unregister runs
|
|
595
|
+
* before the disconnect because it authenticates with the runtime session
|
|
596
|
+
* the disconnect revokes. Idempotent per session id: a second call joins
|
|
597
|
+
* the first.
|
|
598
|
+
*/
|
|
599
|
+
startCleanupSession(sessionId, opts) {
|
|
600
|
+
const existing = this.cleanupTasks.get(sessionId);
|
|
601
|
+
if (existing) {
|
|
602
|
+
return existing;
|
|
603
|
+
}
|
|
604
|
+
if (this.closedSessionIds.has(sessionId)) {
|
|
605
|
+
return Promise.resolve(true);
|
|
606
|
+
}
|
|
607
|
+
const task = this.runCleanupSession(sessionId, opts);
|
|
608
|
+
this.cleanupTasks.set(sessionId, task);
|
|
609
|
+
const release = () => {
|
|
610
|
+
if (this.cleanupTasks.get(sessionId) === task) {
|
|
611
|
+
this.cleanupTasks.delete(sessionId);
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
void task.then(release, release);
|
|
615
|
+
return task;
|
|
616
|
+
}
|
|
617
|
+
async runCleanupSession(sessionId, opts) {
|
|
618
|
+
// Synchronous prefix — no awaits before the maps below are updated, so a
|
|
619
|
+
// request interleaving at any later await already sees the session gone.
|
|
620
|
+
const session = this.sessions.get(sessionId);
|
|
621
|
+
this.sessions.delete(sessionId);
|
|
622
|
+
this.rememberClosedSession(sessionId);
|
|
623
|
+
this.pendingSessionClose.delete(sessionId);
|
|
624
|
+
this.lastClientActivityAtMs.delete(sessionId);
|
|
625
|
+
this.heartbeatCapableSessions.delete(sessionId);
|
|
626
|
+
this.inFlightRequests.delete(sessionId);
|
|
627
|
+
if (opts.closeTransport && session) {
|
|
628
|
+
try {
|
|
629
|
+
// The transport's `onclose` re-enters `startCleanupSession`, which
|
|
630
|
+
// joins this run via `cleanupTasks` instead of cleaning twice.
|
|
631
|
+
await session.transport.close();
|
|
632
|
+
}
|
|
633
|
+
catch {
|
|
634
|
+
// Best effort — the maps above are already consistent.
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
// Best effort, before the binding is cleared: the live-display DELETE
|
|
638
|
+
// authenticates through the runtime session header, and the disconnect
|
|
639
|
+
// below revokes that session — so the unregister must run first, while
|
|
640
|
+
// the session is still valid. (Disconnect is a public endpoint keyed by
|
|
641
|
+
// mcpSessionId, so it needs no valid session of its own.)
|
|
642
|
+
let unregistered;
|
|
643
|
+
try {
|
|
644
|
+
unregistered = await this.withUnregisterSlot(() => this.unregisterLiveDisplayQuiet(sessionId));
|
|
645
|
+
}
|
|
646
|
+
catch {
|
|
647
|
+
unregistered = false;
|
|
648
|
+
}
|
|
649
|
+
try {
|
|
650
|
+
await this.disconnectTrustedSession(sessionId);
|
|
651
|
+
}
|
|
652
|
+
catch {
|
|
653
|
+
// Best-effort cleanup.
|
|
654
|
+
}
|
|
655
|
+
this.sessionBinding.clearSession(sessionId);
|
|
656
|
+
this.badgeBySession.delete(sessionId);
|
|
657
|
+
this.lastTouchAtMs.delete(sessionId);
|
|
658
|
+
return unregistered;
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* NOT-191: close every session that is idle past the transport TTL or has
|
|
662
|
+
* a deferred close pending — unless a host request is in flight, in which
|
|
663
|
+
* case it waits for the next sweep. Unregisters run concurrently under the
|
|
664
|
+
* shared bound and their failures collapse into one summary line.
|
|
665
|
+
*/
|
|
666
|
+
async sweepIdleTransports() {
|
|
667
|
+
if (this.transportSweepRunning) {
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
this.transportSweepRunning = true;
|
|
671
|
+
try {
|
|
672
|
+
const now = this.nowMs();
|
|
673
|
+
const candidates = [];
|
|
674
|
+
for (const sessionId of this.sessions.keys()) {
|
|
675
|
+
if (this.cleanupTasks.has(sessionId) || this.closedSessionIds.has(sessionId)) {
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
if ((this.inFlightRequests.get(sessionId) ?? 0) > 0) {
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
if (this.pendingSessionClose.has(sessionId)) {
|
|
682
|
+
candidates.push(sessionId);
|
|
683
|
+
continue;
|
|
684
|
+
}
|
|
685
|
+
if (this.transportIdleTtlMs <= 0) {
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
const lastActivity = this.lastClientActivityAtMs.get(sessionId);
|
|
689
|
+
if (lastActivity === undefined) {
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
// `>=`: a session idle for exactly the TTL is already past retention.
|
|
693
|
+
if (now - lastActivity >= this.transportIdleTtlMs) {
|
|
694
|
+
candidates.push(sessionId);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
if (candidates.length === 0) {
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
const results = await Promise.all(candidates.map((sessionId) => this.startCleanupSession(sessionId, { closeTransport: true })));
|
|
701
|
+
this.logUnregisterSummary('transport-sweep', results);
|
|
702
|
+
}
|
|
703
|
+
finally {
|
|
704
|
+
this.transportSweepRunning = false;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
startTransportSweep() {
|
|
708
|
+
this.stopTransportSweep();
|
|
709
|
+
if (this.transportSweepIntervalMs <= 0) {
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
const timer = setInterval(() => {
|
|
713
|
+
void this.sweepIdleTransports().catch(() => { });
|
|
714
|
+
}, this.transportSweepIntervalMs);
|
|
715
|
+
timer.unref?.();
|
|
716
|
+
this.transportSweepTimer = timer;
|
|
717
|
+
}
|
|
718
|
+
stopTransportSweep() {
|
|
719
|
+
if (this.transportSweepTimer) {
|
|
720
|
+
clearInterval(this.transportSweepTimer);
|
|
721
|
+
this.transportSweepTimer = null;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* NOT-191: run one POST inside the per-session in-flight guard. A session
|
|
726
|
+
* with work in flight is never expired or deleted; when the last request
|
|
727
|
+
* lands, a deferred close runs immediately instead of waiting for the
|
|
728
|
+
* sweep. (The long-lived GET stream is deliberately not counted — it stays
|
|
729
|
+
* open for the session's whole life, so counting it would pin every
|
|
730
|
+
* session against the TTL forever.)
|
|
731
|
+
*/
|
|
732
|
+
async handleTransportPost(sessionId, req, res) {
|
|
733
|
+
this.inFlightRequests.set(sessionId, (this.inFlightRequests.get(sessionId) ?? 0) + 1);
|
|
734
|
+
try {
|
|
735
|
+
const session = this.sessions.get(sessionId);
|
|
736
|
+
if (session) {
|
|
737
|
+
await session.transport.handleRequest(req, res, req.body);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
finally {
|
|
741
|
+
const remaining = (this.inFlightRequests.get(sessionId) ?? 1) - 1;
|
|
742
|
+
if (remaining <= 0) {
|
|
743
|
+
this.inFlightRequests.delete(sessionId);
|
|
744
|
+
if (this.pendingSessionClose.has(sessionId)) {
|
|
745
|
+
this.pendingSessionClose.delete(sessionId);
|
|
746
|
+
void this.startCleanupSession(sessionId, { closeTransport: true });
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
else {
|
|
750
|
+
this.inFlightRequests.set(sessionId, remaining);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
async callBackendAPI(endpoint, init = {}, sessionId, opts) {
|
|
375
755
|
try {
|
|
376
756
|
const headers = this.sessionBinding.getAgentHeaders(sessionId);
|
|
377
757
|
const response = await fetch(`${this.backendUrl}${endpoint}`, {
|
|
@@ -400,7 +780,11 @@ class AgentDeckMCPServer {
|
|
|
400
780
|
return body;
|
|
401
781
|
}
|
|
402
782
|
catch (error) {
|
|
403
|
-
|
|
783
|
+
// NOT-191: quiet mode keeps best-effort teardown (unregister) from
|
|
784
|
+
// logging one stack trace per session; batch callers log one summary.
|
|
785
|
+
if (!opts?.quiet) {
|
|
786
|
+
console.error(`Failed to call backend API ${endpoint}:`, error);
|
|
787
|
+
}
|
|
404
788
|
throw error;
|
|
405
789
|
}
|
|
406
790
|
}
|
|
@@ -971,6 +1355,13 @@ class AgentDeckMCPServer {
|
|
|
971
1355
|
const header = readLaunchDeckHeader(req);
|
|
972
1356
|
const boundDeck = this.sessionBinding.getBinding(sessionId).deckId;
|
|
973
1357
|
if (header && header !== boundDeck && !(0, client_grants_1.principalAllowsDeck)(principal, header)) {
|
|
1358
|
+
this.getAuditStore()?.append({
|
|
1359
|
+
actor: principal.grantId,
|
|
1360
|
+
event: 'deck.selection_denied',
|
|
1361
|
+
targetId: (0, store_1.auditDeckTarget)(header),
|
|
1362
|
+
outcome: 'denied',
|
|
1363
|
+
reasonCode: 'resource_out_of_scope',
|
|
1364
|
+
});
|
|
974
1365
|
console.warn('[agent-deck] Grant follow-up deck denied (transport kept):', `grantId=${principal.grantId}`);
|
|
975
1366
|
this.sendOutOfScope(res);
|
|
976
1367
|
return false;
|
|
@@ -1112,6 +1503,13 @@ class AgentDeckMCPServer {
|
|
|
1112
1503
|
}
|
|
1113
1504
|
const deckId = (0, client_grants_1.resolveGrantDeck)(principal, readLaunchDeckHeader(req));
|
|
1114
1505
|
if (!deckId) {
|
|
1506
|
+
this.getAuditStore()?.append({
|
|
1507
|
+
actor: principal.grantId,
|
|
1508
|
+
event: 'deck.selection_denied',
|
|
1509
|
+
targetId: (0, store_1.auditDeckTarget)(readLaunchDeckHeader(req)),
|
|
1510
|
+
outcome: 'denied',
|
|
1511
|
+
reasonCode: 'resource_out_of_scope',
|
|
1512
|
+
});
|
|
1115
1513
|
console.warn('[agent-deck] Grant initialize deck denied (no session created):', `grantId=${principal.grantId}`);
|
|
1116
1514
|
this.sendOutOfScope(res);
|
|
1117
1515
|
return;
|
|
@@ -1126,6 +1524,13 @@ class AgentDeckMCPServer {
|
|
|
1126
1524
|
this.sendGrantRequired(res);
|
|
1127
1525
|
return;
|
|
1128
1526
|
}
|
|
1527
|
+
this.getAuditStore()?.append({
|
|
1528
|
+
actor: principal.grantId,
|
|
1529
|
+
event: 'grant.used',
|
|
1530
|
+
targetId: (0, store_1.auditDeckTarget)(deckId),
|
|
1531
|
+
outcome: 'succeeded',
|
|
1532
|
+
reasonCode: null,
|
|
1533
|
+
});
|
|
1129
1534
|
await this.establishTransportSession(req, res, sessionId);
|
|
1130
1535
|
}
|
|
1131
1536
|
async handleMcpPost(req, res) {
|
|
@@ -1152,8 +1557,16 @@ class AgentDeckMCPServer {
|
|
|
1152
1557
|
return;
|
|
1153
1558
|
}
|
|
1154
1559
|
}
|
|
1560
|
+
// The auth above awaits, so re-check: a sweep may have expired the
|
|
1561
|
+
// session while it ran, and answering on a dead transport would hang.
|
|
1562
|
+
const live = this.sessions.get(sessionIdHeader);
|
|
1563
|
+
if (!live) {
|
|
1564
|
+
this.sendSessionNotFound(sessionIdHeader, res);
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
1567
|
+
this.noteClientActivity(sessionIdHeader, req);
|
|
1155
1568
|
this.touchLiveDisplay(sessionIdHeader);
|
|
1156
|
-
await
|
|
1569
|
+
await this.handleTransportPost(sessionIdHeader, req, res);
|
|
1157
1570
|
return;
|
|
1158
1571
|
}
|
|
1159
1572
|
const body = req.body;
|
|
@@ -1161,6 +1574,22 @@ class AgentDeckMCPServer {
|
|
|
1161
1574
|
typeof body === 'object' &&
|
|
1162
1575
|
((0, types_js_1.isInitializeRequest)(body) ||
|
|
1163
1576
|
(Array.isArray(body) && body.some((message) => (0, types_js_1.isInitializeRequest)(message))));
|
|
1577
|
+
if (isInit && process.env.AGENT_DECK_HOSTED_MODE === '1') {
|
|
1578
|
+
const principal = this.authenticateGrant(readBearerToken(req));
|
|
1579
|
+
const clientKey = principal
|
|
1580
|
+
? `grant:${principal.grantId}`
|
|
1581
|
+
: `ip:${req.socket.remoteAddress ?? 'unknown'}`;
|
|
1582
|
+
const rate = this.initializeLimiter.consume(clientKey, exports.MCP_INITIALIZE_RATE_LIMIT);
|
|
1583
|
+
if (!rate.allowed) {
|
|
1584
|
+
res.set('Retry-After', String(rate.retryAfterSeconds));
|
|
1585
|
+
res.status(429).json({
|
|
1586
|
+
jsonrpc: '2.0',
|
|
1587
|
+
error: { code: -32000, message: 'Too many initialize requests' },
|
|
1588
|
+
id: null,
|
|
1589
|
+
});
|
|
1590
|
+
return;
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1164
1593
|
if (!isInit) {
|
|
1165
1594
|
// Hosted endpoints run the bearer-grant gate before session
|
|
1166
1595
|
// existence: an unauthenticated prober gets 401, never the NOT-101
|
|
@@ -1205,6 +1634,13 @@ class AgentDeckMCPServer {
|
|
|
1205
1634
|
await this.authenticateLaunchDeck(sessionId, req);
|
|
1206
1635
|
}
|
|
1207
1636
|
catch (error) {
|
|
1637
|
+
this.getAuditStore()?.append({
|
|
1638
|
+
actor: 'local-launch',
|
|
1639
|
+
event: 'deck.selection_denied',
|
|
1640
|
+
targetId: (0, store_1.auditDeckTarget)(launchDeck),
|
|
1641
|
+
outcome: 'denied',
|
|
1642
|
+
reasonCode: 'resource_out_of_scope',
|
|
1643
|
+
});
|
|
1208
1644
|
console.warn('[agent-deck] Launch-deck auth failed before MCP init:', error instanceof Error ? error.message : error);
|
|
1209
1645
|
this.sendLaunchDeckInvalid(res, error instanceof Error ? error.message : 'LAUNCH_DECK_INVALID');
|
|
1210
1646
|
return;
|
|
@@ -1227,7 +1663,7 @@ class AgentDeckMCPServer {
|
|
|
1227
1663
|
*/
|
|
1228
1664
|
async establishTransportSession(req, res, sessionId) {
|
|
1229
1665
|
const body = req.body;
|
|
1230
|
-
const server = this.createMcpServer(sessionId);
|
|
1666
|
+
const server = await this.createMcpServer(sessionId);
|
|
1231
1667
|
let sessionEntry;
|
|
1232
1668
|
const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
|
|
1233
1669
|
sessionIdGenerator: () => sessionId,
|
|
@@ -1240,17 +1676,11 @@ class AgentDeckMCPServer {
|
|
|
1240
1676
|
transport.onclose = () => {
|
|
1241
1677
|
const closedSessionId = transport.sessionId;
|
|
1242
1678
|
if (closedSessionId) {
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
//
|
|
1246
|
-
//
|
|
1247
|
-
|
|
1248
|
-
this.sessionBinding.clearSession(closedSessionId);
|
|
1249
|
-
this.badgeBySession.delete(closedSessionId);
|
|
1250
|
-
this.lastTouchAtMs.delete(closedSessionId);
|
|
1251
|
-
this.unregisterTasks.delete(closedSessionId);
|
|
1252
|
-
});
|
|
1253
|
-
this.unregisterTasks.set(closedSessionId, task);
|
|
1679
|
+
// NOT-191: every close funnels through the unified cleanup — the
|
|
1680
|
+
// transport/server entry, trusted runtime session, binding, badge,
|
|
1681
|
+
// touch, activity, and live-display row all go together. A sweep or
|
|
1682
|
+
// deferred close already running for this id is joined, not doubled.
|
|
1683
|
+
void this.startCleanupSession(closedSessionId, { closeTransport: false });
|
|
1254
1684
|
}
|
|
1255
1685
|
};
|
|
1256
1686
|
try {
|
|
@@ -1278,6 +1708,9 @@ class AgentDeckMCPServer {
|
|
|
1278
1708
|
// The replacement session is live, so the session this client lost to the
|
|
1279
1709
|
// restart is genuinely recovered and no longer a stranded client.
|
|
1280
1710
|
this.markStaleSessionRecovered(req);
|
|
1711
|
+
// NOT-191: the handshake is the session's first client activity, and it
|
|
1712
|
+
// is also where a heartbeat-capable bridge is first recognized.
|
|
1713
|
+
this.noteClientActivity(transport.sessionId, req);
|
|
1281
1714
|
if (!this.sessionBinding.isUnassigned(transport.sessionId)) {
|
|
1282
1715
|
void this.registerLiveDisplay(transport.sessionId).catch(() => { });
|
|
1283
1716
|
}
|
|
@@ -1315,8 +1748,23 @@ class AgentDeckMCPServer {
|
|
|
1315
1748
|
return;
|
|
1316
1749
|
}
|
|
1317
1750
|
}
|
|
1751
|
+
// The auth above awaits — same re-check as the POST path.
|
|
1752
|
+
const live = this.sessions.get(sessionId);
|
|
1753
|
+
if (!live) {
|
|
1754
|
+
this.sendSessionNotFound(sessionId, res);
|
|
1755
|
+
return;
|
|
1756
|
+
}
|
|
1757
|
+
this.noteClientActivity(sessionId, req);
|
|
1758
|
+
if (req.method === 'DELETE' && (this.inFlightRequests.get(sessionId) ?? 0) > 0) {
|
|
1759
|
+
// NOT-191: never delete a session under running work. The close is
|
|
1760
|
+
// deferred and runs when the last in-flight request lands (or on the
|
|
1761
|
+
// next sweep); the 200 acknowledges the request, not the teardown.
|
|
1762
|
+
this.pendingSessionClose.add(sessionId);
|
|
1763
|
+
res.status(200).end();
|
|
1764
|
+
return;
|
|
1765
|
+
}
|
|
1318
1766
|
this.touchLiveDisplay(sessionId);
|
|
1319
|
-
await
|
|
1767
|
+
await live.transport.handleRequest(req, res);
|
|
1320
1768
|
}
|
|
1321
1769
|
async start() {
|
|
1322
1770
|
if (this.httpServer) {
|
|
@@ -1356,6 +1804,7 @@ class AgentDeckMCPServer {
|
|
|
1356
1804
|
this.httpServer = httpServer;
|
|
1357
1805
|
});
|
|
1358
1806
|
this.startLiveDisplayKeepAlive();
|
|
1807
|
+
this.startTransportSweep();
|
|
1359
1808
|
return this.app;
|
|
1360
1809
|
}
|
|
1361
1810
|
catch (error) {
|
|
@@ -1367,21 +1816,26 @@ class AgentDeckMCPServer {
|
|
|
1367
1816
|
async stop() {
|
|
1368
1817
|
try {
|
|
1369
1818
|
this.stopLiveDisplayKeepAlive();
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
}
|
|
1378
|
-
|
|
1379
|
-
//
|
|
1380
|
-
//
|
|
1381
|
-
await Promise.all([...this.
|
|
1819
|
+
this.stopTransportSweep();
|
|
1820
|
+
// NOT-191: every open session goes through the unified cleanup, so
|
|
1821
|
+
// shutdown removes the same state a clean DELETE would — transport,
|
|
1822
|
+
// trusted runtime session, binding, badge, and live-display row.
|
|
1823
|
+
// Cleanups run concurrently with unregisters under the shared bound,
|
|
1824
|
+
// and their failures collapse into one summary line.
|
|
1825
|
+
const sessionIds = [...this.sessions.keys()];
|
|
1826
|
+
const results = await Promise.all(sessionIds.map((sessionId) => this.startCleanupSession(sessionId, { closeTransport: true })));
|
|
1827
|
+
// Drain cleanups that started outside the snapshot (a close racing
|
|
1828
|
+
// shutdown) before tearing down HTTP — otherwise tests close the stub
|
|
1829
|
+
// backend and see ECONNRESET console.error noise.
|
|
1830
|
+
await Promise.all([...this.cleanupTasks.values()]);
|
|
1831
|
+
this.logUnregisterSummary('server-shutdown', results);
|
|
1382
1832
|
// Release the port too, otherwise a restart on the same port races the old
|
|
1383
1833
|
// listener and the "did it come back?" probe can't tell the two apart.
|
|
1384
1834
|
await this.closeHttpServer();
|
|
1835
|
+
this.sharedSecurityDb?.close();
|
|
1836
|
+
this.sharedSecurityDb = null;
|
|
1837
|
+
this.grantStoreCache = null;
|
|
1838
|
+
this.auditStoreCache = null;
|
|
1385
1839
|
console.log(`🛑 MCP server stopped`);
|
|
1386
1840
|
}
|
|
1387
1841
|
catch (error) {
|