@nativemind108/mcp 0.0.0-stage → 1.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 (90) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/LICENSE +289 -0
  3. package/NOTICE +5 -0
  4. package/README.md +53 -2
  5. package/dist/cjs/access.d.ts +41 -0
  6. package/dist/cjs/access.js +28 -0
  7. package/dist/cjs/access.js.map +1 -0
  8. package/dist/cjs/catalog.d.ts +21 -0
  9. package/dist/cjs/catalog.js +54 -0
  10. package/dist/cjs/catalog.js.map +1 -0
  11. package/dist/cjs/client.d.ts +67 -0
  12. package/dist/cjs/client.js +123 -0
  13. package/dist/cjs/client.js.map +1 -0
  14. package/dist/cjs/define.d.ts +50 -0
  15. package/dist/cjs/define.js +27 -0
  16. package/dist/cjs/define.js.map +1 -0
  17. package/dist/cjs/feedback.d.ts +21 -0
  18. package/dist/cjs/feedback.js +93 -0
  19. package/dist/cjs/feedback.js.map +1 -0
  20. package/dist/cjs/http.d.ts +15 -0
  21. package/dist/cjs/http.js +213 -0
  22. package/dist/cjs/http.js.map +1 -0
  23. package/dist/cjs/hub.d.ts +51 -0
  24. package/dist/cjs/hub.js +346 -0
  25. package/dist/cjs/hub.js.map +1 -0
  26. package/dist/cjs/index.d.ts +11 -0
  27. package/dist/cjs/index.js +29 -0
  28. package/dist/cjs/index.js.map +1 -0
  29. package/dist/cjs/options.d.ts +168 -0
  30. package/dist/cjs/options.js +3 -0
  31. package/dist/cjs/options.js.map +1 -0
  32. package/dist/cjs/output.d.ts +23 -0
  33. package/dist/cjs/output.js +88 -0
  34. package/dist/cjs/output.js.map +1 -0
  35. package/dist/cjs/package.json +3 -0
  36. package/dist/cjs/service.d.ts +68 -0
  37. package/dist/cjs/service.js +98 -0
  38. package/dist/cjs/service.js.map +1 -0
  39. package/dist/cjs/tools.d.ts +31 -0
  40. package/dist/cjs/tools.js +124 -0
  41. package/dist/cjs/tools.js.map +1 -0
  42. package/dist/esm/access.d.ts +42 -0
  43. package/dist/esm/access.d.ts.map +1 -0
  44. package/dist/esm/access.js +24 -0
  45. package/dist/esm/access.js.map +1 -0
  46. package/dist/esm/catalog.d.ts +22 -0
  47. package/dist/esm/catalog.d.ts.map +1 -0
  48. package/dist/esm/catalog.js +50 -0
  49. package/dist/esm/catalog.js.map +1 -0
  50. package/dist/esm/client.d.ts +68 -0
  51. package/dist/esm/client.d.ts.map +1 -0
  52. package/dist/esm/client.js +118 -0
  53. package/dist/esm/client.js.map +1 -0
  54. package/dist/esm/define.d.ts +51 -0
  55. package/dist/esm/define.d.ts.map +1 -0
  56. package/dist/esm/define.js +23 -0
  57. package/dist/esm/define.js.map +1 -0
  58. package/dist/esm/feedback.d.ts +22 -0
  59. package/dist/esm/feedback.d.ts.map +1 -0
  60. package/dist/esm/feedback.js +89 -0
  61. package/dist/esm/feedback.js.map +1 -0
  62. package/dist/esm/http.d.ts +16 -0
  63. package/dist/esm/http.d.ts.map +1 -0
  64. package/dist/esm/http.js +206 -0
  65. package/dist/esm/http.js.map +1 -0
  66. package/dist/esm/hub.d.ts +52 -0
  67. package/dist/esm/hub.d.ts.map +1 -0
  68. package/dist/esm/hub.js +337 -0
  69. package/dist/esm/hub.js.map +1 -0
  70. package/dist/esm/index.d.ts +12 -0
  71. package/dist/esm/index.d.ts.map +1 -0
  72. package/dist/esm/index.js +13 -0
  73. package/dist/esm/index.js.map +1 -0
  74. package/dist/esm/options.d.ts +169 -0
  75. package/dist/esm/options.d.ts.map +1 -0
  76. package/dist/esm/options.js +2 -0
  77. package/dist/esm/options.js.map +1 -0
  78. package/dist/esm/output.d.ts +24 -0
  79. package/dist/esm/output.d.ts.map +1 -0
  80. package/dist/esm/output.js +79 -0
  81. package/dist/esm/output.js.map +1 -0
  82. package/dist/esm/service.d.ts +69 -0
  83. package/dist/esm/service.d.ts.map +1 -0
  84. package/dist/esm/service.js +93 -0
  85. package/dist/esm/service.js.map +1 -0
  86. package/dist/esm/tools.d.ts +32 -0
  87. package/dist/esm/tools.d.ts.map +1 -0
  88. package/dist/esm/tools.js +118 -0
  89. package/dist/esm/tools.js.map +1 -0
  90. package/package.json +59 -4
