@haneinfo/mcp-server 3.5.1 → 4.0.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/README.md +177 -12
- package/dist/admin-access.d.ts +24 -0
- package/dist/admin-access.d.ts.map +1 -0
- package/dist/admin-access.js +54 -0
- package/dist/admin-access.js.map +1 -0
- package/dist/authenticator.d.ts +31 -0
- package/dist/authenticator.d.ts.map +1 -0
- package/dist/authenticator.js +37 -0
- package/dist/authenticator.js.map +1 -0
- package/dist/deployment-config.d.ts +67 -0
- package/dist/deployment-config.d.ts.map +1 -0
- package/dist/deployment-config.js +157 -0
- package/dist/deployment-config.js.map +1 -0
- package/dist/discovery-push.service.d.ts +11 -9
- package/dist/discovery-push.service.d.ts.map +1 -1
- package/dist/discovery-push.service.js +27 -11
- package/dist/discovery-push.service.js.map +1 -1
- package/dist/enabled-resources.d.ts +53 -0
- package/dist/enabled-resources.d.ts.map +1 -0
- package/dist/enabled-resources.js +243 -0
- package/dist/enabled-resources.js.map +1 -0
- package/dist/iam-authenticator.d.ts +29 -0
- package/dist/iam-authenticator.d.ts.map +1 -0
- package/dist/iam-authenticator.js +269 -0
- package/dist/iam-authenticator.js.map +1 -0
- package/dist/index.d.ts +10 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -5
- package/dist/index.js.map +1 -1
- package/dist/mcp-tool.registry.d.ts +21 -76
- package/dist/mcp-tool.registry.d.ts.map +1 -1
- package/dist/mcp-tool.registry.js +66 -240
- package/dist/mcp-tool.registry.js.map +1 -1
- package/dist/mcp.controller.d.ts +21 -5
- package/dist/mcp.controller.d.ts.map +1 -1
- package/dist/mcp.controller.js +273 -48
- package/dist/mcp.controller.js.map +1 -1
- package/dist/mcp.module.d.ts +5 -0
- package/dist/mcp.module.d.ts.map +1 -1
- package/dist/mcp.module.js +71 -8
- package/dist/mcp.module.js.map +1 -1
- package/dist/mcp.service.d.ts +31 -18
- package/dist/mcp.service.d.ts.map +1 -1
- package/dist/mcp.service.js +784 -194
- package/dist/mcp.service.js.map +1 -1
- package/dist/pg-rate-limiter.d.ts +46 -0
- package/dist/pg-rate-limiter.d.ts.map +1 -0
- package/dist/pg-rate-limiter.js +161 -0
- package/dist/pg-rate-limiter.js.map +1 -0
- package/dist/plugin.d.ts +41 -4
- package/dist/plugin.d.ts.map +1 -1
- package/dist/plugin.js +23 -11
- package/dist/plugin.js.map +1 -1
- package/dist/prm.controller.d.ts +17 -0
- package/dist/prm.controller.d.ts.map +1 -0
- package/dist/prm.controller.js +77 -0
- package/dist/prm.controller.js.map +1 -0
- package/dist/protocol-config.d.ts +36 -0
- package/dist/protocol-config.d.ts.map +1 -0
- package/dist/protocol-config.js +142 -0
- package/dist/protocol-config.js.map +1 -0
- package/dist/rate-limit-config.d.ts +25 -0
- package/dist/rate-limit-config.d.ts.map +1 -0
- package/dist/rate-limit-config.js +85 -0
- package/dist/rate-limit-config.js.map +1 -0
- package/dist/rate-limit-http.d.ts +11 -0
- package/dist/rate-limit-http.d.ts.map +1 -0
- package/dist/rate-limit-http.js +68 -0
- package/dist/rate-limit-http.js.map +1 -0
- package/dist/request-state.d.ts +14 -9
- package/dist/request-state.d.ts.map +1 -1
- package/dist/request-state.js +37 -3
- package/dist/request-state.js.map +1 -1
- package/dist/types.d.ts +24 -7
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -1
- package/dist/write-confirmation.d.ts +82 -0
- package/dist/write-confirmation.d.ts.map +1 -0
- package/dist/write-confirmation.js +207 -0
- package/dist/write-confirmation.js.map +1 -0
- package/haneinfo.plugin.json +16 -8
- package/package.json +15 -3
- package/prisma/mcp-rate-limit.prisma +34 -0
package/dist/mcp.service.js
CHANGED
|
@@ -8,28 +8,89 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
8
8
|
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
9
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
10
|
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
11
14
|
var McpService_1;
|
|
12
15
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
16
|
exports.McpService = void 0;
|
|
14
|
-
|
|
15
|
-
const
|
|
17
|
+
const node_crypto_1 = require("node:crypto");
|
|
18
|
+
const commands_1 = require("@haneinfo/commands");
|
|
19
|
+
const plugin_api_1 = require("@haneinfo/plugin-api");
|
|
16
20
|
const server_1 = require("@modelcontextprotocol/server");
|
|
17
21
|
const common_1 = require("@nestjs/common");
|
|
22
|
+
const zod_1 = require("zod");
|
|
23
|
+
const deployment_config_1 = require("./deployment-config");
|
|
24
|
+
const enabled_resources_1 = require("./enabled-resources");
|
|
18
25
|
const mcp_tool_registry_1 = require("./mcp-tool.registry");
|
|
19
26
|
const request_state_1 = require("./request-state");
|
|
20
|
-
const
|
|
21
|
-
const
|
|
27
|
+
const types_1 = require("./types");
|
|
28
|
+
const write_confirmation_1 = require("./write-confirmation");
|
|
29
|
+
const NOOP_RBAC = {
|
|
30
|
+
rolesForUser: async () => [],
|
|
31
|
+
flatten: () => ({ roleNames: [], permissionPolicy: 'DENY_ALL', permissions: [] }),
|
|
32
|
+
};
|
|
33
|
+
const DEFAULT_LOCK_TIMEOUT_MS = 2000;
|
|
34
|
+
const DEFAULT_ADMIN_MAX_AUTH_AGE_SECONDS = 3600;
|
|
35
|
+
const MODERN_PROTOCOL_VERSION = '2026-07-28';
|
|
36
|
+
const CONFIRMATION_FORM_SCHEMA = zod_1.z.object({ confirm: zod_1.z.boolean() });
|
|
37
|
+
function toolUnavailableError() {
|
|
38
|
+
return new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Tool is unavailable', {
|
|
39
|
+
code: 'tool_unavailable',
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
function confirmationUnavailableError() {
|
|
43
|
+
return new server_1.ProtocolError(write_confirmation_1.CONFIRMATION_UNAVAILABLE_ERROR_CODE, 'Write confirmation is unavailable', { code: 'confirmation_unavailable' });
|
|
44
|
+
}
|
|
45
|
+
function isPlainRecord(value) {
|
|
46
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
47
|
+
}
|
|
48
|
+
function hasElicitationFormCapability(clientCapabilities) {
|
|
49
|
+
if (!isPlainRecord(clientCapabilities))
|
|
50
|
+
return false;
|
|
51
|
+
const elicitation = clientCapabilities.elicitation;
|
|
52
|
+
if (!isPlainRecord(elicitation))
|
|
53
|
+
return false;
|
|
54
|
+
return isPlainRecord(elicitation.form);
|
|
55
|
+
}
|
|
56
|
+
function commandRequiresConfirmation(command, surface) {
|
|
57
|
+
if (command.access !== 'write')
|
|
58
|
+
return false;
|
|
59
|
+
if (surface === 'mcp-admin')
|
|
60
|
+
return true;
|
|
61
|
+
return command.confirmation !== 'exempt';
|
|
62
|
+
}
|
|
63
|
+
function commandSchemaToJsonSchema(schema, io) {
|
|
64
|
+
const standard = schema['~standard'];
|
|
65
|
+
const converter = standard?.jsonSchema?.[io];
|
|
66
|
+
if (typeof converter === 'function') {
|
|
67
|
+
return converter({ target: 'draft-2020-12' });
|
|
68
|
+
}
|
|
69
|
+
return zod_1.z.toJSONSchema(schema, { io });
|
|
70
|
+
}
|
|
22
71
|
let McpService = McpService_1 = class McpService {
|
|
23
|
-
constructor(registry) {
|
|
72
|
+
constructor(registry, commandsOptions, rbac, identityStore, prisma, deployment, enabledResources) {
|
|
24
73
|
this.registry = registry;
|
|
74
|
+
this.identityStore = identityStore;
|
|
75
|
+
this.prisma = prisma;
|
|
76
|
+
this.deployment = deployment;
|
|
77
|
+
this.enabledResources = enabledResources;
|
|
25
78
|
this.logger = new common_1.Logger(McpService_1.name);
|
|
26
|
-
this.
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
79
|
+
this.requestStateKey = (0, request_state_1.tryReadMcpRequestStateKey)();
|
|
80
|
+
if (commandsOptions?.commands) {
|
|
81
|
+
this.commands = commandsOptions.commands;
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
this.logger.warn('McpModule.forRoot was called without options.commands; MCP serves no tools until a sealed CommandRegistry is passed.');
|
|
85
|
+
const empty = (0, commands_1.createCommandRegistry)();
|
|
86
|
+
empty.seal();
|
|
87
|
+
this.commands = empty;
|
|
88
|
+
}
|
|
89
|
+
this.rbac = rbac ?? NOOP_RBAC;
|
|
90
|
+
this.authorizer = (0, commands_1.createCommandAuthorizer)({
|
|
91
|
+
rbac: this.rbac,
|
|
92
|
+
lockTimeoutMs: commandsOptions?.lockTimeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS,
|
|
93
|
+
});
|
|
33
94
|
}
|
|
34
95
|
/** Returns the application-wide handler used by HTTP controllers. */
|
|
35
96
|
getHandler() {
|
|
@@ -47,10 +108,9 @@ let McpService = McpService_1 = class McpService {
|
|
|
47
108
|
throw new Error('MCP call context is missing from validated authentication info');
|
|
48
109
|
return ctx;
|
|
49
110
|
};
|
|
50
|
-
const handler = (0,
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
legacySessionIdleTtlMs: readPositiveInteger('MCP_LEGACY_SESSION_IDLE_TTL_MS'),
|
|
111
|
+
const handler = (0, server_1.createMcpHandler)((requestContext) => this.createServer(resolveContext(requestContext)), {
|
|
112
|
+
legacy: 'reject',
|
|
113
|
+
responseMode: 'json',
|
|
54
114
|
onerror: (error) => this.logger.error(error.message, error.stack),
|
|
55
115
|
});
|
|
56
116
|
return {
|
|
@@ -59,17 +119,7 @@ let McpService = McpService_1 = class McpService {
|
|
|
59
119
|
const current = readMcpCallContext(options?.authInfo) ?? fallbackCtx;
|
|
60
120
|
if (!current)
|
|
61
121
|
throw new Error('MCP call context is missing from validated authentication info');
|
|
62
|
-
|
|
63
|
-
return this.requestContexts.run(current, () => handler.fetch(request, options));
|
|
64
|
-
// With @haneinfo/settings: refresh mcp-server.disabledTools, and let a tools/call reach the
|
|
65
|
-
// wrapper of the named tool so it can answer TOOL_DISABLED (tools/list still hides it).
|
|
66
|
-
// With a tool source (decision 202610-c5e8): let it recompute (throttled by the source) so
|
|
67
|
-
// this request's server registers its current tools. No list-changed notification is sent.
|
|
68
|
-
return Promise.all([
|
|
69
|
-
this.registry.refreshDisabledTools(),
|
|
70
|
-
this.registry.refreshToolSources(),
|
|
71
|
-
calledToolName(request, options?.parsedBody),
|
|
72
|
-
]).then(([, , called]) => this.requestContexts.run(current, () => this.calledTools.run(called, () => handler.fetch(request, options))));
|
|
122
|
+
return handler.fetch(request, options);
|
|
73
123
|
},
|
|
74
124
|
};
|
|
75
125
|
}
|
|
@@ -78,205 +128,745 @@ let McpService = McpService_1 = class McpService {
|
|
|
78
128
|
this.sharedHandler = undefined;
|
|
79
129
|
await handler?.close();
|
|
80
130
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
131
|
+
/**
|
|
132
|
+
* Handles a stateless MCP 2025-11-25 request using a per-request
|
|
133
|
+
* `WebStandardStreamableHTTPServerTransport` and `McpServer`, closing both on completion.
|
|
134
|
+
*/
|
|
135
|
+
async handleLegacy2025(request, options) {
|
|
136
|
+
const current = readMcpCallContext(options?.authInfo);
|
|
137
|
+
if (!current) {
|
|
138
|
+
throw new Error('MCP call context is missing from validated authentication info');
|
|
139
|
+
}
|
|
140
|
+
const server = this.createServer(current, { supportedProtocolVersions: ['2025-11-25'] });
|
|
141
|
+
const transport = new server_1.WebStandardStreamableHTTPServerTransport({
|
|
142
|
+
sessionIdGenerator: undefined,
|
|
143
|
+
enableJsonResponse: true,
|
|
144
|
+
supportedProtocolVersions: ['2025-11-25'],
|
|
145
|
+
});
|
|
146
|
+
await server.connect(transport);
|
|
147
|
+
try {
|
|
148
|
+
return await transport.handleRequest(request, options);
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
await transport.close().catch(() => undefined);
|
|
152
|
+
await server.close().catch(() => undefined);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
createServer(ctx, options) {
|
|
156
|
+
const isLegacy2025 = options?.supportedProtocolVersions?.includes('2025-11-25') === true;
|
|
85
157
|
const server = new server_1.McpServer({
|
|
86
158
|
name: process.env.npm_package_name ?? 'haneinfo-app',
|
|
87
159
|
version: process.env.npm_package_version ?? '1.0.0',
|
|
88
|
-
},
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
160
|
+
}, {
|
|
161
|
+
capabilities: {
|
|
162
|
+
tools: { listChanged: false },
|
|
163
|
+
},
|
|
164
|
+
...(options?.supportedProtocolVersions
|
|
165
|
+
? { supportedProtocolVersions: options.supportedProtocolVersions }
|
|
166
|
+
: {}),
|
|
167
|
+
// Verification of requestState is performed inside tools/call after the
|
|
168
|
+
// confirmation gate so gate failures always return -32092 (1A §6, W5-06).
|
|
169
|
+
inputRequired: { legacyShim: false },
|
|
170
|
+
});
|
|
171
|
+
const lowLevel = server.server;
|
|
172
|
+
lowLevel.setRequestHandler('tools/list', async (_request, sdkCtx) => {
|
|
173
|
+
const requestCtx = readMcpCallContext(sdkCtx.http?.authInfo) ?? ctx;
|
|
174
|
+
const surface = requestCtx.kind === 'admin' ? 'mcp-admin' : 'mcp';
|
|
175
|
+
if (this.registry.disabledToolsSupported) {
|
|
176
|
+
await this.registry.refreshDisabledTools();
|
|
92
177
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
const inputSchema = generated
|
|
111
|
-
? {
|
|
112
|
-
'~standard': {
|
|
113
|
-
...standard,
|
|
114
|
-
validate: (value) => resolve()?.inputSchema === originalSchema ? { value } : standard.validate(value),
|
|
115
|
-
},
|
|
178
|
+
// Dynamic tools resolve against the current source on every request (1A §4).
|
|
179
|
+
await this.commands.refreshSources();
|
|
180
|
+
const actor = await this.buildActor(requestCtx);
|
|
181
|
+
// Load the caller's roles once per tools/list request; tools/call re-queries live.
|
|
182
|
+
const preloadedRoles = actor.principalKind !== 'm2m-api-key' &&
|
|
183
|
+
actor.actingUserId !== null &&
|
|
184
|
+
actor.actingUserId.length > 0
|
|
185
|
+
? await this.rbac.rolesForUser(actor.actingUserId)
|
|
186
|
+
: undefined;
|
|
187
|
+
const aliasPrefix = (0, mcp_tool_registry_1.getToolAliasPrefix)();
|
|
188
|
+
const tools = [];
|
|
189
|
+
const kind = requestCtx.kind;
|
|
190
|
+
for (const cmd of this.commands.list(surface)) {
|
|
191
|
+
if (this.enabledResources &&
|
|
192
|
+
!this.enabledResources.isCommandScopeAllowed(kind, cmd.scope)) {
|
|
193
|
+
this.enabledResources.warnDynamicCommandScopeOnce(kind, cmd.name);
|
|
194
|
+
continue;
|
|
116
195
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
196
|
+
if (this.registry.isToolDisabled(cmd.name))
|
|
197
|
+
continue;
|
|
198
|
+
// Hide confirmation-required writes on 2025-11-25; list them normally on 2026-07-28.
|
|
199
|
+
if (isLegacy2025 && commandRequiresConfirmation(cmd, surface))
|
|
200
|
+
continue;
|
|
201
|
+
const decision = await this.authorizer.authorize({
|
|
202
|
+
actor,
|
|
203
|
+
command: cmd,
|
|
204
|
+
...(preloadedRoles !== undefined ? { preloadedRoles } : {}),
|
|
205
|
+
});
|
|
206
|
+
if (!decision.ok)
|
|
207
|
+
continue;
|
|
208
|
+
const baseEntry = {
|
|
209
|
+
name: cmd.name,
|
|
210
|
+
description: cmd.description ?? '',
|
|
211
|
+
inputSchema: commandSchemaToJsonSchema(cmd.inputSchema, 'input'),
|
|
212
|
+
annotations: { readOnlyHint: cmd.access === 'read' },
|
|
130
213
|
};
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
214
|
+
if (cmd.outputSchema) {
|
|
215
|
+
baseEntry.outputSchema = commandSchemaToJsonSchema(cmd.outputSchema, 'output');
|
|
216
|
+
}
|
|
217
|
+
tools.push(baseEntry);
|
|
218
|
+
if (aliasPrefix) {
|
|
219
|
+
tools.push({
|
|
220
|
+
...baseEntry,
|
|
221
|
+
name: `${aliasPrefix}_${cmd.name}`,
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return { tools };
|
|
226
|
+
});
|
|
227
|
+
lowLevel.setRequestHandler('tools/call', async (request, sdkCtx) => {
|
|
228
|
+
const requestCtx = readMcpCallContext(sdkCtx.http?.authInfo) ?? ctx;
|
|
229
|
+
const surface = requestCtx.kind === 'admin' ? 'mcp-admin' : 'mcp';
|
|
230
|
+
const calledName = typeof request.params?.name === 'string' ? request.params.name : '';
|
|
231
|
+
if (this.registry.disabledToolsSupported) {
|
|
232
|
+
await this.registry.refreshDisabledTools();
|
|
233
|
+
}
|
|
234
|
+
await this.commands.refreshSources();
|
|
235
|
+
const command = this.resolveCommand(calledName, surface);
|
|
236
|
+
if (!command) {
|
|
237
|
+
throw toolUnavailableError();
|
|
238
|
+
}
|
|
239
|
+
if (this.enabledResources &&
|
|
240
|
+
!this.enabledResources.isCommandScopeAllowed(requestCtx.kind, command.scope)) {
|
|
241
|
+
this.enabledResources.warnDynamicCommandScopeOnce(requestCtx.kind, command.name);
|
|
242
|
+
throw toolUnavailableError();
|
|
243
|
+
}
|
|
244
|
+
if (this.registry.isToolDisabled(command.name)) {
|
|
245
|
+
throw toolUnavailableError();
|
|
246
|
+
}
|
|
247
|
+
const actor = await this.buildActor(requestCtx);
|
|
248
|
+
const preCheck = await this.authorizer.authorize({ actor, command });
|
|
249
|
+
if (!preCheck.ok) {
|
|
250
|
+
throw toolUnavailableError();
|
|
251
|
+
}
|
|
252
|
+
const requiresConfirmation = commandRequiresConfirmation(command, surface);
|
|
253
|
+
const rawRequestState = sdkCtx.mcpReq.requestState();
|
|
254
|
+
if (requiresConfirmation) {
|
|
255
|
+
return await this.executeConfirmedWrite({
|
|
256
|
+
request,
|
|
257
|
+
sdkCtx,
|
|
258
|
+
requestCtx,
|
|
259
|
+
actor,
|
|
260
|
+
command,
|
|
261
|
+
isLegacy2025,
|
|
262
|
+
rawRequestState,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
if (rawRequestState !== undefined) {
|
|
266
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {
|
|
267
|
+
reason: 'invalid_request_state',
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
// Validate input only after authorization succeeds, so unauthorized callers cannot
|
|
271
|
+
// probe input schemas via validation error differences.
|
|
272
|
+
const parsed = command.inputSchema.safeParse(request.params?.arguments ?? {});
|
|
273
|
+
if (!parsed.success) {
|
|
274
|
+
return {
|
|
275
|
+
isError: true,
|
|
276
|
+
content: [{ type: 'text', text: 'Invalid tool arguments' }],
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
try {
|
|
280
|
+
if (!this.prisma) {
|
|
281
|
+
throw new Error('PRISMA provider is required to execute commands');
|
|
282
|
+
}
|
|
283
|
+
const result = command.access === 'read'
|
|
284
|
+
? await command.handler(actor, parsed.data, this.prisma)
|
|
285
|
+
: await this.prisma.$transaction(async (tx) => {
|
|
286
|
+
const txCheck = await this.authorizer.authorizeWriteInTransaction({ actor, command }, tx);
|
|
287
|
+
if (!txCheck.ok) {
|
|
288
|
+
if (txCheck.code === 'lock_timeout') {
|
|
289
|
+
throw new server_1.ProtocolError(-32090, 'Lock timeout', { code: 'lock_timeout' });
|
|
290
|
+
}
|
|
291
|
+
if (txCheck.code === 'authorization_stale') {
|
|
292
|
+
throw new server_1.ProtocolError(-32091, 'Authorization stale', {
|
|
293
|
+
code: 'authorization_stale',
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
throw toolUnavailableError();
|
|
297
|
+
}
|
|
298
|
+
return await command.handler(actor, parsed.data, tx);
|
|
299
|
+
}, { isolationLevel: 'ReadCommitted' });
|
|
300
|
+
if ((0, server_1.isInputRequiredResult)(result)) {
|
|
301
|
+
return result;
|
|
302
|
+
}
|
|
303
|
+
return formatToolSuccess(result);
|
|
304
|
+
}
|
|
305
|
+
catch (err) {
|
|
306
|
+
return this.handleToolExecutionError(command.name, err);
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
return server;
|
|
310
|
+
}
|
|
311
|
+
async executeConfirmedWrite(params) {
|
|
312
|
+
const { request, sdkCtx, requestCtx, actor, command, isLegacy2025, rawRequestState } = params;
|
|
313
|
+
const envelope = sdkCtx.mcpReq.envelope;
|
|
314
|
+
const protocolVersion = envelope?.['io.modelcontextprotocol/protocolVersion'];
|
|
315
|
+
const clientCaps = envelope?.['io.modelcontextprotocol/clientCapabilities'];
|
|
316
|
+
// Gate check on BOTH initial call and every resume (1A §6, W5-06).
|
|
317
|
+
const requestStateKey = this.requestStateKey;
|
|
318
|
+
if (isLegacy2025 ||
|
|
319
|
+
protocolVersion !== MODERN_PROTOCOL_VERSION ||
|
|
320
|
+
!hasElicitationFormCapability(clientCaps) ||
|
|
321
|
+
!requestStateKey) {
|
|
322
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
323
|
+
event: 'confirmation_gate_rejected',
|
|
324
|
+
correlationId: (0, node_crypto_1.randomUUID)(),
|
|
325
|
+
operationId: null,
|
|
326
|
+
resource: requestCtx.resource,
|
|
327
|
+
issuer: requestCtx.issuer,
|
|
328
|
+
subject: requestCtx.sub,
|
|
329
|
+
actingUserId: requestCtx.actingUserId,
|
|
330
|
+
clientId: requestCtx.clientId,
|
|
331
|
+
toolName: command.name,
|
|
332
|
+
resultCode: 'confirmation_unavailable',
|
|
333
|
+
workflowId: requestCtx.workflowId,
|
|
334
|
+
});
|
|
335
|
+
throw confirmationUnavailableError();
|
|
336
|
+
}
|
|
337
|
+
const requestStateCodec = (0, request_state_1.createMcpRequestStateStore)({
|
|
338
|
+
key: requestStateKey,
|
|
339
|
+
issuer: requestCtx.issuer,
|
|
340
|
+
principal: requestCtx.sub,
|
|
341
|
+
resource: requestCtx.resource,
|
|
342
|
+
ttlSeconds: request_state_1.DEFAULT_REQUEST_STATE_TTL_SECONDS,
|
|
343
|
+
});
|
|
344
|
+
// First call: validate args, persist pending receipt, mint requestState, return input_required.
|
|
345
|
+
if (rawRequestState === undefined) {
|
|
346
|
+
const parsed = command.inputSchema.safeParse(request.params?.arguments ?? {});
|
|
347
|
+
if (!parsed.success) {
|
|
348
|
+
return {
|
|
349
|
+
isError: true,
|
|
350
|
+
content: [{ type: 'text', text: 'Invalid tool arguments' }],
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
if (!this.prisma) {
|
|
354
|
+
throw new Error('PRISMA provider is required to execute commands');
|
|
355
|
+
}
|
|
356
|
+
const operationId = (0, node_crypto_1.randomUUID)();
|
|
357
|
+
const correlationId = (0, node_crypto_1.randomUUID)();
|
|
358
|
+
const argsDigest = (0, write_confirmation_1.computeArgsDigest)(parsed.data);
|
|
359
|
+
const expSeconds = Math.floor(Date.now() / 1000) + request_state_1.DEFAULT_REQUEST_STATE_TTL_SECONDS;
|
|
360
|
+
const expiresAt = new Date(expSeconds * 1000);
|
|
361
|
+
await this.prisma.$transaction(async (tx) => {
|
|
362
|
+
await (0, write_confirmation_1.insertPendingConfirmationReceipt)(tx, {
|
|
363
|
+
operationId,
|
|
364
|
+
correlationId,
|
|
365
|
+
issuer: requestCtx.issuer,
|
|
366
|
+
subject: requestCtx.sub,
|
|
367
|
+
actingUserId: requestCtx.actingUserId,
|
|
368
|
+
clientId: requestCtx.clientId,
|
|
369
|
+
resource: requestCtx.resource,
|
|
370
|
+
toolName: command.name,
|
|
371
|
+
schemaVersion: command.schemaVersion,
|
|
372
|
+
argsDigest,
|
|
373
|
+
expiresAt,
|
|
374
|
+
});
|
|
375
|
+
}, { isolationLevel: 'ReadCommitted' });
|
|
376
|
+
const statePayload = {
|
|
377
|
+
toolName: command.name,
|
|
378
|
+
schemaVersion: command.schemaVersion,
|
|
379
|
+
argsDigest,
|
|
380
|
+
operationId,
|
|
381
|
+
};
|
|
382
|
+
const requestState = await requestStateCodec.mint(statePayload, sdkCtx);
|
|
383
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
384
|
+
event: 'confirmation_issued',
|
|
385
|
+
correlationId,
|
|
386
|
+
operationId,
|
|
387
|
+
resource: requestCtx.resource,
|
|
388
|
+
issuer: requestCtx.issuer,
|
|
389
|
+
subject: requestCtx.sub,
|
|
390
|
+
actingUserId: requestCtx.actingUserId,
|
|
391
|
+
clientId: requestCtx.clientId,
|
|
392
|
+
toolName: command.name,
|
|
393
|
+
resultCode: 'pending',
|
|
394
|
+
workflowId: requestCtx.workflowId,
|
|
395
|
+
});
|
|
396
|
+
return (0, server_1.inputRequired)({
|
|
397
|
+
requestState,
|
|
398
|
+
inputRequests: {
|
|
399
|
+
confirm: server_1.inputRequired.elicit({
|
|
400
|
+
message: `Confirm execution of ${command.name}?`,
|
|
401
|
+
requestedSchema: CONFIRMATION_FORM_SCHEMA,
|
|
402
|
+
}),
|
|
403
|
+
},
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
// Resume call: verify requestState, re-parse args, validate form, lock & transition receipt.
|
|
407
|
+
if (typeof rawRequestState !== 'string') {
|
|
408
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {
|
|
409
|
+
reason: 'invalid_request_state',
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
let decodedPayload;
|
|
413
|
+
try {
|
|
414
|
+
const verified = await requestStateCodec.verify(rawRequestState, sdkCtx);
|
|
415
|
+
decodedPayload = (0, write_confirmation_1.parseConfirmationRequestStatePayload)(verified.data);
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
419
|
+
event: 'confirmation_binding_rejected',
|
|
420
|
+
correlationId: (0, node_crypto_1.randomUUID)(),
|
|
421
|
+
operationId: null,
|
|
422
|
+
resource: requestCtx.resource,
|
|
423
|
+
issuer: requestCtx.issuer,
|
|
424
|
+
subject: requestCtx.sub,
|
|
425
|
+
actingUserId: requestCtx.actingUserId,
|
|
426
|
+
clientId: requestCtx.clientId,
|
|
427
|
+
toolName: command.name,
|
|
428
|
+
resultCode: 'invalid_request_state',
|
|
429
|
+
workflowId: requestCtx.workflowId,
|
|
430
|
+
});
|
|
431
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {
|
|
432
|
+
reason: 'invalid_request_state',
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
if (!decodedPayload) {
|
|
436
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {
|
|
437
|
+
reason: 'invalid_request_state',
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
const parsed = command.inputSchema.safeParse(request.params?.arguments ?? {});
|
|
441
|
+
if (!parsed.success) {
|
|
442
|
+
return {
|
|
443
|
+
isError: true,
|
|
444
|
+
content: [{ type: 'text', text: 'Invalid tool arguments' }],
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
const argsDigest = (0, write_confirmation_1.computeArgsDigest)(parsed.data);
|
|
448
|
+
if (decodedPayload.toolName !== command.name ||
|
|
449
|
+
decodedPayload.schemaVersion !== command.schemaVersion ||
|
|
450
|
+
decodedPayload.argsDigest !== argsDigest) {
|
|
451
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
452
|
+
event: 'confirmation_binding_rejected',
|
|
453
|
+
correlationId: (0, node_crypto_1.randomUUID)(),
|
|
454
|
+
operationId: decodedPayload.operationId,
|
|
455
|
+
resource: requestCtx.resource,
|
|
456
|
+
issuer: requestCtx.issuer,
|
|
457
|
+
subject: requestCtx.sub,
|
|
458
|
+
actingUserId: requestCtx.actingUserId,
|
|
459
|
+
clientId: requestCtx.clientId,
|
|
460
|
+
toolName: command.name,
|
|
461
|
+
resultCode: 'binding_mismatch',
|
|
462
|
+
workflowId: requestCtx.workflowId,
|
|
463
|
+
});
|
|
464
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {
|
|
465
|
+
reason: 'invalid_request_state',
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
const formView = (0, server_1.inputResponse)(sdkCtx.mcpReq.inputResponses, 'confirm');
|
|
469
|
+
if (formView.kind !== 'elicit') {
|
|
470
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Missing or invalid confirmation response', { code: 'invalid_confirmation_response' });
|
|
471
|
+
}
|
|
472
|
+
let decision;
|
|
473
|
+
if (formView.action === 'accept') {
|
|
474
|
+
const formParsed = CONFIRMATION_FORM_SCHEMA.safeParse(formView.content);
|
|
475
|
+
if (!formParsed.success) {
|
|
476
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Invalid confirmation form response', { code: 'invalid_confirmation_response' });
|
|
477
|
+
}
|
|
478
|
+
decision = formParsed.data.confirm ? 'accept' : 'decline';
|
|
479
|
+
}
|
|
480
|
+
else if (formView.action === 'decline') {
|
|
481
|
+
decision = 'decline';
|
|
482
|
+
}
|
|
483
|
+
else {
|
|
484
|
+
decision = 'cancel';
|
|
485
|
+
}
|
|
486
|
+
if (!this.prisma) {
|
|
487
|
+
throw new Error('PRISMA provider is required to execute commands');
|
|
488
|
+
}
|
|
489
|
+
let outcome;
|
|
490
|
+
try {
|
|
491
|
+
outcome = await this.prisma.$transaction(async (tx) => {
|
|
492
|
+
const receipt = await (0, write_confirmation_1.lockConfirmationReceiptForUpdate)(tx, decodedPayload.operationId);
|
|
493
|
+
if (!receipt) {
|
|
494
|
+
return { kind: 'not_found' };
|
|
495
|
+
}
|
|
496
|
+
if (receipt.issuer !== requestCtx.issuer ||
|
|
497
|
+
receipt.subject !== requestCtx.sub ||
|
|
498
|
+
receipt.actingUserId !== requestCtx.actingUserId ||
|
|
499
|
+
receipt.clientId !== requestCtx.clientId ||
|
|
500
|
+
receipt.resource !== requestCtx.resource ||
|
|
501
|
+
receipt.toolName !== command.name ||
|
|
502
|
+
receipt.schemaVersion !== command.schemaVersion ||
|
|
503
|
+
receipt.argsDigest !== argsDigest) {
|
|
504
|
+
return { kind: 'binding_mismatch', correlationId: receipt.correlationId };
|
|
505
|
+
}
|
|
506
|
+
if (receipt.status === 'committed' && decision === 'accept') {
|
|
507
|
+
return {
|
|
508
|
+
kind: 'replay',
|
|
509
|
+
correlationId: receipt.correlationId,
|
|
510
|
+
result: receipt.resultJson,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
if (receipt.status !== 'pending') {
|
|
158
514
|
return {
|
|
159
|
-
|
|
160
|
-
|
|
515
|
+
kind: 'already_finalized',
|
|
516
|
+
status: receipt.status,
|
|
517
|
+
correlationId: receipt.correlationId,
|
|
161
518
|
};
|
|
162
519
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
return { isError: true, content: [{ type: 'text', text: publicMessage }] };
|
|
520
|
+
const nowMs = Date.now();
|
|
521
|
+
if (nowMs >= receipt.expiresAt.getTime()) {
|
|
522
|
+
const transitioned = await (0, write_confirmation_1.transitionConfirmationReceipt)(tx, {
|
|
523
|
+
operationId: receipt.operationId,
|
|
524
|
+
nextStatus: 'expired',
|
|
525
|
+
});
|
|
526
|
+
return { kind: 'expired', transitioned, correlationId: receipt.correlationId };
|
|
171
527
|
}
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
get: () => {
|
|
177
|
-
const called = this.calledTools.getStore() === tool.name;
|
|
178
|
-
const current = resolve();
|
|
179
|
-
// A source tool removed since this (legacy) server was built: hidden from tools/list, and
|
|
180
|
-
// a direct call reaches the wrapper above, which answers "Tool <name> not found".
|
|
181
|
-
if (!current)
|
|
182
|
-
return fromSource && called;
|
|
183
|
-
return this.registry.isListed(this.requestContexts.getStore() ?? ctx, current, {
|
|
184
|
-
includeDisabled: called,
|
|
528
|
+
if (decision === 'decline') {
|
|
529
|
+
const transitioned = await (0, write_confirmation_1.transitionConfirmationReceipt)(tx, {
|
|
530
|
+
operationId: receipt.operationId,
|
|
531
|
+
nextStatus: 'declined',
|
|
185
532
|
});
|
|
186
|
-
|
|
533
|
+
return { kind: 'declined', transitioned, correlationId: receipt.correlationId };
|
|
534
|
+
}
|
|
535
|
+
if (decision === 'cancel') {
|
|
536
|
+
const transitioned = await (0, write_confirmation_1.transitionConfirmationReceipt)(tx, {
|
|
537
|
+
operationId: receipt.operationId,
|
|
538
|
+
nextStatus: 'cancelled',
|
|
539
|
+
});
|
|
540
|
+
return { kind: 'cancelled', transitioned, correlationId: receipt.correlationId };
|
|
541
|
+
}
|
|
542
|
+
// Accept: re-check token exp, admin auth age, and Step 5 locks & authorization at current time.
|
|
543
|
+
const nowSeconds = Math.floor(nowMs / 1000);
|
|
544
|
+
// Fail closed: a context without the token expiry cannot prove the token is still valid.
|
|
545
|
+
if (requestCtx.tokenExp === undefined || nowSeconds > requestCtx.tokenExp) {
|
|
546
|
+
throw new server_1.ProtocolError(-32091, 'Authorization stale', { code: 'authorization_stale' });
|
|
547
|
+
}
|
|
548
|
+
if (requestCtx.kind === 'admin') {
|
|
549
|
+
const maxAge = this.deployment?.mcp.admin.maxAuthAgeSeconds ?? DEFAULT_ADMIN_MAX_AUTH_AGE_SECONDS;
|
|
550
|
+
const authTimeValid = requestCtx.mfa === true &&
|
|
551
|
+
typeof requestCtx.authTime === 'number' &&
|
|
552
|
+
Number.isInteger(requestCtx.authTime) &&
|
|
553
|
+
requestCtx.authTime <= nowSeconds &&
|
|
554
|
+
nowSeconds - requestCtx.authTime <= maxAge;
|
|
555
|
+
if (!authTimeValid) {
|
|
556
|
+
throw new server_1.ProtocolError(-32091, 'Authorization stale', {
|
|
557
|
+
code: 'authorization_stale',
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
const txCheck = await this.authorizer.authorizeWriteInTransaction({ actor, command }, tx);
|
|
562
|
+
if (!txCheck.ok) {
|
|
563
|
+
if (txCheck.code === 'lock_timeout') {
|
|
564
|
+
throw new server_1.ProtocolError(-32090, 'Lock timeout', { code: 'lock_timeout' });
|
|
565
|
+
}
|
|
566
|
+
if (txCheck.code === 'authorization_stale') {
|
|
567
|
+
throw new server_1.ProtocolError(-32091, 'Authorization stale', {
|
|
568
|
+
code: 'authorization_stale',
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
throw toolUnavailableError();
|
|
572
|
+
}
|
|
573
|
+
const handlerResult = await command.handler(actor, parsed.data, tx);
|
|
574
|
+
const transitioned = await (0, write_confirmation_1.transitionConfirmationReceipt)(tx, {
|
|
575
|
+
operationId: receipt.operationId,
|
|
576
|
+
nextStatus: 'committed',
|
|
577
|
+
resultJson: handlerResult ?? null,
|
|
578
|
+
});
|
|
579
|
+
if (!transitioned) {
|
|
580
|
+
throw new Error('Confirmation receipt was not in pending state during commit');
|
|
581
|
+
}
|
|
582
|
+
return {
|
|
583
|
+
kind: 'committed',
|
|
584
|
+
correlationId: receipt.correlationId,
|
|
585
|
+
result: handlerResult,
|
|
586
|
+
};
|
|
587
|
+
}, { isolationLevel: 'ReadCommitted' });
|
|
588
|
+
}
|
|
589
|
+
catch (err) {
|
|
590
|
+
if (err instanceof server_1.ProtocolError) {
|
|
591
|
+
if (err.code === -32090 ||
|
|
592
|
+
err.code === -32091 ||
|
|
593
|
+
err.code === server_1.ProtocolErrorCode.InvalidParams) {
|
|
594
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
595
|
+
event: 'confirmation_authz_denied',
|
|
596
|
+
correlationId: decodedPayload.operationId,
|
|
597
|
+
operationId: decodedPayload.operationId,
|
|
598
|
+
resource: requestCtx.resource,
|
|
599
|
+
issuer: requestCtx.issuer,
|
|
600
|
+
subject: requestCtx.sub,
|
|
601
|
+
actingUserId: requestCtx.actingUserId,
|
|
602
|
+
clientId: requestCtx.clientId,
|
|
603
|
+
toolName: command.name,
|
|
604
|
+
resultCode: typeof err.data?.code === 'string'
|
|
605
|
+
? err.data.code
|
|
606
|
+
: String(err.code),
|
|
607
|
+
workflowId: requestCtx.workflowId,
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
throw err;
|
|
611
|
+
}
|
|
612
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
613
|
+
event: 'confirmation_write_failed',
|
|
614
|
+
correlationId: decodedPayload.operationId,
|
|
615
|
+
operationId: decodedPayload.operationId,
|
|
616
|
+
resource: requestCtx.resource,
|
|
617
|
+
issuer: requestCtx.issuer,
|
|
618
|
+
subject: requestCtx.sub,
|
|
619
|
+
actingUserId: requestCtx.actingUserId,
|
|
620
|
+
clientId: requestCtx.clientId,
|
|
621
|
+
toolName: command.name,
|
|
622
|
+
resultCode: err instanceof commands_1.CommandToolError ? 'command_tool_error' : 'internal_error',
|
|
623
|
+
workflowId: requestCtx.workflowId,
|
|
187
624
|
});
|
|
625
|
+
return this.handleToolExecutionError(command.name, err);
|
|
188
626
|
}
|
|
189
|
-
|
|
627
|
+
switch (outcome.kind) {
|
|
628
|
+
case 'not_found':
|
|
629
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {
|
|
630
|
+
reason: 'invalid_request_state',
|
|
631
|
+
});
|
|
632
|
+
case 'binding_mismatch':
|
|
633
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
634
|
+
event: 'confirmation_binding_rejected',
|
|
635
|
+
correlationId: outcome.correlationId,
|
|
636
|
+
operationId: decodedPayload.operationId,
|
|
637
|
+
resource: requestCtx.resource,
|
|
638
|
+
issuer: requestCtx.issuer,
|
|
639
|
+
subject: requestCtx.sub,
|
|
640
|
+
actingUserId: requestCtx.actingUserId,
|
|
641
|
+
clientId: requestCtx.clientId,
|
|
642
|
+
toolName: command.name,
|
|
643
|
+
resultCode: 'binding_mismatch',
|
|
644
|
+
workflowId: requestCtx.workflowId,
|
|
645
|
+
});
|
|
646
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {
|
|
647
|
+
reason: 'invalid_request_state',
|
|
648
|
+
});
|
|
649
|
+
case 'replay':
|
|
650
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
651
|
+
event: 'confirmation_replayed',
|
|
652
|
+
correlationId: outcome.correlationId,
|
|
653
|
+
operationId: decodedPayload.operationId,
|
|
654
|
+
resource: requestCtx.resource,
|
|
655
|
+
issuer: requestCtx.issuer,
|
|
656
|
+
subject: requestCtx.sub,
|
|
657
|
+
actingUserId: requestCtx.actingUserId,
|
|
658
|
+
clientId: requestCtx.clientId,
|
|
659
|
+
toolName: command.name,
|
|
660
|
+
resultCode: 'replayed',
|
|
661
|
+
workflowId: requestCtx.workflowId,
|
|
662
|
+
});
|
|
663
|
+
return formatToolSuccess(outcome.result === null ? undefined : outcome.result);
|
|
664
|
+
case 'already_finalized':
|
|
665
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, `Confirmation already ${outcome.status}`, { code: `confirmation_${outcome.status}` });
|
|
666
|
+
case 'expired':
|
|
667
|
+
if (outcome.transitioned) {
|
|
668
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
669
|
+
event: 'confirmation_expired',
|
|
670
|
+
correlationId: outcome.correlationId,
|
|
671
|
+
operationId: decodedPayload.operationId,
|
|
672
|
+
resource: requestCtx.resource,
|
|
673
|
+
issuer: requestCtx.issuer,
|
|
674
|
+
subject: requestCtx.sub,
|
|
675
|
+
actingUserId: requestCtx.actingUserId,
|
|
676
|
+
clientId: requestCtx.clientId,
|
|
677
|
+
toolName: command.name,
|
|
678
|
+
resultCode: 'expired',
|
|
679
|
+
workflowId: requestCtx.workflowId,
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
throw new server_1.ProtocolError(server_1.ProtocolErrorCode.InvalidParams, 'Confirmation expired', {
|
|
683
|
+
code: 'confirmation_expired',
|
|
684
|
+
});
|
|
685
|
+
case 'declined':
|
|
686
|
+
if (outcome.transitioned) {
|
|
687
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
688
|
+
event: 'confirmation_declined',
|
|
689
|
+
correlationId: outcome.correlationId,
|
|
690
|
+
operationId: decodedPayload.operationId,
|
|
691
|
+
resource: requestCtx.resource,
|
|
692
|
+
issuer: requestCtx.issuer,
|
|
693
|
+
subject: requestCtx.sub,
|
|
694
|
+
actingUserId: requestCtx.actingUserId,
|
|
695
|
+
clientId: requestCtx.clientId,
|
|
696
|
+
toolName: command.name,
|
|
697
|
+
resultCode: 'declined',
|
|
698
|
+
workflowId: requestCtx.workflowId,
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
return {
|
|
702
|
+
isError: true,
|
|
703
|
+
content: [
|
|
704
|
+
{
|
|
705
|
+
type: 'text',
|
|
706
|
+
text: JSON.stringify({
|
|
707
|
+
ok: false,
|
|
708
|
+
status: 'declined',
|
|
709
|
+
operationId: decodedPayload.operationId,
|
|
710
|
+
}),
|
|
711
|
+
},
|
|
712
|
+
],
|
|
713
|
+
};
|
|
714
|
+
case 'cancelled':
|
|
715
|
+
if (outcome.transitioned) {
|
|
716
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
717
|
+
event: 'confirmation_cancelled',
|
|
718
|
+
correlationId: outcome.correlationId,
|
|
719
|
+
operationId: decodedPayload.operationId,
|
|
720
|
+
resource: requestCtx.resource,
|
|
721
|
+
issuer: requestCtx.issuer,
|
|
722
|
+
subject: requestCtx.sub,
|
|
723
|
+
actingUserId: requestCtx.actingUserId,
|
|
724
|
+
clientId: requestCtx.clientId,
|
|
725
|
+
toolName: command.name,
|
|
726
|
+
resultCode: 'cancelled',
|
|
727
|
+
workflowId: requestCtx.workflowId,
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
return {
|
|
731
|
+
isError: true,
|
|
732
|
+
content: [
|
|
733
|
+
{
|
|
734
|
+
type: 'text',
|
|
735
|
+
text: JSON.stringify({
|
|
736
|
+
ok: false,
|
|
737
|
+
status: 'cancelled',
|
|
738
|
+
operationId: decodedPayload.operationId,
|
|
739
|
+
}),
|
|
740
|
+
},
|
|
741
|
+
],
|
|
742
|
+
};
|
|
743
|
+
case 'committed':
|
|
744
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
745
|
+
event: 'confirmation_accepted',
|
|
746
|
+
correlationId: outcome.correlationId,
|
|
747
|
+
operationId: decodedPayload.operationId,
|
|
748
|
+
resource: requestCtx.resource,
|
|
749
|
+
issuer: requestCtx.issuer,
|
|
750
|
+
subject: requestCtx.sub,
|
|
751
|
+
actingUserId: requestCtx.actingUserId,
|
|
752
|
+
clientId: requestCtx.clientId,
|
|
753
|
+
toolName: command.name,
|
|
754
|
+
resultCode: 'accepted',
|
|
755
|
+
workflowId: requestCtx.workflowId,
|
|
756
|
+
});
|
|
757
|
+
(0, write_confirmation_1.emitConfirmationAuditEvent)(this.logger, {
|
|
758
|
+
event: 'confirmation_write_succeeded',
|
|
759
|
+
correlationId: outcome.correlationId,
|
|
760
|
+
operationId: decodedPayload.operationId,
|
|
761
|
+
resource: requestCtx.resource,
|
|
762
|
+
issuer: requestCtx.issuer,
|
|
763
|
+
subject: requestCtx.sub,
|
|
764
|
+
actingUserId: requestCtx.actingUserId,
|
|
765
|
+
clientId: requestCtx.clientId,
|
|
766
|
+
toolName: command.name,
|
|
767
|
+
resultCode: 'committed',
|
|
768
|
+
workflowId: requestCtx.workflowId,
|
|
769
|
+
});
|
|
770
|
+
return formatToolSuccess(outcome.result);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
handleToolExecutionError(toolName, err) {
|
|
774
|
+
if (err instanceof server_1.ProtocolError) {
|
|
775
|
+
throw err;
|
|
776
|
+
}
|
|
777
|
+
if (err instanceof commands_1.CommandToolError) {
|
|
778
|
+
const text = JSON.stringify(err.payload) ?? 'null';
|
|
779
|
+
return {
|
|
780
|
+
isError: true,
|
|
781
|
+
content: [{ type: 'text', text }],
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
785
|
+
// Never log raw input arguments on unexpected errors.
|
|
786
|
+
this.logger.error(`Tool ${toolName} threw: ${msg}`, err instanceof Error ? err.stack : undefined);
|
|
787
|
+
return {
|
|
788
|
+
isError: true,
|
|
789
|
+
content: [{ type: 'text', text: 'Tool execution failed' }],
|
|
790
|
+
};
|
|
791
|
+
}
|
|
792
|
+
resolveCommand(calledName, surface) {
|
|
793
|
+
if (!calledName)
|
|
794
|
+
return undefined;
|
|
795
|
+
const direct = this.commands.get(calledName, surface);
|
|
796
|
+
if (direct)
|
|
797
|
+
return direct;
|
|
798
|
+
const aliasPrefix = (0, mcp_tool_registry_1.getToolAliasPrefix)();
|
|
799
|
+
if (aliasPrefix && calledName.startsWith(`${aliasPrefix}_`)) {
|
|
800
|
+
return this.commands.get(calledName.slice(aliasPrefix.length + 1), surface);
|
|
801
|
+
}
|
|
802
|
+
return undefined;
|
|
803
|
+
}
|
|
804
|
+
async buildActor(requestCtx) {
|
|
805
|
+
const surface = requestCtx.kind === 'admin' ? 'mcp-admin' : 'mcp';
|
|
806
|
+
const principalKind = requestCtx.kind === 'admin' ? 'oauth-admin' : 'oauth-employee';
|
|
807
|
+
const localUser = this.identityStore && requestCtx.actingUserId.length > 0
|
|
808
|
+
? await this.identityStore.findById(requestCtx.actingUserId)
|
|
809
|
+
: null;
|
|
810
|
+
return {
|
|
811
|
+
surface,
|
|
812
|
+
principalKind,
|
|
813
|
+
issuer: requestCtx.issuer,
|
|
814
|
+
subject: requestCtx.sub,
|
|
815
|
+
actingUserId: requestCtx.actingUserId,
|
|
816
|
+
isServiceAccount: localUser ? localUser.isServiceAccount : false,
|
|
817
|
+
isActive: localUser ? localUser.isActive : false,
|
|
818
|
+
scopes: requestCtx.scopes,
|
|
819
|
+
...(requestCtx.kind === 'admin'
|
|
820
|
+
? { mfaVerified: requestCtx.mfa, authTime: requestCtx.authTime }
|
|
821
|
+
: {}),
|
|
822
|
+
};
|
|
190
823
|
}
|
|
191
824
|
};
|
|
192
825
|
exports.McpService = McpService;
|
|
193
826
|
exports.McpService = McpService = McpService_1 = __decorate([
|
|
194
827
|
(0, common_1.Injectable)(),
|
|
195
|
-
|
|
828
|
+
__param(1, (0, common_1.Optional)()),
|
|
829
|
+
__param(1, (0, common_1.Inject)(types_1.MCP_COMMANDS_OPTIONS)),
|
|
830
|
+
__param(2, (0, common_1.Optional)()),
|
|
831
|
+
__param(2, (0, common_1.Inject)(plugin_api_1.RBAC_POLICY)),
|
|
832
|
+
__param(3, (0, common_1.Optional)()),
|
|
833
|
+
__param(3, (0, common_1.Inject)(plugin_api_1.IDENTITY_STORE)),
|
|
834
|
+
__param(4, (0, common_1.Optional)()),
|
|
835
|
+
__param(4, (0, common_1.Inject)(plugin_api_1.PRISMA)),
|
|
836
|
+
__param(5, (0, common_1.Optional)()),
|
|
837
|
+
__param(5, (0, common_1.Inject)(deployment_config_1.MCP_DEPLOYMENT_CONFIG)),
|
|
838
|
+
__param(6, (0, common_1.Optional)()),
|
|
839
|
+
__param(6, (0, common_1.Inject)(enabled_resources_1.McpEnabledResources)),
|
|
840
|
+
__metadata("design:paramtypes", [mcp_tool_registry_1.McpToolRegistry, Object, Object, Object, Object, Object, enabled_resources_1.McpEnabledResources])
|
|
196
841
|
], McpService);
|
|
197
842
|
function readMcpCallContext(authInfo) {
|
|
198
843
|
const value = authInfo?.extra?.mcpCallContext;
|
|
199
844
|
if (!value || typeof value !== 'object')
|
|
200
845
|
return undefined;
|
|
201
846
|
const candidate = value;
|
|
202
|
-
if (
|
|
203
|
-
|
|
204
|
-
typeof candidate.isApiKey !== 'boolean' ||
|
|
205
|
-
!Array.isArray(candidate.roleNames) ||
|
|
206
|
-
!candidate.roleNames.every((role) => typeof role === 'string') ||
|
|
847
|
+
if ((candidate.kind !== 'employee' && candidate.kind !== 'admin') ||
|
|
848
|
+
typeof candidate.issuer !== 'string' ||
|
|
207
849
|
typeof candidate.sub !== 'string' ||
|
|
208
|
-
|
|
209
|
-
|
|
850
|
+
typeof candidate.actingUserId !== 'string' ||
|
|
851
|
+
(candidate.actingUserEmail !== undefined && typeof candidate.actingUserEmail !== 'string') ||
|
|
852
|
+
typeof candidate.resource !== 'string' ||
|
|
853
|
+
typeof candidate.clientId !== 'string' ||
|
|
854
|
+
!(candidate.authTime === null || typeof candidate.authTime === 'number') ||
|
|
855
|
+
typeof candidate.mfa !== 'boolean' ||
|
|
856
|
+
!Array.isArray(candidate.scopes) ||
|
|
857
|
+
!candidate.scopes.every((scope) => typeof scope === 'string') ||
|
|
858
|
+
(candidate.tokenExp !== undefined && typeof candidate.tokenExp !== 'number') ||
|
|
210
859
|
!('workflowId' in candidate) ||
|
|
211
860
|
!(candidate.workflowId === null || typeof candidate.workflowId === 'string')) {
|
|
212
861
|
return undefined;
|
|
213
862
|
}
|
|
214
863
|
return candidate;
|
|
215
864
|
}
|
|
216
|
-
|
|
217
|
-
|
|
865
|
+
function formatToolSuccess(result) {
|
|
866
|
+
const text = result === undefined ? '' : (JSON.stringify(result) ?? String(result));
|
|
218
867
|
return {
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
{
|
|
222
|
-
type: 'text',
|
|
223
|
-
text: JSON.stringify({
|
|
224
|
-
code: mcp_tool_registry_1.MCP_TOOL_DISABLED,
|
|
225
|
-
message: `Tool ${name} is disabled by an administrator`,
|
|
226
|
-
}),
|
|
227
|
-
},
|
|
228
|
-
],
|
|
229
|
-
};
|
|
230
|
-
}
|
|
231
|
-
/** The tool a single JSON-RPC tools/call targets, read from the parsed body or a body clone. */
|
|
232
|
-
async function calledToolName(request, parsedBody) {
|
|
233
|
-
let body = parsedBody;
|
|
234
|
-
if (body === undefined) {
|
|
235
|
-
if (request.method.toUpperCase() !== 'POST')
|
|
236
|
-
return undefined;
|
|
237
|
-
try {
|
|
238
|
-
body = await request.clone().json();
|
|
239
|
-
}
|
|
240
|
-
catch {
|
|
241
|
-
return undefined;
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
if (!body || typeof body !== 'object' || Array.isArray(body))
|
|
245
|
-
return undefined;
|
|
246
|
-
const message = body;
|
|
247
|
-
return message.method === 'tools/call' && typeof message.params?.name === 'string'
|
|
248
|
-
? message.params.name
|
|
249
|
-
: undefined;
|
|
250
|
-
}
|
|
251
|
-
function readPositiveInteger(variableName) {
|
|
252
|
-
const raw = process.env[variableName];
|
|
253
|
-
if (!raw)
|
|
254
|
-
return undefined;
|
|
255
|
-
const value = Number(raw);
|
|
256
|
-
return Number.isSafeInteger(value) && value > 0 ? value : undefined;
|
|
257
|
-
}
|
|
258
|
-
function buildMrtrContext(requestStateCodec, sdkCtx) {
|
|
259
|
-
// Already verified by the SDK (via the `requestState.verify` hook passed to McpServer)
|
|
260
|
-
// before this handler runs -- reading it here never re-checks integrity, it just reads
|
|
261
|
-
// the hook's decoded result. undefined when this call carried no requestState at all.
|
|
262
|
-
const resumedPayload = sdkCtx.mcpReq.requestState();
|
|
263
|
-
return {
|
|
264
|
-
resumed: resumedPayload !== undefined
|
|
265
|
-
? {
|
|
266
|
-
data: resumedPayload.data,
|
|
267
|
-
round: resumedPayload.round,
|
|
268
|
-
inputResponses: sdkCtx.mcpReq.inputResponses ?? {},
|
|
269
|
-
}
|
|
270
|
-
: undefined,
|
|
271
|
-
async requestInput(inputRequests, data) {
|
|
272
|
-
if (!requestStateCodec) {
|
|
273
|
-
throw new Error('ctx.mrtr.requestInput requires MCP_REQUEST_STATE_KEY to be configured for this app');
|
|
274
|
-
}
|
|
275
|
-
const requestState = resumedPayload !== undefined
|
|
276
|
-
? await requestStateCodec.mintNextRound(data, resumedPayload.round, sdkCtx)
|
|
277
|
-
: await requestStateCodec.mint(data, sdkCtx);
|
|
278
|
-
return { resultType: 'input_required', inputRequests, requestState };
|
|
279
|
-
},
|
|
868
|
+
content: [{ type: 'text', text }],
|
|
869
|
+
...(result !== undefined ? { structuredContent: result } : {}),
|
|
280
870
|
};
|
|
281
871
|
}
|
|
282
872
|
//# sourceMappingURL=mcp.service.js.map
|