@haneinfo/mcp-server 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.
Files changed (49) hide show
  1. package/LICENSE +14 -0
  2. package/dist/discovery-push.service.d.ts +18 -0
  3. package/dist/discovery-push.service.d.ts.map +1 -0
  4. package/dist/discovery-push.service.js +66 -0
  5. package/dist/discovery-push.service.js.map +1 -0
  6. package/dist/index.d.ts +10 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +28 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/mcp-tool.decorator.d.ts +17 -0
  11. package/dist/mcp-tool.decorator.d.ts.map +1 -0
  12. package/dist/mcp-tool.decorator.js +35 -0
  13. package/dist/mcp-tool.decorator.js.map +1 -0
  14. package/dist/mcp-tool.registry.d.ts +37 -0
  15. package/dist/mcp-tool.registry.d.ts.map +1 -0
  16. package/dist/mcp-tool.registry.js +189 -0
  17. package/dist/mcp-tool.registry.js.map +1 -0
  18. package/dist/mcp.controller.d.ts +16 -0
  19. package/dist/mcp.controller.d.ts.map +1 -0
  20. package/dist/mcp.controller.js +115 -0
  21. package/dist/mcp.controller.js.map +1 -0
  22. package/dist/mcp.module.d.ts +9 -0
  23. package/dist/mcp.module.d.ts.map +1 -0
  24. package/dist/mcp.module.js +39 -0
  25. package/dist/mcp.module.js.map +1 -0
  26. package/dist/mcp.service.d.ts +22 -0
  27. package/dist/mcp.service.d.ts.map +1 -0
  28. package/dist/mcp.service.js +174 -0
  29. package/dist/mcp.service.js.map +1 -0
  30. package/dist/plugin.d.ts +14 -0
  31. package/dist/plugin.d.ts.map +1 -0
  32. package/dist/plugin.js +62 -0
  33. package/dist/plugin.js.map +1 -0
  34. package/dist/request-state.d.ts +41 -0
  35. package/dist/request-state.d.ts.map +1 -0
  36. package/dist/request-state.js +58 -0
  37. package/dist/request-state.js.map +1 -0
  38. package/dist/stateful-mcp-handler.d.ts +19 -0
  39. package/dist/stateful-mcp-handler.d.ts.map +1 -0
  40. package/dist/stateful-mcp-handler.js +159 -0
  41. package/dist/stateful-mcp-handler.js.map +1 -0
  42. package/dist/types.d.ts +32 -0
  43. package/dist/types.d.ts.map +1 -0
  44. package/dist/types.js +3 -0
  45. package/dist/types.js.map +1 -0
  46. package/haneinfo.plugin.json +37 -0
  47. package/package.json +66 -0
  48. package/plugin.d.ts +3 -0
  49. package/plugin.js +4 -0
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.McpModule = void 0;
10
+ const plugin_api_1 = require("@haneinfo/plugin-api");
11
+ const plugin_host_nest_1 = require("@haneinfo/plugin-host-nest");
12
+ const common_1 = require("@nestjs/common");
13
+ const discovery_push_service_1 = require("./discovery-push.service");
14
+ const mcp_controller_1 = require("./mcp.controller");
15
+ const mcp_service_1 = require("./mcp.service");
16
+ const mcp_tool_registry_1 = require("./mcp-tool.registry");
17
+ /**
18
+ * Model Context Protocol Server capability module (051 PL4-06).
19
+ *
20
+ * The module is deliberately scoped. Feature modules that inject `McpToolRegistry` must import it
21
+ * explicitly or import a generated plugin composition module that exports it.
22
+ */
23
+ let McpModule = class McpModule {
24
+ };
25
+ exports.McpModule = McpModule;
26
+ exports.McpModule = McpModule = __decorate([
27
+ (0, common_1.Module)({
28
+ imports: [plugin_host_nest_1.HaneinfoAuthInfrastructureModule],
29
+ controllers: [mcp_controller_1.McpController],
30
+ providers: [
31
+ mcp_service_1.McpService,
32
+ mcp_tool_registry_1.McpToolRegistry,
33
+ discovery_push_service_1.DiscoveryPushService,
34
+ { provide: plugin_api_1.MCP_TOOLS, useExisting: mcp_tool_registry_1.McpToolRegistry },
35
+ ],
36
+ exports: [mcp_service_1.McpService, mcp_tool_registry_1.McpToolRegistry, discovery_push_service_1.DiscoveryPushService, plugin_api_1.MCP_TOOLS],
37
+ })
38
+ ], McpModule);
39
+ //# sourceMappingURL=mcp.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.module.js","sourceRoot":"","sources":["../src/mcp.module.ts"],"names":[],"mappings":";;;;;;;;;AAAA,qDAAiD;AACjD,iEAA8E;AAC9E,2CAAwC;AACxC,qEAAgE;AAChE,qDAAiD;AACjD,+CAA2C;AAC3C,2DAAsD;AAEtD;;;;;GAKG;AAYI,IAAM,SAAS,GAAf,MAAM,SAAS;CAAG,CAAA;AAAZ,8BAAS;oBAAT,SAAS;IAXrB,IAAA,eAAM,EAAC;QACN,OAAO,EAAE,CAAC,mDAAgC,CAAC;QAC3C,WAAW,EAAE,CAAC,8BAAa,CAAC;QAC5B,SAAS,EAAE;YACT,wBAAU;YACV,mCAAe;YACf,6CAAoB;YACpB,EAAE,OAAO,EAAE,sBAAS,EAAE,WAAW,EAAE,mCAAe,EAAE;SACrD;QACD,OAAO,EAAE,CAAC,wBAAU,EAAE,mCAAe,EAAE,6CAAoB,EAAE,sBAAS,CAAC;KACxE,CAAC;GACW,SAAS,CAAG"}
@@ -0,0 +1,22 @@
1
+ import type { McpHttpHandler } from '@modelcontextprotocol/server';
2
+ import { McpServer } from '@modelcontextprotocol/server';
3
+ import { type OnModuleDestroy } from '@nestjs/common';
4
+ import { McpToolRegistry } from './mcp-tool.registry';
5
+ import type { McpCallContext } from './types';
6
+ export declare class McpService implements OnModuleDestroy {
7
+ private readonly registry;
8
+ private readonly logger;
9
+ private readonly requestStateKey;
10
+ private sharedHandler;
11
+ constructor(registry: McpToolRegistry);
12
+ /** Returns the application-wide handler used by HTTP controllers. */
13
+ getHandler(): McpHttpHandler;
14
+ /**
15
+ * Creates an independently owned handler. The fallback context is kept for direct and
16
+ * transport-neutral callers; HTTP controllers pass the current context in AuthInfo.extra.
17
+ */
18
+ createHandler(fallbackCtx?: McpCallContext): McpHttpHandler;
19
+ onModuleDestroy(): Promise<void>;
20
+ createServer(ctx: McpCallContext): McpServer;
21
+ }
22
+ //# sourceMappingURL=mcp.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.service.d.ts","sourceRoot":"","sources":["../src/mcp.service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,cAAc,EAGf,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAyB,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAChF,OAAO,EAAsB,KAAK,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC1E,OAAO,EAA0B,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAQ9E,OAAO,KAAK,EAAE,cAAc,EAA4C,MAAM,SAAS,CAAC;AAExF,qBACa,UAAW,YAAW,eAAe;IASpC,OAAO,CAAC,QAAQ,CAAC,QAAQ;IARrC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA+B;IAKtD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAyB;IACzD,OAAO,CAAC,aAAa,CAA6B;gBAErB,QAAQ,EAAE,eAAe;IAItD,qEAAqE;IACrE,UAAU,IAAI,cAAc;IAK5B;;;OAGG;IACH,aAAa,CAAC,WAAW,CAAC,EAAE,cAAc,GAAG,cAAc;IAmBrD,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtC,YAAY,CAAC,GAAG,EAAE,cAAc,GAAG,SAAS;CA+E7C"}
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var McpService_1;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.McpService = void 0;
14
+ const server_1 = require("@modelcontextprotocol/server");
15
+ const common_1 = require("@nestjs/common");
16
+ const mcp_tool_registry_1 = require("./mcp-tool.registry");
17
+ const request_state_1 = require("./request-state");
18
+ const stateful_mcp_handler_1 = require("./stateful-mcp-handler");
19
+ let McpService = McpService_1 = class McpService {
20
+ constructor(registry) {
21
+ this.registry = registry;
22
+ this.logger = new common_1.Logger(McpService_1.name);
23
+ this.requestStateKey = (0, request_state_1.readMcpRequestStateKey)();
24
+ }
25
+ /** Returns the application-wide handler used by HTTP controllers. */
26
+ getHandler() {
27
+ this.sharedHandler ??= this.createHandler();
28
+ return this.sharedHandler;
29
+ }
30
+ /**
31
+ * Creates an independently owned handler. The fallback context is kept for direct and
32
+ * transport-neutral callers; HTTP controllers pass the current context in AuthInfo.extra.
33
+ */
34
+ createHandler(fallbackCtx) {
35
+ const resolveContext = (requestContext) => {
36
+ const ctx = readMcpCallContext(requestContext.authInfo) ?? fallbackCtx;
37
+ if (!ctx)
38
+ throw new Error('MCP call context is missing from validated authentication info');
39
+ return ctx;
40
+ };
41
+ return (0, stateful_mcp_handler_1.createStatefulMcpHandler)((requestContext) => this.createServer(resolveContext(requestContext)), {
42
+ principalKey: (requestOptions) => readMcpCallContext(requestOptions?.authInfo)?.sub ?? fallbackCtx?.sub,
43
+ maxLegacySessions: readPositiveInteger('MCP_MAX_LEGACY_SESSIONS'),
44
+ legacySessionIdleTtlMs: readPositiveInteger('MCP_LEGACY_SESSION_IDLE_TTL_MS'),
45
+ onerror: (error) => this.logger.error(error.message, error.stack),
46
+ });
47
+ }
48
+ async onModuleDestroy() {
49
+ const handler = this.sharedHandler;
50
+ this.sharedHandler = undefined;
51
+ await handler?.close();
52
+ }
53
+ createServer(ctx) {
54
+ const requestStateCodec = this.requestStateKey
55
+ ? (0, request_state_1.createMcpRequestStateStore)({ key: this.requestStateKey, principal: ctx.sub })
56
+ : undefined;
57
+ const server = new server_1.McpServer({
58
+ name: process.env.npm_package_name ?? 'haneinfo-app',
59
+ version: process.env.npm_package_version ?? '1.0.0',
60
+ }, requestStateCodec
61
+ ? {
62
+ requestState: { verify: (state, sdkCtx) => requestStateCodec.verify(state, sdkCtx) },
63
+ inputRequired: { maxRounds: requestStateCodec.maxRounds },
64
+ }
65
+ : undefined);
66
+ const tools = this.registry.listTools(ctx);
67
+ for (const tool of tools) {
68
+ server.registerTool(tool.name, {
69
+ description: tool.description,
70
+ inputSchema: tool.inputSchema,
71
+ outputSchema: tool.outputSchema,
72
+ // Derived from `requiredScopes` at listing time, not hand-set per app (dev_docs 002
73
+ // "scope action read/write classification rules", dev_docs 023 §2.3/§6.4). This is the wire-format
74
+ // channel the AI Agent Team app's single-write-per-invocation check reads from
75
+ // (023 §3.5) — `requiredScopes` itself never leaves the server.
76
+ annotations: { readOnlyHint: (0, mcp_tool_registry_1.classifyToolAsReadOnly)(tool.requiredScopes) },
77
+ }, async (args, sdkCtx) => {
78
+ const requestCtx = readMcpCallContext(sdkCtx.http?.authInfo) ?? ctx;
79
+ const callCtx = {
80
+ ...requestCtx,
81
+ mrtr: buildMrtrContext(requestStateCodec, sdkCtx),
82
+ };
83
+ try {
84
+ const result = await tool.handler(args, callCtx);
85
+ // A handler that called `ctx.mrtr.requestInput(...)` returns the SDK's own
86
+ // input_required shape directly -- pass it straight through the wire, bypassing
87
+ // the content/structuredContent wrapping below (which is only for a completed
88
+ // result), same as the SDK's own tools/call handler does for this discriminator.
89
+ if ((0, server_1.isInputRequiredResult)(result))
90
+ return result;
91
+ // `structuredContent` is exposed for any serializable result (object, array, or
92
+ // primitive) -- not just plain objects. The v2 SDK's own wire codec
93
+ // (projectCallToolResult) wraps non-object structuredContent in `{ result: ... }`
94
+ // for eras that require it; restricting this to plain objects meant every tool
95
+ // declaring a non-object outputSchema (e.g. an array or string) failed
96
+ // `validateToolOutput`'s "no structured content was provided" check on every
97
+ // successful call.
98
+ const text = result === undefined ? '' : (JSON.stringify(result) ?? String(result));
99
+ return {
100
+ content: [{ type: 'text', text }],
101
+ ...(result !== undefined && result !== null ? { structuredContent: result } : {}),
102
+ };
103
+ }
104
+ catch (err) {
105
+ const msg = err instanceof Error ? err.message : String(err);
106
+ // The caller-facing message is unchanged here (many tools intentionally throw a
107
+ // descriptive validation error that the calling agent needs to see); what was
108
+ // missing is that this failure was otherwise invisible server-side, so an infra
109
+ // error (a stack trace, a DB host/user) reached an external API-key holder while
110
+ // this app's own logs and alerting never saw it at all.
111
+ this.logger.error(`Tool ${tool.name} threw: ${msg}`, err instanceof Error ? err.stack : undefined);
112
+ return { isError: true, content: [{ type: 'text', text: msg }] };
113
+ }
114
+ });
115
+ }
116
+ return server;
117
+ }
118
+ };
119
+ exports.McpService = McpService;
120
+ exports.McpService = McpService = McpService_1 = __decorate([
121
+ (0, common_1.Injectable)(),
122
+ __metadata("design:paramtypes", [mcp_tool_registry_1.McpToolRegistry])
123
+ ], McpService);
124
+ function readMcpCallContext(authInfo) {
125
+ const value = authInfo?.extra?.mcpCallContext;
126
+ if (!value || typeof value !== 'object')
127
+ return undefined;
128
+ const candidate = value;
129
+ if (!Array.isArray(candidate.scopes) ||
130
+ !candidate.scopes.every((scope) => typeof scope === 'string') ||
131
+ typeof candidate.isApiKey !== 'boolean' ||
132
+ !Array.isArray(candidate.roleNames) ||
133
+ !candidate.roleNames.every((role) => typeof role === 'string') ||
134
+ typeof candidate.sub !== 'string' ||
135
+ !('actingUserId' in candidate) ||
136
+ !(candidate.actingUserId === null || typeof candidate.actingUserId === 'string') ||
137
+ !('workflowId' in candidate) ||
138
+ !(candidate.workflowId === null || typeof candidate.workflowId === 'string')) {
139
+ return undefined;
140
+ }
141
+ return candidate;
142
+ }
143
+ function readPositiveInteger(variableName) {
144
+ const raw = process.env[variableName];
145
+ if (!raw)
146
+ return undefined;
147
+ const value = Number(raw);
148
+ return Number.isSafeInteger(value) && value > 0 ? value : undefined;
149
+ }
150
+ function buildMrtrContext(requestStateCodec, sdkCtx) {
151
+ // Already verified by the SDK (via the `requestState.verify` hook passed to McpServer)
152
+ // before this handler runs -- reading it here never re-checks integrity, it just reads
153
+ // the hook's decoded result. undefined when this call carried no requestState at all.
154
+ const resumedPayload = sdkCtx.mcpReq.requestState();
155
+ return {
156
+ resumed: resumedPayload !== undefined
157
+ ? {
158
+ data: resumedPayload.data,
159
+ round: resumedPayload.round,
160
+ inputResponses: sdkCtx.mcpReq.inputResponses ?? {},
161
+ }
162
+ : undefined,
163
+ async requestInput(inputRequests, data) {
164
+ if (!requestStateCodec) {
165
+ throw new Error('ctx.mrtr.requestInput requires MCP_REQUEST_STATE_KEY to be configured for this app');
166
+ }
167
+ const requestState = resumedPayload !== undefined
168
+ ? await requestStateCodec.mintNextRound(data, resumedPayload.round, sdkCtx)
169
+ : await requestStateCodec.mint(data, sdkCtx);
170
+ return { resultType: 'input_required', inputRequests, requestState };
171
+ },
172
+ };
173
+ }
174
+ //# sourceMappingURL=mcp.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.service.js","sourceRoot":"","sources":["../src/mcp.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAMA,yDAAgF;AAChF,2CAA0E;AAC1E,2DAA8E;AAC9E,mDAKyB;AACzB,iEAAkE;AAI3D,IAAM,UAAU,kBAAhB,MAAM,UAAU;IASrB,YAA6B,QAAyB;QAAzB,aAAQ,GAAR,QAAQ,CAAiB;QARrC,WAAM,GAAG,IAAI,eAAM,CAAC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M,iBAAiB,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;YACjD,OAAO,EAAE,UAAU,EAAE,gBAAyB,EAAE,aAAa,EAAE,YAAY,EAAE,CAAC;QAChF,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `@haneinfo/mcp-server/plugin` — manifest and plugin descriptor (PL4-06).
3
+ */
4
+ import { MCP_TOOLS, type McpToolsPort, type PluginManifestV1 } from '@haneinfo/plugin-api';
5
+ import { McpModule } from './mcp.module';
6
+ import { McpService } from './mcp.service';
7
+ import { McpToolRegistry } from './mcp-tool.registry';
8
+ export { MCP_TOOLS, McpModule, McpService, McpToolRegistry, type McpToolsPort };
9
+ /** Mirrors `haneinfo.plugin.json`; `plugin.spec.ts` fails if the two drift apart. */
10
+ export declare const mcpServerManifest: PluginManifestV1;
11
+ export declare const mcpServerPlugin: import("@haneinfo/plugin-api").DefinedPlugin<unknown, typeof McpModule>;
12
+ export declare function mcpServer(): import("@haneinfo/plugin-api").DefinedPlugin<unknown, typeof McpModule>;
13
+ export default mcpServerPlugin;
14
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAEL,SAAS,EACT,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,eAAe,EAAE,KAAK,YAAY,EAAE,CAAC;AAEhF,qFAAqF;AACrF,eAAO,MAAM,iBAAiB,EAAE,gBAoC/B,CAAC;AAEF,eAAO,MAAM,eAAe,yEAG1B,CAAC;AAEH,wBAAgB,SAAS,4EAExB;AAED,eAAe,eAAe,CAAC"}
package/dist/plugin.js ADDED
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ /**
3
+ * `@haneinfo/mcp-server/plugin` — manifest and plugin descriptor (PL4-06).
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.mcpServerPlugin = exports.mcpServerManifest = exports.McpToolRegistry = exports.McpService = exports.McpModule = exports.MCP_TOOLS = void 0;
7
+ exports.mcpServer = mcpServer;
8
+ const plugin_api_1 = require("@haneinfo/plugin-api");
9
+ Object.defineProperty(exports, "MCP_TOOLS", { enumerable: true, get: function () { return plugin_api_1.MCP_TOOLS; } });
10
+ const mcp_module_1 = require("./mcp.module");
11
+ Object.defineProperty(exports, "McpModule", { enumerable: true, get: function () { return mcp_module_1.McpModule; } });
12
+ const mcp_service_1 = require("./mcp.service");
13
+ Object.defineProperty(exports, "McpService", { enumerable: true, get: function () { return mcp_service_1.McpService; } });
14
+ const mcp_tool_registry_1 = require("./mcp-tool.registry");
15
+ Object.defineProperty(exports, "McpToolRegistry", { enumerable: true, get: function () { return mcp_tool_registry_1.McpToolRegistry; } });
16
+ /** Mirrors `haneinfo.plugin.json`; `plugin.spec.ts` fails if the two drift apart. */
17
+ exports.mcpServerManifest = {
18
+ schemaVersion: 'haneinfo.plugin/v1',
19
+ id: 'mcp-server',
20
+ displayName: 'Model Context Protocol Server',
21
+ cardinality: 'singleton',
22
+ distribution: 'official',
23
+ engine: {
24
+ haneinfoPluginApi: '^1.0.0',
25
+ node: '>=22.0.0',
26
+ frameworks: {
27
+ '@nestjs/common': '^11.0.5',
28
+ '@nestjs/core': '^11.0.5',
29
+ '@prisma/client': '^6.2.0',
30
+ express: '^5.0.0',
31
+ zod: '^4.4.3',
32
+ },
33
+ },
34
+ provides: ['haneinfo.mcp-tools'],
35
+ requires: ['haneinfo.principal-context'],
36
+ optionalRequires: [
37
+ 'haneinfo.audit-sink',
38
+ 'haneinfo.machine-auth-provider',
39
+ 'haneinfo.scope-matcher',
40
+ ],
41
+ facets: {
42
+ backend: {
43
+ modulePath: './dist/mcp.module.js',
44
+ exportName: 'McpModule',
45
+ controllerRoutes: ['mcp'],
46
+ providerTokens: ['haneinfo.mcp-tools'],
47
+ },
48
+ operations: {
49
+ healthIndicatorId: 'mcp-server',
50
+ shutdownTimeoutMs: 5000,
51
+ },
52
+ },
53
+ };
54
+ exports.mcpServerPlugin = (0, plugin_api_1.definePlugin)({
55
+ manifest: exports.mcpServerManifest,
56
+ backend: () => mcp_module_1.McpModule,
57
+ });
58
+ function mcpServer() {
59
+ return exports.mcpServerPlugin;
60
+ }
61
+ exports.default = exports.mcpServerPlugin;
62
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AA0DH,8BAEC;AA1DD,qDAK8B;AAKrB,0FARP,sBAAS,OAQO;AAJlB,6CAAyC;AAIrB,0FAJX,sBAAS,OAIW;AAH7B,+CAA2C;AAGZ,2FAHtB,wBAAU,OAGsB;AAFzC,2DAAsD;AAEX,gGAFlC,mCAAe,OAEkC;AAE1D,qFAAqF;AACxE,QAAA,iBAAiB,GAAqB;IACjD,aAAa,EAAE,oBAAoB;IACnC,EAAE,EAAE,YAAY;IAChB,WAAW,EAAE,+BAA+B;IAC5C,WAAW,EAAE,WAAW;IACxB,YAAY,EAAE,UAAU;IACxB,MAAM,EAAE;QACN,iBAAiB,EAAE,QAAQ;QAC3B,IAAI,EAAE,UAAU;QAChB,UAAU,EAAE;YACV,gBAAgB,EAAE,SAAS;YAC3B,cAAc,EAAE,SAAS;YACzB,gBAAgB,EAAE,QAAQ;YAC1B,OAAO,EAAE,QAAQ;YACjB,GAAG,EAAE,QAAQ;SACd;KACF;IACD,QAAQ,EAAE,CAAC,oBAAoB,CAAC;IAChC,QAAQ,EAAE,CAAC,4BAA4B,CAAC;IACxC,gBAAgB,EAAE;QAChB,qBAAqB;QACrB,gCAAgC;QAChC,wBAAwB;KACzB;IACD,MAAM,EAAE;QACN,OAAO,EAAE;YACP,UAAU,EAAE,sBAAsB;YAClC,UAAU,EAAE,WAAW;YACvB,gBAAgB,EAAE,CAAC,KAAK,CAAC;YACzB,cAAc,EAAE,CAAC,oBAAoB,CAAC;SACvC;QACD,UAAU,EAAE;YACV,iBAAiB,EAAE,YAAY;YAC/B,iBAAiB,EAAE,IAAI;SACxB;KACF;CACF,CAAC;AAEW,QAAA,eAAe,GAAG,IAAA,yBAAY,EAAC;IAC1C,QAAQ,EAAE,yBAAiB;IAC3B,OAAO,EAAE,GAAG,EAAE,CAAC,sBAAS;CACzB,CAAC,CAAC;AAEH,SAAgB,SAAS;IACvB,OAAO,uBAAe,CAAC;AACzB,CAAC;AAED,kBAAe,uBAAe,CAAC"}
@@ -0,0 +1,41 @@
1
+ import type { ServerContext } from '@modelcontextprotocol/server';
2
+ export interface McpRequestStateOptions {
3
+ /** Exactly 32 bytes. Same key must be available to every instance of this app that may
4
+ * receive an echoed requestState (i.e. every replica behind the same deployment). */
5
+ key: Uint8Array;
6
+ /** @default 600 (10 minutes) */
7
+ ttlSeconds?: number;
8
+ /** Handler re-entries a single flow may go through before resume() refuses it.
9
+ * @default 8 */
10
+ maxRounds?: number;
11
+ /** The authenticated caller to bind minted state to (together with the SDK's own
12
+ * `ctx.mcpReq.method`) -- pass the caller's own resolved identity (e.g.
13
+ * McpCallContext.sub from mcp.controller.ts's ApiKeyGuard-validated user), not something
14
+ * read off the SDK's transport-level `ctx.http.authInfo`: that field is populated by
15
+ * whichever transport adapter is in front of a given request (toNodeHandler reading
16
+ * Express's `req.auth`), and a caller-supplied principal is the one binding source that
17
+ * doesn't depend on that propagation path actually running for a given entry point. */
18
+ principal: string;
19
+ }
20
+ export interface McpMultiRoundStatePayload<T = unknown> {
21
+ round: number;
22
+ data: T;
23
+ }
24
+ export declare class McpRequestStateRoundLimitError extends Error {
25
+ readonly maxRounds: number;
26
+ constructor(maxRounds: number);
27
+ }
28
+ export interface McpRequestStateCodec {
29
+ readonly maxRounds: number;
30
+ /** Drop-in for `ServerOptions.requestState.verify` -- decodes and integrity-checks an
31
+ * echoed requestState, additionally enforcing the round cap `mint` tracks. */
32
+ verify(state: string, ctx: ServerContext): Promise<McpMultiRoundStatePayload>;
33
+ /** Seals `data` for round 0 of a new flow. */
34
+ mint(data: unknown, ctx: ServerContext): Promise<string>;
35
+ /** Seals `data` for the round *after* `previousRound` (i.e. resuming a verified payload).
36
+ * Throws McpRequestStateRoundLimitError if that would exceed maxRounds. */
37
+ mintNextRound(data: unknown, previousRound: number, ctx: ServerContext): Promise<string>;
38
+ }
39
+ export declare function createMcpRequestStateStore(options: McpRequestStateOptions): McpRequestStateCodec;
40
+ export declare function readMcpRequestStateKey(): Uint8Array | undefined;
41
+ //# sourceMappingURL=request-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-state.d.ts","sourceRoot":"","sources":["../src/request-state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAmBlE,MAAM,WAAW,sBAAsB;IACrC;yFACqF;IACrF,GAAG,EAAE,UAAU,CAAC;IAChB,gCAAgC;IAChC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;oBACgB;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;;2FAMuF;IACvF,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,yBAAyB,CAAC,CAAC,GAAG,OAAO;IACpD,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,CAAC,CAAC;CACT;AAED,qBAAa,8BAA+B,SAAQ,KAAK;IAC3C,QAAQ,CAAC,SAAS,EAAE,MAAM;gBAAjB,SAAS,EAAE,MAAM;CAIvC;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B;kFAC8E;IAC9E,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;IAC9E,8CAA8C;IAC9C,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACzD;+EAC2E;IAC3E,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC1F;AAED,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,sBAAsB,GAAG,oBAAoB,CA4BhG;AAMD,wBAAgB,sBAAsB,IAAI,UAAU,GAAG,SAAS,CAU/D"}
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.McpRequestStateRoundLimitError = void 0;
4
+ exports.createMcpRequestStateStore = createMcpRequestStateStore;
5
+ exports.readMcpRequestStateKey = readMcpRequestStateKey;
6
+ const server_1 = require("@modelcontextprotocol/server");
7
+ class McpRequestStateRoundLimitError extends Error {
8
+ constructor(maxRounds) {
9
+ super(`MCP requestState round limit exceeded (max ${maxRounds})`);
10
+ this.maxRounds = maxRounds;
11
+ this.name = 'McpRequestStateRoundLimitError';
12
+ }
13
+ }
14
+ exports.McpRequestStateRoundLimitError = McpRequestStateRoundLimitError;
15
+ function createMcpRequestStateStore(options) {
16
+ const maxRounds = options.maxRounds ?? 8;
17
+ if (!Number.isInteger(maxRounds) || maxRounds <= 0) {
18
+ throw new RangeError('requestState maxRounds must be a positive integer');
19
+ }
20
+ const codec = (0, server_1.createRequestStateCodec)({
21
+ key: options.key,
22
+ ttlSeconds: options.ttlSeconds,
23
+ bind: (ctx) => `${ctx.mcpReq.method}\0${options.principal}`,
24
+ });
25
+ return {
26
+ maxRounds,
27
+ async verify(state, ctx) {
28
+ const payload = await codec.verify(state, ctx);
29
+ if (payload.round >= maxRounds)
30
+ throw new McpRequestStateRoundLimitError(maxRounds);
31
+ return payload;
32
+ },
33
+ mint(data, ctx) {
34
+ return codec.mint({ round: 0, data }, ctx);
35
+ },
36
+ async mintNextRound(data, previousRound, ctx) {
37
+ const nextRound = previousRound + 1;
38
+ if (nextRound >= maxRounds)
39
+ throw new McpRequestStateRoundLimitError(maxRounds);
40
+ return codec.mint({ round: nextRound, data }, ctx);
41
+ },
42
+ };
43
+ }
44
+ /// Reads and base64-decodes `MCP_REQUEST_STATE_KEY`. Deliberately opt-in, not required at
45
+ /// module load: an app that never calls `ctx.mrtr.requestInput` shouldn't have to provision
46
+ /// a secret it doesn't use. Throws only when a tool handler actually tries to use MRTR
47
+ /// without the key configured -- see McpService.
48
+ function readMcpRequestStateKey() {
49
+ const raw = process.env.MCP_REQUEST_STATE_KEY;
50
+ if (raw === undefined || raw.length === 0)
51
+ return undefined;
52
+ const decoded = Buffer.from(raw, 'base64');
53
+ if (decoded.byteLength < 32) {
54
+ throw new RangeError(`MCP_REQUEST_STATE_KEY must decode to at least 32 bytes (got ${decoded.byteLength}); generate one with: node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"`);
55
+ }
56
+ return decoded;
57
+ }
58
+ //# sourceMappingURL=request-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-state.js","sourceRoot":"","sources":["../src/request-state.ts"],"names":[],"mappings":";;;AA8DA,gEA4BC;AAMD,wDAUC;AAzGD,yDAAuE;AA0CvE,MAAa,8BAA+B,SAAQ,KAAK;IACvD,YAAqB,SAAiB;QACpC,KAAK,CAAC,8CAA8C,SAAS,GAAG,CAAC,CAAC;QAD/C,cAAS,GAAT,SAAS,CAAQ;QAEpC,IAAI,CAAC,IAAI,GAAG,gCAAgC,CAAC;IAC/C,CAAC;CACF;AALD,wEAKC;AAcD,SAAgB,0BAA0B,CAAC,OAA+B;IACxE,MAAM,SAAS,GAAG,OAAO,CAAC,SAA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F;AACvF,iDAAiD;AACjD,SAAgB,sBAAsB;IACpC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC;IAC9C,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC5D,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAC3C,IAAI,OAAO,CAAC,UAAU,GAAG,EAAE,EAAE,CAAC;QAC5B,MAAM,IAAI,UAAU,CAClB,+DAA+D,OAAO,CAAC,UAAU,mGAAmG,CACrL,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { type McpHandlerRequestOptions, type McpHttpHandler, type McpServerFactory } from '@modelcontextprotocol/server';
2
+ export interface StatefulMcpHandlerOptions {
3
+ /** Returns the stable authenticated principal represented by this request. */
4
+ principalKey: (request: McpHandlerRequestOptions | undefined) => string | undefined;
5
+ maxLegacySessions?: number;
6
+ legacySessionIdleTtlMs?: number;
7
+ onerror?: (error: Error) => void;
8
+ }
9
+ /**
10
+ * Serves modern MCP requests per request and keeps 2025-era streamable HTTP sessions alive.
11
+ *
12
+ * The SDK's default legacy fallback is intentionally stateless. That is sufficient for simple
13
+ * tools, but it loses the capabilities declared during `initialize`, so a later tool call cannot
14
+ * issue server-to-client requests such as `elicitation/create`. This adapter preserves the
15
+ * legacy transport and server for the session while binding every request to the same validated
16
+ * principal. Authentication still belongs to the HTTP controller and must run on every request.
17
+ */
18
+ export declare function createStatefulMcpHandler(factory: McpServerFactory, options: StatefulMcpHandlerOptions): McpHttpHandler;
19
+ //# sourceMappingURL=stateful-mcp-handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stateful-mcp-handler.d.ts","sourceRoot":"","sources":["../src/stateful-mcp-handler.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,KAAK,wBAAwB,EAC7B,KAAK,cAAc,EAEnB,KAAK,gBAAgB,EAGtB,MAAM,8BAA8B,CAAC;AActC,MAAM,WAAW,yBAAyB;IACxC,8EAA8E;IAC9E,YAAY,EAAE,CAAC,OAAO,EAAE,wBAAwB,GAAG,SAAS,KAAK,MAAM,GAAG,SAAS,CAAC;IACpF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAED;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,gBAAgB,EACzB,OAAO,EAAE,yBAAyB,GACjC,cAAc,CAiBhB"}
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createStatefulMcpHandler = createStatefulMcpHandler;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const server_1 = require("@modelcontextprotocol/server");
6
+ const DEFAULT_MAX_LEGACY_SESSIONS = 1_000;
7
+ const DEFAULT_LEGACY_SESSION_IDLE_TTL_MS = 30 * 60 * 1_000;
8
+ /**
9
+ * Serves modern MCP requests per request and keeps 2025-era streamable HTTP sessions alive.
10
+ *
11
+ * The SDK's default legacy fallback is intentionally stateless. That is sufficient for simple
12
+ * tools, but it loses the capabilities declared during `initialize`, so a later tool call cannot
13
+ * issue server-to-client requests such as `elicitation/create`. This adapter preserves the
14
+ * legacy transport and server for the session while binding every request to the same validated
15
+ * principal. Authentication still belongs to the HTTP controller and must run on every request.
16
+ */
17
+ function createStatefulMcpHandler(factory, options) {
18
+ const modern = (0, server_1.createMcpHandler)(factory, { legacy: 'reject', onerror: options.onerror });
19
+ const legacy = new StatefulLegacyHandler(factory, options);
20
+ return {
21
+ bus: modern.bus,
22
+ notify: modern.notify,
23
+ fetch: async (request, requestOptions) => {
24
+ const legacyRequest = await (0, server_1.isLegacyRequest)(request, requestOptions?.parsedBody);
25
+ return legacyRequest
26
+ ? legacy.fetch(request, requestOptions)
27
+ : modern.fetch(request, requestOptions);
28
+ },
29
+ close: async () => {
30
+ await Promise.all([modern.close(), legacy.close()]);
31
+ },
32
+ };
33
+ }
34
+ class StatefulLegacyHandler {
35
+ constructor(factory, options) {
36
+ this.factory = factory;
37
+ this.options = options;
38
+ this.sessions = new Map();
39
+ this.pendingInitializations = 0;
40
+ this.closed = false;
41
+ this.maxSessions = positiveInteger(options.maxLegacySessions, DEFAULT_MAX_LEGACY_SESSIONS);
42
+ this.idleTtlMs = positiveInteger(options.legacySessionIdleTtlMs, DEFAULT_LEGACY_SESSION_IDLE_TTL_MS);
43
+ }
44
+ async fetch(request, requestOptions) {
45
+ if (this.closed)
46
+ return jsonRpcError(503, -32603, 'MCP handler is shutting down');
47
+ await this.pruneExpiredSessions();
48
+ const principalKey = this.options.principalKey(requestOptions);
49
+ if (!principalKey)
50
+ return jsonRpcError(401, -32001, 'Authentication is required');
51
+ const requestedSessionId = request.headers.get('mcp-session-id');
52
+ if (requestedSessionId) {
53
+ const session = this.sessions.get(requestedSessionId);
54
+ // Use the same response for an unknown session and a session owned by another principal.
55
+ // This prevents a valid caller from using the endpoint as a session-id oracle.
56
+ if (!session || session.principalKey !== principalKey || session.closed) {
57
+ return jsonRpcError(404, -32001, 'Session not found');
58
+ }
59
+ session.lastSeenAt = Date.now();
60
+ const response = await session.transport.handleRequest(request, requestOptions);
61
+ if (request.method.toUpperCase() === 'DELETE')
62
+ await this.closeSession(session);
63
+ return response;
64
+ }
65
+ if (request.method.toUpperCase() !== 'POST') {
66
+ return jsonRpcError(400, -32600, 'Mcp-Session-Id header is required');
67
+ }
68
+ if (this.sessions.size + this.pendingInitializations >= this.maxSessions) {
69
+ return jsonRpcError(503, -32603, 'MCP session capacity reached');
70
+ }
71
+ this.pendingInitializations += 1;
72
+ let session;
73
+ try {
74
+ const product = await this.factory({
75
+ era: 'legacy',
76
+ ...(requestOptions?.authInfo ? { authInfo: requestOptions.authInfo } : {}),
77
+ requestInfo: request,
78
+ });
79
+ const transport = new server_1.WebStandardStreamableHTTPServerTransport({
80
+ sessionIdGenerator: node_crypto_1.randomUUID,
81
+ onsessioninitialized: (sessionId) => {
82
+ if (!session || this.closed)
83
+ return;
84
+ session.id = sessionId;
85
+ session.lastSeenAt = Date.now();
86
+ this.sessions.set(sessionId, session);
87
+ },
88
+ onsessionclosed: (sessionId) => {
89
+ this.sessions.delete(sessionId);
90
+ },
91
+ });
92
+ session = {
93
+ principalKey,
94
+ product,
95
+ transport,
96
+ lastSeenAt: Date.now(),
97
+ closed: false,
98
+ };
99
+ await product.connect(transport);
100
+ const response = await transport.handleRequest(request, requestOptions);
101
+ // A valid initialize request assigns a session id synchronously. Anything else sent
102
+ // without a session id is a failed initialization and must not leave live resources.
103
+ if (!session.id)
104
+ await this.closeSession(session);
105
+ return response;
106
+ }
107
+ catch (error) {
108
+ this.report(error);
109
+ if (session)
110
+ await this.closeSession(session);
111
+ return jsonRpcError(500, -32603, 'Internal server error');
112
+ }
113
+ finally {
114
+ this.pendingInitializations -= 1;
115
+ }
116
+ }
117
+ async close() {
118
+ if (this.closed)
119
+ return;
120
+ this.closed = true;
121
+ const sessions = [...this.sessions.values()];
122
+ this.sessions.clear();
123
+ await Promise.all(sessions.map((session) => this.closeSession(session)));
124
+ }
125
+ async pruneExpiredSessions() {
126
+ const expiry = Date.now() - this.idleTtlMs;
127
+ const expired = [...this.sessions.values()].filter((session) => !session.closed && session.lastSeenAt < expiry);
128
+ await Promise.all(expired.map((session) => this.closeSession(session)));
129
+ }
130
+ async closeSession(session) {
131
+ if (session.closed)
132
+ return;
133
+ session.closed = true;
134
+ if (session.id)
135
+ this.sessions.delete(session.id);
136
+ try {
137
+ await session.product.close();
138
+ }
139
+ catch (error) {
140
+ this.report(error);
141
+ }
142
+ }
143
+ report(value) {
144
+ const error = value instanceof Error ? value : new Error(String(value));
145
+ try {
146
+ this.options.onerror?.(error);
147
+ }
148
+ catch {
149
+ // Error reporting must never alter an MCP response or block cleanup.
150
+ }
151
+ }
152
+ }
153
+ function positiveInteger(value, fallback) {
154
+ return Number.isSafeInteger(value) && value > 0 ? value : fallback;
155
+ }
156
+ function jsonRpcError(status, code, message) {
157
+ return Response.json({ jsonrpc: '2.0', error: { code, message }, id: null }, { status, headers: { 'Content-Type': 'application/json' } });
158
+ }
159
+ //# sourceMappingURL=stateful-mcp-handler.js.map