@@ -0,0 +1,206 @@
1
+ import crypto from 'node:crypto';
2
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
3
+ import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
4
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
5
+ import { bearerOf, createApp, httpServer } from '@nativemind108/core';
6
+ import { ApiCallError } from './client.js';
7
+ import { HubPool, keyHash } from './hub.js';
8
+ // generated by Claude (Opus 5.5), 2026-11-14; SDD sdd-nativemind-backend-handmade
9
+ export const DEFAULT_ROUTE = { path: '/mcp' };
10
+ function rpcError(reply, status, message, headers = {}) {
11
+ return reply.code(status).headers(headers).type('application/json').send({ jsonrpc: '2.0', error: { code: -32000, message }, id: null });
12
+ }
13
+ // generated by Claude (Opus 5.5), 2026-11-14; SDD sdd-nativemind-backend-handmade (from dropexpired services/mcp/src/http.ts + PBN mcp http/oauth, node:http → fastify)
14
+ /**
15
+ * Streamable HTTP on fastify (started with core `httpServer.start`). No server-side key: every request carries its own
16
+ * `Authorization: Bearer …`, forwarded to the API. A session is bound to the key (hash), route and params that opened it.
17
+ * `/health` is open; `/.well-known/oauth-protected-resource[/…]` (RFC 9728) when authServers are set.
18
+ */
19
+ export async function startHttp(options) {
20
+ const http = options.transports.http;
21
+ const pool = new HubPool(options);
22
+ const sessions = new Map();
23
+ const idleMs = http.sessionIdleMs ?? 30 * 60_000;
24
+ const maxSessions = http.maxSessions ?? 5000;
25
+ const routes = options.routes?.length ? options.routes : [DEFAULT_ROUTE];
26
+ const publicUrl = (http.publicUrl ?? `http://${http.host}:${http.port}`).replace(/\/+$/, '');
27
+ const accept = options.acceptToken ?? ((t) => t.length > 0);
28
+ const app = await createApp({
29
+ name: options.product.name,
30
+ ...(options.logger ? { logger: options.logger } : {}),
31
+ bodyLimit: 4 * 1024 * 1024,
32
+ trustProxy: true,
33
+ health: { check: () => ({ sessions: sessions.size }) },
34
+ });
35
+ if (http.lenientJson) {
36
+ app.addContentTypeParser('text/plain', { parseAs: 'string' }, (_req, body, done) => {
37
+ try {
38
+ done(null, body ? JSON.parse(body) : undefined);
39
+ }
40
+ catch {
41
+ done(null, body);
42
+ }
43
+ });
44
+ }
45
+ const challenge = (path) => ({ 'WWW-Authenticate': `Bearer resource_metadata="${publicUrl}/.well-known/oauth-protected-resource${path.replace(/\/+$/, '')}"` });
46
+ const langOf = (req) => options.langOf ? options.langOf(req.query, req.headers) : (req.query.lang ?? null);
47
+ if (http.authServers?.length) {
48
+ const extra = (path, query) => typeof http.resourceMetadata === 'function' ? http.resourceMetadata(path, query) : (http.resourceMetadata ?? {});
49
+ const meta = (path, query) => ({
50
+ resource: `${publicUrl}${path}`, authorization_servers: http.authServers, bearer_methods_supported: ['header'], resource_name: options.product.title,
51
+ ...extra(path, query),
52
+ });
53
+ app.get('/.well-known/oauth-protected-resource', async (req) => meta('/mcp', req.query));
54
+ app.get('/.well-known/oauth-protected-resource/*', async (req) => meta(`/${req.params['*']}`, req.query));
55
+ }
56
+ async function open(route, req, reply, token, params, make) {
57
+ if (sessions.size >= maxSessions)
58
+ return rpcError(reply, 503, 'Too many MCP sessions; try again later.');
59
+ let hub;
60
+ try {
61
+ hub = await pool.acquire(route.anonymous && !token ? null : token);
62
+ }
63
+ catch (error) {
64
+ if (error instanceof ApiCallError && (error.status === 401 || error.status === 403)) {
65
+ return rpcError(reply, error.status, `${error.code}: ${error.message}`, error.status === 401 ? challenge(req.url.split('?')[0]) : {});
66
+ }
67
+ return rpcError(reply, 502, `The ${options.product.title} API is not reachable; try again later.`);
68
+ }
69
+ const request = { ip: req.ip, headers: req.headers };
70
+ let session = {};
71
+ if (route.authorize) {
72
+ const verdict = await route.authorize({ ...request, query: req.query }, token, params, hub.client);
73
+ if ('error' in verdict)
74
+ return rpcError(reply, verdict.error.status, verdict.error.message, verdict.error.headers ?? {});
75
+ session = verdict.session ?? {};
76
+ }
77
+ const identity = token && options.oauth?.isOAuthToken(token) ? (await options.oauth.identity(hub.client)) ?? undefined : undefined;
78
+ const transport = await make(hub, identity);
79
+ const server = hub.createServer(route, params, langOf(req), true, token ? keyHash(token) : null, session, request);
80
+ await server.connect(transport);
81
+ return { hub, transport, identity };
82
+ }
83
+ for (const route of routes) {
84
+ const handler = async (req, reply) => {
85
+ const params = (req.params ?? {});
86
+ if (route.accepts && !route.accepts(params))
87
+ return rpcError(reply, 404, 'Unknown MCP endpoint.');
88
+ const path = req.url.split('?')[0];
89
+ const token = bearerOf(req.headers.authorization);
90
+ if (token && !accept(token))
91
+ return rpcError(reply, 401, 'Unauthorized: this bearer token is not accepted here.', challenge(path));
92
+ if (!token && !route.anonymous)
93
+ return rpcError(reply, 401, `Unauthorized: connect through OAuth (see WWW-Authenticate) or send "Authorization: Bearer <key>" (an API key of your ${options.product.title} account).`, challenge(path));
94
+ const hash = token ? keyHash(token) : null;
95
+ const paramsKey = JSON.stringify(params);
96
+ const sid = req.headers['mcp-session-id'];
97
+ const existing = typeof sid === 'string' ? sessions.get(sid) : undefined;
98
+ if (existing) {
99
+ if (!(existing.transport instanceof StreamableHTTPServerTransport))
100
+ return rpcError(reply, 400, 'This session uses the legacy SSE transport.');
101
+ if (existing.keyHash !== hash) {
102
+ // 1.0.1 (security): check the new token's grant with a standalone client; the shared hub client gets the
103
+ // rotated token only after the check passed (a refused token never reaches other sessions of the hub)
104
+ const same = !!existing.identity && !!token && !!options.oauth?.isOAuthToken(token) &&
105
+ (await options.oauth.identity(existing.hub.client.withKey(token)).catch(() => null)) === existing.identity;
106
+ if (!same)
107
+ return rpcError(reply, 401, 'Unauthorized: this session was opened with another key.', challenge(path));
108
+ existing.hub.client.setKey(token);
109
+ existing.keyHash = hash;
110
+ }
111
+ if (existing.route !== route.path || existing.params !== paramsKey)
112
+ return rpcError(reply, 400, 'This session belongs to another MCP endpoint.');
113
+ existing.lastSeen = Date.now();
114
+ }
115
+ if (req.method === 'POST') {
116
+ const body = req.body;
117
+ if (existing) {
118
+ reply.hijack();
119
+ return existing.transport.handleRequest(req.raw, reply.raw, body);
120
+ }
121
+ if (sid || !isInitializeRequest(body))
122
+ return rpcError(reply, 400, 'No valid session: start with an initialize request.');
123
+ let transport;
124
+ const opened = await open(route, req, reply, token, params, async (hub, identity) => {
125
+ transport = new StreamableHTTPServerTransport({
126
+ sessionIdGenerator: () => crypto.randomUUID(),
127
+ onsessioninitialized: (id) => {
128
+ sessions.set(id, { transport, keyHash: hash, route: route.path, params: paramsKey, lastSeen: Date.now(), hub, ...(identity ? { identity } : {}) });
129
+ },
130
+ });
131
+ transport.onclose = () => { if (transport.sessionId)
132
+ sessions.delete(transport.sessionId); };
133
+ return transport;
134
+ });
135
+ if (!opened || !('transport' in opened))
136
+ return opened;
137
+ reply.hijack();
138
+ await transport.handleRequest(req.raw, reply.raw, body);
139
+ return;
140
+ }
141
+ if (req.method === 'GET' || req.method === 'DELETE') {
142
+ if (!existing)
143
+ return rpcError(reply, 400, 'Unknown or missing mcp-session-id.');
144
+ reply.hijack();
145
+ return existing.transport.handleRequest(req.raw, reply.raw);
146
+ }
147
+ return rpcError(reply, 405, 'Method not allowed', { Allow: 'GET, POST, DELETE' });
148
+ };
149
+ app.route({ method: ['GET', 'POST', 'DELETE'], url: route.path, handler });
150
+ }
151
+ if (http.legacySse) {
152
+ const sse = http.legacySse;
153
+ const route = routes.find((r) => r.path === (sse.route ?? '/mcp')) ?? routes[0];
154
+ app.get(sse.ssePath, async (req, reply) => {
155
+ const token = bearerOf(req.headers.authorization);
156
+ if (token && !accept(token))
157
+ return rpcError(reply, 401, 'Unauthorized.', challenge(sse.ssePath));
158
+ if (!token && !route.anonymous)
159
+ return rpcError(reply, 401, 'Unauthorized: send "Authorization: Bearer <key>".', challenge(sse.ssePath));
160
+ let transport;
161
+ const opened = await open(route, req, reply, token, {}, async () => {
162
+ reply.hijack();
163
+ transport = new SSEServerTransport(sse.messagesPath, reply.raw);
164
+ return transport;
165
+ });
166
+ if (!opened || !('transport' in opened))
167
+ return;
168
+ sessions.set(transport.sessionId, { transport, keyHash: token ? keyHash(token) : null, route: route.path, params: '{}', lastSeen: Date.now(), hub: opened.hub });
169
+ transport.onclose = () => sessions.delete(transport.sessionId);
170
+ });
171
+ app.post(sse.messagesPath, async (req, reply) => {
172
+ const sid = req.query.sessionId;
173
+ const s = sid ? sessions.get(sid) : undefined;
174
+ if (!s || !(s.transport instanceof SSEServerTransport))
175
+ return rpcError(reply, 404, 'Unknown session.');
176
+ const token = bearerOf(req.headers.authorization);
177
+ if ((token ? keyHash(token) : null) !== s.keyHash)
178
+ return rpcError(reply, 401, 'Unauthorized: this session was opened with another key.');
179
+ s.lastSeen = Date.now();
180
+ reply.hijack();
181
+ await s.transport.handlePostMessage(req.raw, reply.raw, req.body);
182
+ });
183
+ }
184
+ const sweeper = setInterval(() => {
185
+ const now = Date.now();
186
+ for (const s of sessions.values())
187
+ if (now - s.lastSeen > idleMs)
188
+ void s.transport.close();
189
+ }, Math.min(idleMs, 60_000));
190
+ sweeper.unref();
191
+ await httpServer.start(app, { port: http.port, host: http.host });
192
+ return {
193
+ app,
194
+ pool,
195
+ sessions: () => sessions.size,
196
+ close: async () => {
197
+ clearInterval(sweeper);
198
+ for (const s of sessions.values())
199
+ await s.transport.close().catch(() => undefined);
200
+ sessions.clear();
201
+ pool.stop();
202
+ await app.close();
203
+ },
204
+ };
205
+ }
206
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/http.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AAEjC,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,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C,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IAClE,OAAO;QACL,GAAG;QACH,IAAI;QACJ,QAAQ,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI;QAC7B,KAAK,EAAE,KAAK,IAAI,EAAE;YAChB,aAAa,CAAC,OAAO,CAAC,CAAC;YACvB,KAAK,MAAM,CAAC,IAAI,QAAQ,CAAC,MAAM,EAAE;gBAAE,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YACpF,QAAQ,CAAC,KAAK,EAAE,CAAC;YACjB,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,MAAM,GAAG,CAAC,KAAK,EAAE,CAAC;QACpB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,52 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { Catalog } from './catalog.js';
3
+ import { ApiClient } from './client.js';
4
+ import type { McpRoute, McpServiceOptions, RouteContext } from './options.js';
5
+ import { ResultStore } from './output.js';
6
+ import { type SessionInfo } from './access.js';
7
+ /** sha256 of a key: cache key of its catalog (the secret itself is never a map key). */
8
+ export declare function keyHash(apiKey: string): string;
9
+ /**
10
+ * State of one key (or of anonymous access): API client, catalog, result cache. Every MCP session of the key gets its own
11
+ * `Server`; catalog changes notify all of them (tools/list_changed).
12
+ */
13
+ export declare class KeyHub {
14
+ readonly options: McpServiceOptions;
15
+ readonly client: ApiClient;
16
+ readonly catalog: Catalog | null;
17
+ readonly store: ResultStore;
18
+ /** 1.1: each open session's descriptor, so toolsChanged(match) can pick sessions. */
19
+ private readonly servers;
20
+ private timer;
21
+ lastUsed: number;
22
+ constructor(options: McpServiceOptions, apiKey: string | null);
23
+ get sessions(): number;
24
+ private get refreshMs();
25
+ /** Loads the catalog when never loaded or stale; 401/403 propagate, other errors keep the last catalog. */
26
+ ensureFresh(): Promise<void>;
27
+ private notifyChanged;
28
+ /**
29
+ * 1.1: the product's rights changed (Konsilium: «Аккаунт → API», co-ownership …) → matching sessions get
30
+ * notifications/tools/list_changed and re-list (the policy is evaluated live). Returns how many were notified.
31
+ */
32
+ notifyToolsChanged(match?: (s: SessionInfo) => boolean): Promise<number>;
33
+ /** Re-reads the catalog; notifies sessions on change. Errors keep the last catalog. */
34
+ refresh(): Promise<boolean>;
35
+ startTimer(): void;
36
+ stop(): void;
37
+ /** An MCP server for one session of `route` with its params. */
38
+ createServer(route: McpRoute, params: Record<string, string>, lang: string | null, closeTimerWhenIdle: boolean, keyId: string | null, session?: Record<string, unknown>, request?: RouteContext['request']): Server;
39
+ }
40
+ /** HTTP mode: one KeyHub per key hash (+ one anonymous); idle hubs are evicted. */
41
+ export declare class HubPool {
42
+ readonly options: McpServiceOptions;
43
+ private readonly hubs;
44
+ constructor(options: McpServiceOptions);
45
+ get size(): number;
46
+ acquire(apiKey: string | null): Promise<KeyHub>;
47
+ private sweep;
48
+ /** 1.1: tools/list_changed to matching sessions of every hub (see KeyHub.notifyToolsChanged). */
49
+ notifyToolsChanged(match?: (s: SessionInfo) => boolean): Promise<number>;
50
+ stop(): void;
51
+ }
52
+ //# sourceMappingURL=hub.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hub.d.ts","sourceRoot":"","sources":["../../src/hub.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AAMnE,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAgB,SAAS,EAAE,MAAM,aAAa,CAAC;AAGtD,OAAO,KAAK,EAAE,QAAQ,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC9E,OAAO,EAAE,WAAW,EAA8C,MAAM,aAAa,CAAC;AAEtF,OAAO,EAAgD,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAG7F,wFAAwF;AACxF,wBA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CAA6B;gBAE7B,OAAO,EAAE,iBAAiB;IAE/C,IAAI,IAAI,IAAI,MAAM,CAEjB;IAEK,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;IAiBrD,OAAO,CAAC,KAAK;IAYb,iGAAiG;IAC3F,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,EAAE,WAAW,KAAK,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAM9E,IAAI,IAAI,IAAI;CAIb"}
@@ -0,0 +1,337 @@
1
+ import crypto from 'node:crypto';
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { CallToolRequestSchema, ErrorCode, GetPromptRequestSchema, SubscribeRequestSchema, UnsubscribeRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
4
+ import { ZodError } from 'zod';
5
+ import { Catalog } from './catalog.js';
6
+ import { ApiCallError, ApiClient } from './client.js';
7
+ import { isCallToolResult } from './define.js';
8
+ import { feedbackTools } from './feedback.js';
9
+ import { ResultStore, errorResult, toolResult } from './output.js';
10
+ import { JOB_TOOLS, callCatalogTool, catalogTool, hasJobs } from './tools.js';
11
+ import { accessDeniedResult, needsOf } from './access.js';
12
+ // generated by Claude (Opus 5.5), 2026-11-14; SDD sdd-nativemind-backend-handmade
13
+ /** sha256 of a key: cache key of its catalog (the secret itself is never a map key). */
14
+ export function keyHash(apiKey) {
15
+ return crypto.createHash('sha256').update(apiKey).digest('hex');
16
+ }
17
+ // generated by Claude (Opus 5.5), 2026-11-14; SDD sdd-nativemind-backend-handmade (from dropexpired services/mcp/src/server.ts KeyHub)
18
+ /**
19
+ * State of one key (or of anonymous access): API client, catalog, result cache. Every MCP session of the key gets its own
20
+ * `Server`; catalog changes notify all of them (tools/list_changed).
21
+ */
22
+ export class KeyHub {
23
+ options;
24
+ client;
25
+ catalog;
26
+ store = new ResultStore();
27
+ /** 1.1: each open session's descriptor, so toolsChanged(match) can pick sessions. */
28
+ servers = new Map();
29
+ timer = null;
30
+ lastUsed = Date.now();
31
+ constructor(options, apiKey) {
32
+ this.options = options;
33
+ this.client = new ApiClient(options.api.url, apiKey, {
34
+ basePath: options.api.basePath,
35
+ ...(options.api.envelope ? { envelope: options.api.envelope } : {}),
36
+ ...(options.api.clientHeaders ? { clientHeaders: options.api.clientHeaders } : {}),
37
+ userAgent: options.api.userAgent ?? `${options.product.name}/${options.product.version ?? '1'}`,
38
+ ...(options.api.fetch ? { fetch: options.api.fetch } : {}),
39
+ });
40
+ this.catalog = options.catalog?.enabled && apiKey !== null ? new Catalog(this.client, options.catalog.toolsets ? new Set(options.catalog.toolsets) : null) : null;
41
+ }
42
+ get sessions() {
43
+ return this.servers.size;
44
+ }
45
+ get refreshMs() {
46
+ return this.options.catalog?.refreshMs ?? 60_000;
47
+ }
48
+ /** Loads the catalog when never loaded or stale; 401/403 propagate, other errors keep the last catalog. */
49
+ async ensureFresh() {
50
+ if (!this.catalog)
51
+ return;
52
+ if (!this.catalog.isLoaded) {
53
+ await this.catalog.refresh();
54
+ }
55
+ else if (Date.now() - this.catalog.loadedAt >= this.refreshMs) {
56
+ try {
57
+ const changed = await this.catalog.refresh();
58
+ if (changed)
59
+ await this.notifyChanged();
60
+ }
61
+ catch (error) {
62
+ if (error instanceof ApiCallError && (error.status === 401 || error.status === 403))
63
+ throw error;
64
+ }
65
+ }
66
+ }
67
+ async notifyChanged() {
68
+ await Promise.all([...this.servers.keys()].map((s) => s.sendToolListChanged().catch(() => undefined)));
69
+ }
70
+ // generated by Claude (Opus 5.5), 2026-11-15; SDD sdd-konsilium-mcp-local
71
+ /**
72
+ * 1.1: the product's rights changed (Konsilium: «Аккаунт → API», co-ownership …) → matching sessions get
73
+ * notifications/tools/list_changed and re-list (the policy is evaluated live). Returns how many were notified.
74
+ */
75
+ async notifyToolsChanged(match) {
76
+ const picked = [...this.servers].filter(([, info]) => !match || match(info)).map(([srv]) => srv);
77
+ await Promise.all(picked.map((srv) => srv.sendToolListChanged().catch(() => undefined)));
78
+ return picked.length;
79
+ }
80
+ /** Re-reads the catalog; notifies sessions on change. Errors keep the last catalog. */
81
+ async refresh() {
82
+ if (!this.catalog)
83
+ return false;
84
+ try {
85
+ const changed = await this.catalog.refresh();
86
+ if (changed)
87
+ await this.notifyChanged();
88
+ return changed;
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ }
94
+ startTimer() {
95
+ if (this.timer || !this.catalog)
96
+ return;
97
+ this.timer = setInterval(() => void this.refresh(), this.refreshMs);
98
+ this.timer.unref();
99
+ }
100
+ stop() {
101
+ if (this.timer)
102
+ clearInterval(this.timer);
103
+ this.timer = null;
104
+ }
105
+ /** An MCP server for one session of `route` with its params. */
106
+ createServer(route, params, lang, closeTimerWhenIdle, keyId, session = {}, request = null) {
107
+ const o = this.options;
108
+ // one client per session: per-session headers never leak between sessions sharing a key (or the anonymous hub)
109
+ const sessionApi = this.client.withHeaders({});
110
+ const routeCtx = { params, lang, api: sessionApi, session, request };
111
+ const instructions = typeof route.instructions === 'function' ? route.instructions(routeCtx) : (route.instructions ?? o.product.instructions);
112
+ const server = new Server({ name: route.serverName ?? o.product.name, version: o.product.version ?? '1.0.0' }, {
113
+ capabilities: { tools: { listChanged: true }, resources: o.resources?.subscribe ? { subscribe: true } : {}, ...(o.prompts ? { prompts: {} } : {}) },
114
+ ...(instructions ? { instructions } : {}),
115
+ });
116
+ this.servers.set(server, { route: route.path, params, session, keyHash: keyId });
117
+ this.lastUsed = Date.now();
118
+ this.startTimer();
119
+ const watches = new Map();
120
+ server.onclose = () => {
121
+ for (const stop of watches.values())
122
+ stop();
123
+ watches.clear();
124
+ this.servers.delete(server);
125
+ this.lastUsed = Date.now();
126
+ if (this.servers.size === 0 && closeTimerWhenIdle)
127
+ this.stop();
128
+ };
129
+ const limits = { maxRows: o.limits?.maxRows ?? 25, maxBytes: o.limits?.maxBytes ?? 8192, scheme: o.resultScheme ?? o.product.name.replace(/-mcp$/, '') };
130
+ const useCatalog = (route.catalog ?? o.catalog?.enabled ?? false) && this.catalog !== null;
131
+ const catalogOps = () => {
132
+ if (!useCatalog)
133
+ return [];
134
+ const ops = this.catalog.operations.filter((op) => !route.filter || route.filter(op, params));
135
+ return route.filterAll ? route.filterAll(ops, params) : ops;
136
+ };
137
+ const allManual = () => {
138
+ const own = route.tools?.(routeCtx) ?? [];
139
+ const fb = feedbackTools({ product: o.product.title, basePath: o.api.basePath, ...(o.feedback ?? {}) });
140
+ const names = new Set(own.map((t) => t.name));
141
+ return [...own, ...fb.filter((t) => !names.has(t.name))];
142
+ };
143
+ // 1.1: the access policy (live) — hidden tools are not listed and are refused on call
144
+ const policy = route.access ?? o.access;
145
+ const allowed = (t) => !policy || policy.allowed(t.requires, t.name, routeCtx);
146
+ const manual = () => allManual().filter(allowed);
147
+ const hidden = () => (policy ? allManual().filter((t) => !allowed(t)).map((t) => ({ name: t.name, needs: needsOf(t.requires), kind: t.requires?.kind ?? null })) : []);
148
+ const translate = (t) => {
149
+ if (!lang || !o.i18n)
150
+ return t;
151
+ const tr = o.i18n(t.name, lang);
152
+ if (!tr)
153
+ return t;
154
+ return { ...t, ...(tr.title ? { title: tr.title, annotations: { ...(t.annotations ?? {}), title: tr.title } } : {}), ...(tr.description ? { description: tr.description } : {}) };
155
+ };
156
+ const clientName = () => {
157
+ const ci = server.getClientVersion?.();
158
+ return ci?.name ? `${ci.name}${ci.version ? ` ${ci.version}` : ''}` : 'MCP';
159
+ };
160
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
161
+ if (useCatalog)
162
+ await this.ensureFresh().catch(() => undefined);
163
+ const ops = catalogOps();
164
+ const tools = ops.map((op) => catalogTool(op, o.catalog ?? {}));
165
+ if (o.catalog?.jobs && hasJobs(ops))
166
+ tools.push(...JOB_TOOLS.filter((j) => !tools.some((t) => t.name === j.name)));
167
+ const seen = new Set(tools.map((t) => t.name));
168
+ for (const t of manual()) {
169
+ if (seen.has(t.name))
170
+ continue;
171
+ seen.add(t.name);
172
+ tools.push({ ...(t.listFields ?? {}), name: t.name, title: t.title, description: t.description, inputSchema: t.inputSchema, annotations: { title: t.title, ...(t.annotations ?? {}) } });
173
+ }
174
+ return { tools: tools.map(translate) };
175
+ });
176
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
177
+ const started = Date.now();
178
+ const name = req.params.name;
179
+ let result;
180
+ const callApi = sessionApi.withHeaders({ 'X-NM-MCP-Client': clientName() });
181
+ try {
182
+ const any = allManual().find((t) => t.name === name);
183
+ const tool = any && allowed(any) ? any : undefined;
184
+ if (any && !tool) {
185
+ result = accessDeniedResult(name, any.requires, policy?.refusal?.(name, any.requires, routeCtx));
186
+ }
187
+ else if (tool) {
188
+ const ctx = { api: callApi, params, lang, client: clientName(), extra: session, request, hidden };
189
+ try {
190
+ const args = tool.parse ? tool.parse(req.params.arguments ?? {}) : (req.params.arguments ?? {});
191
+ const value = await tool.call(args, ctx);
192
+ result = isCallToolResult(value) ? value : toolResult({ data: value }, limits, this.store);
193
+ }
194
+ catch (error) {
195
+ if (error instanceof ZodError) {
196
+ result = errorResult(new ApiCallError(400, 'VALIDATION_ERROR', 'Invalid arguments.', error.issues.map((i) => ({ field: i.path.join('.'), reason: i.message }))));
197
+ }
198
+ else {
199
+ result = errorResult(error);
200
+ }
201
+ }
202
+ }
203
+ else {
204
+ const r = useCatalog
205
+ ? await callCatalogTool({
206
+ api: callApi, store: this.store, limits, options: o.catalog ?? {},
207
+ ...(o.catalog?.rewriteArgs ? { rewriteArgs: o.catalog.rewriteArgs } : {}),
208
+ ...(o.catalog?.resultExtra ? { resultExtra: o.catalog.resultExtra } : {}),
209
+ onScopeDenied: () => void this.refresh(),
210
+ }, catalogOps(), name, req.params.arguments)
211
+ : null;
212
+ result = r ?? errorResult(new ApiCallError(404, 'UNKNOWN_TOOL', `Tool ${name} is not available here: unknown, not on this MCP endpoint, or not allowed for this key.`));
213
+ }
214
+ }
215
+ catch (error) {
216
+ result = errorResult(error);
217
+ }
218
+ const errorCode = result.isError ? (result.structuredContent?.error?.code ?? 'ERROR') : undefined;
219
+ o.onCall?.({ tool: name, route: route.path, ok: !result.isError, ms: Date.now() - started, keyHash: keyId, params, client: clientName(), session, ...(errorCode ? { errorCode } : {}) });
220
+ return result;
221
+ });
222
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: (await o.resources?.list?.(sessionApi)) ?? [] }));
223
+ if (o.resources?.subscribe) {
224
+ const subscribe = o.resources.subscribe;
225
+ server.setRequestHandler(SubscribeRequestSchema, async (req) => {
226
+ const uri = req.params.uri;
227
+ if (watches.has(uri))
228
+ return {};
229
+ const stop = subscribe(uri, sessionApi, () => {
230
+ watches.delete(uri);
231
+ void server.sendResourceUpdated({ uri }).catch(() => undefined);
232
+ });
233
+ if (stop)
234
+ watches.set(uri, stop);
235
+ return {};
236
+ });
237
+ server.setRequestHandler(UnsubscribeRequestSchema, async (req) => {
238
+ watches.get(req.params.uri)?.();
239
+ watches.delete(req.params.uri);
240
+ return {};
241
+ });
242
+ }
243
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({
244
+ resourceTemplates: [
245
+ { uriTemplate: `${limits.scheme}://results/{token}`, name: 'Full tool result', mimeType: 'application/json', description: 'Full result of a truncated tool call' },
246
+ ...(o.resources?.templates?.() ?? []),
247
+ ],
248
+ }));
249
+ server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
250
+ const uri = req.params.uri;
251
+ const m = new RegExp(`^${limits.scheme}://results/([A-Za-z0-9_-]+)$`).exec(uri);
252
+ if (m) {
253
+ const value = this.store.get(m[1]);
254
+ if (value === undefined)
255
+ throw new McpError(ErrorCode.InvalidParams, `Unknown or expired result ${uri}`);
256
+ return { contents: [{ uri, mimeType: 'application/json', text: JSON.stringify(value) }] };
257
+ }
258
+ try {
259
+ const r = await o.resources?.read?.(uri, sessionApi);
260
+ if (r)
261
+ return r;
262
+ }
263
+ catch (error) {
264
+ const code = error instanceof ApiCallError ? error.code : 'MCP_ERROR';
265
+ throw new McpError(ErrorCode.InvalidParams, `${code}: ${error instanceof Error ? error.message : String(error)}`);
266
+ }
267
+ throw new McpError(ErrorCode.InvalidParams, `Unknown resource ${uri}`);
268
+ });
269
+ if (o.prompts) {
270
+ const prompts = o.prompts;
271
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: prompts.list() }));
272
+ server.setRequestHandler(GetPromptRequestSchema, async (req) => {
273
+ try {
274
+ return prompts.get(req.params.name, req.params.arguments ?? {});
275
+ }
276
+ catch (error) {
277
+ throw new McpError(ErrorCode.InvalidParams, error instanceof Error ? error.message : String(error));
278
+ }
279
+ });
280
+ }
281
+ return server;
282
+ }
283
+ }
284
+ // generated by Claude (Opus 5.5), 2026-11-14; SDD sdd-nativemind-backend-handmade (from dropexpired services/mcp/src/server.ts HubPool)
285
+ /** HTTP mode: one KeyHub per key hash (+ one anonymous); idle hubs are evicted. */
286
+ export class HubPool {
287
+ options;
288
+ hubs = new Map();
289
+ constructor(options) {
290
+ this.options = options;
291
+ }
292
+ get size() {
293
+ return this.hubs.size;
294
+ }
295
+ async acquire(apiKey) {
296
+ this.sweep();
297
+ const hash = apiKey === null ? 'anonymous' : keyHash(apiKey);
298
+ let hub = this.hubs.get(hash);
299
+ if (!hub) {
300
+ hub = new KeyHub(this.options, apiKey);
301
+ this.hubs.set(hash, hub);
302
+ }
303
+ try {
304
+ await hub.ensureFresh();
305
+ }
306
+ catch (error) {
307
+ if (!hub.catalog?.isLoaded)
308
+ this.hubs.delete(hash);
309
+ throw error;
310
+ }
311
+ return hub;
312
+ }
313
+ sweep() {
314
+ const idleMs = Math.max(10 * (this.options.catalog?.refreshMs ?? 60_000), 10 * 60_000);
315
+ const now = Date.now();
316
+ for (const [hash, hub] of this.hubs) {
317
+ if (hub.sessions === 0 && now - hub.lastUsed > idleMs) {
318
+ hub.stop();
319
+ this.hubs.delete(hash);
320
+ }
321
+ }
322
+ }
323
+ // generated by Claude (Opus 5.5), 2026-11-15; SDD sdd-konsilium-mcp-local
324
+ /** 1.1: tools/list_changed to matching sessions of every hub (see KeyHub.notifyToolsChanged). */
325
+ async notifyToolsChanged(match) {
326
+ let n = 0;
327
+ for (const hub of this.hubs.values())
328
+ n += await hub.notifyToolsChanged(match);
329
+ return n;
330
+ }
331
+ stop() {
332
+ for (const hub of this.hubs.values())
333
+ hub.stop();
334
+ this.hubs.clear();
335
+ }
336
+ }
337
+ //# sourceMappingURL=hub.js.map