@nativemind108/mcp 0.0.0-stage → 1.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.
Files changed (83) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +289 -0
  3. package/NOTICE +5 -0
  4. package/README.md +29 -2
  5. package/dist/cjs/catalog.d.ts +21 -0
  6. package/dist/cjs/catalog.js +54 -0
  7. package/dist/cjs/catalog.js.map +1 -0
  8. package/dist/cjs/client.d.ts +59 -0
  9. package/dist/cjs/client.js +107 -0
  10. package/dist/cjs/client.js.map +1 -0
  11. package/dist/cjs/define.d.ts +37 -0
  12. package/dist/cjs/define.js +26 -0
  13. package/dist/cjs/define.js.map +1 -0
  14. package/dist/cjs/feedback.d.ts +21 -0
  15. package/dist/cjs/feedback.js +77 -0
  16. package/dist/cjs/feedback.js.map +1 -0
  17. package/dist/cjs/http.d.ts +15 -0
  18. package/dist/cjs/http.js +192 -0
  19. package/dist/cjs/http.js.map +1 -0
  20. package/dist/cjs/hub.d.ts +42 -0
  21. package/dist/cjs/hub.js +284 -0
  22. package/dist/cjs/hub.js.map +1 -0
  23. package/dist/cjs/index.d.ts +10 -0
  24. package/dist/cjs/index.js +28 -0
  25. package/dist/cjs/index.js.map +1 -0
  26. package/dist/cjs/options.d.ts +119 -0
  27. package/dist/cjs/options.js +3 -0
  28. package/dist/cjs/options.js.map +1 -0
  29. package/dist/cjs/output.d.ts +23 -0
  30. package/dist/cjs/output.js +88 -0
  31. package/dist/cjs/output.js.map +1 -0
  32. package/dist/cjs/package.json +3 -0
  33. package/dist/cjs/service.d.ts +33 -0
  34. package/dist/cjs/service.js +64 -0
  35. package/dist/cjs/service.js.map +1 -0
  36. package/dist/cjs/tools.d.ts +31 -0
  37. package/dist/cjs/tools.js +124 -0
  38. package/dist/cjs/tools.js.map +1 -0
  39. package/dist/esm/catalog.d.ts +22 -0
  40. package/dist/esm/catalog.d.ts.map +1 -0
  41. package/dist/esm/catalog.js +50 -0
  42. package/dist/esm/catalog.js.map +1 -0
  43. package/dist/esm/client.d.ts +60 -0
  44. package/dist/esm/client.d.ts.map +1 -0
  45. package/dist/esm/client.js +102 -0
  46. package/dist/esm/client.js.map +1 -0
  47. package/dist/esm/define.d.ts +38 -0
  48. package/dist/esm/define.d.ts.map +1 -0
  49. package/dist/esm/define.js +22 -0
  50. package/dist/esm/define.js.map +1 -0
  51. package/dist/esm/feedback.d.ts +22 -0
  52. package/dist/esm/feedback.d.ts.map +1 -0
  53. package/dist/esm/feedback.js +73 -0
  54. package/dist/esm/feedback.js.map +1 -0
  55. package/dist/esm/http.d.ts +16 -0
  56. package/dist/esm/http.d.ts.map +1 -0
  57. package/dist/esm/http.js +185 -0
  58. package/dist/esm/http.js.map +1 -0
  59. package/dist/esm/hub.d.ts +43 -0
  60. package/dist/esm/hub.d.ts.map +1 -0
  61. package/dist/esm/hub.js +275 -0
  62. package/dist/esm/hub.js.map +1 -0
  63. package/dist/esm/index.d.ts +11 -0
  64. package/dist/esm/index.d.ts.map +1 -0
  65. package/dist/esm/index.js +12 -0
  66. package/dist/esm/index.js.map +1 -0
  67. package/dist/esm/options.d.ts +120 -0
  68. package/dist/esm/options.d.ts.map +1 -0
  69. package/dist/esm/options.js +2 -0
  70. package/dist/esm/options.js.map +1 -0
  71. package/dist/esm/output.d.ts +24 -0
  72. package/dist/esm/output.d.ts.map +1 -0
  73. package/dist/esm/output.js +79 -0
  74. package/dist/esm/output.js.map +1 -0
  75. package/dist/esm/service.d.ts +34 -0
  76. package/dist/esm/service.d.ts.map +1 -0
  77. package/dist/esm/service.js +60 -0
  78. package/dist/esm/service.js.map +1 -0
  79. package/dist/esm/tools.d.ts +32 -0
  80. package/dist/esm/tools.d.ts.map +1 -0
  81. package/dist/esm/tools.js +118 -0
  82. package/dist/esm/tools.js.map +1 -0
  83. package/package.json +59 -4
@@ -0,0 +1,73 @@
1
+ import { FEEDBACK_PATHS, FEEDBACK_SCHEMAS } from '@nativemind108/api';
2
+ import { ApiCallError } from './client.js';
3
+ import { errorResult } from './output.js';
4
+ // generated by Claude (Opus 5.5), 2026-11-14; SDD sdd-nativemind-backend-handmade (tools = Konsilium mcp/feedbacktools.js; requirements AC5)
5
+ export const FEEDBACK_TOOL_NAMES = ['report_bug', 'suggest_improvement', 'leave_review', 'add_feedback_note', 'my_feedback'];
6
+ const W = { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
7
+ const strip = (s, drop = []) => {
8
+ const properties = { ...(s.properties ?? {}) };
9
+ for (const d of drop)
10
+ delete properties[d];
11
+ const required = (s.required ?? []).filter((r) => !drop.includes(r));
12
+ return { type: 'object', properties, ...(required.length ? { required } : {}) };
13
+ };
14
+ // generated by Claude (Opus 5.5), 2026-11-14; SDD sdd-nativemind-backend-handmade
15
+ /**
16
+ * The five feedback tools. They are registered on every MCP server of every product and cannot be turned off.
17
+ * A product whose API has no storage yet answers 501 → the tool returns isError with a plain message (no exception).
18
+ */
19
+ export function feedbackTools(o) {
20
+ const p = o.product;
21
+ const S = FEEDBACK_SCHEMAS;
22
+ const path = (k) => `${o.basePath}${FEEDBACK_PATHS[k].path}`;
23
+ const text = (name, title, description) => ({ title: o.describe?.(name)?.title ?? title, description: o.describe?.(name)?.description ?? description });
24
+ const wrap = (name, run) => async (args, ctx) => {
25
+ try {
26
+ const data = (await run(args, ctx));
27
+ return o.decorate ? o.decorate(name, data, ctx.lang) : data;
28
+ }
29
+ catch (error) {
30
+ if (error instanceof ApiCallError && error.status === 501)
31
+ return errorResult(error, `${p} does not accept feedback yet (NOT_IMPLEMENTED).`);
32
+ throw error;
33
+ }
34
+ };
35
+ const post = async (ctx, k, args) => (await ctx.api.request(FEEDBACK_PATHS[k].method, path(k), args, { 'X-NM-MCP-Client': ctx.client })).body.data;
36
+ return [
37
+ {
38
+ name: 'report_bug',
39
+ ...text('report_bug', `Report a ${p} bug`, `Report a bug in ${p} itself (the product: MCP tools, app, API) — not a problem of your own data. Example: a tool returned a wrong error, a result was lost. Becomes an item for the ${p} team.`),
40
+ inputSchema: strip(S.bugInput), annotations: W,
41
+ call: wrap('report_bug', (a, ctx) => post(ctx, 'bug', a)),
42
+ },
43
+ {
44
+ name: 'suggest_improvement',
45
+ ...text('suggest_improvement', `Suggest a ${p} improvement`, `Suggest how to improve ${p} itself, e.g. a missing MCP tool or parameter.`),
46
+ inputSchema: strip(S.improvementInput), annotations: W,
47
+ call: wrap('suggest_improvement', (a, ctx) => post(ctx, 'improvement', a)),
48
+ },
49
+ {
50
+ name: 'leave_review',
51
+ ...text('leave_review', `Review ${p}`, `Leave a review of how ${p} itself works for you. Optional rating 1–5.`),
52
+ inputSchema: strip(S.reviewInput), annotations: W,
53
+ call: wrap('leave_review', (a, ctx) => post(ctx, 'review', a)),
54
+ },
55
+ {
56
+ name: 'add_feedback_note',
57
+ ...text('add_feedback_note', 'Add to my feedback', `Add details to feedback I already sent (#F…) instead of sending a new one: the original stays, the addition is kept in its history with the date and is visible to the ${p} team.`),
58
+ inputSchema: { type: 'object', properties: { feedback_id: { type: 'integer' }, text: { type: 'string', minLength: 2, maxLength: 4000 } }, required: ['feedback_id', 'text'] },
59
+ annotations: W,
60
+ call: wrap('add_feedback_note', (a, ctx) => post(ctx, 'note', { id: a.feedback_id, text: a.text })),
61
+ },
62
+ {
63
+ name: 'my_feedback',
64
+ ...text('my_feedback', 'My feedback', `Feedback I sent about ${p} (#F…), newest first, with status and additions — find the item to add to.`),
65
+ inputSchema: strip(S.mineInput), annotations: { readOnlyHint: true, openWorldHint: false },
66
+ call: wrap('my_feedback', async (a, ctx) => {
67
+ const data = (await ctx.api.request('GET', path('mine'), { limit: a.limit ?? 20 })).body.data;
68
+ return { feedback: data.feedback.map((f) => ({ ...f, text: String(f.text ?? '').slice(0, 300) })) };
69
+ }),
70
+ },
71
+ ];
72
+ }
73
+ //# sourceMappingURL=feedback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"feedback.js","sourceRoot":"","sources":["../../src/feedback.ts"],"names":[],"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,GAAG,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;YACtG,CAAC,CAAC;SACH;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,16 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ import { HubPool } from './hub.js';
3
+ import type { McpRoute, McpServiceOptions } from './options.js';
4
+ export declare const DEFAULT_ROUTE: McpRoute;
5
+ /**
6
+ * Streamable HTTP on fastify (started with core `httpServer.start`). No server-side key: every request carries its own
7
+ * `Authorization: Bearer …`, forwarded to the API. A session is bound to the key (hash), route and params that opened it.
8
+ * `/health` is open; `/.well-known/oauth-protected-resource[/…]` (RFC 9728) when authServers are set.
9
+ */
10
+ export declare function startHttp(options: McpServiceOptions): Promise<{
11
+ app: FastifyInstance;
12
+ pool: HubPool;
13
+ close: () => Promise<void>;
14
+ sessions: () => number;
15
+ }>;
16
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/http.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAgC,MAAM,SAAS,CAAC;AAM7E,OAAO,EAAE,OAAO,EAAwB,MAAM,UAAU,CAAC;AACzD,OAAO,KAAK,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAahE,eAAO,MAAM,aAAa,EAAE,QAA2B,CAAC;AAOxD;;;;GAIG;AACH,wBAAsB,SAAS,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC;IAAE,GAAG,EAAE,eAAe,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAAC,QAAQ,EAAE,MAAM,MAAM,CAAA;CAAE,CAAC,CA0JhK"}
@@ -0,0 +1,185 @@
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
+ const challenge = (path) => ({ 'WWW-Authenticate': `Bearer resource_metadata="${publicUrl}/.well-known/oauth-protected-resource${path.replace(/\/+$/, '')}"` });
36
+ const langOf = (req) => options.langOf ? options.langOf(req.query, req.headers) : (req.query.lang ?? null);
37
+ if (http.authServers?.length) {
38
+ const meta = (path) => ({ resource: `${publicUrl}${path}`, authorization_servers: http.authServers, bearer_methods_supported: ['header'], resource_name: options.product.title });
39
+ app.get('/.well-known/oauth-protected-resource', async () => meta('/mcp'));
40
+ app.get('/.well-known/oauth-protected-resource/*', async (req) => meta(`/${req.params['*']}`));
41
+ }
42
+ async function open(route, req, reply, token, params, make) {
43
+ if (sessions.size >= maxSessions)
44
+ return rpcError(reply, 503, 'Too many MCP sessions; try again later.');
45
+ let hub;
46
+ try {
47
+ hub = await pool.acquire(route.anonymous && !token ? null : token);
48
+ }
49
+ catch (error) {
50
+ if (error instanceof ApiCallError && (error.status === 401 || error.status === 403)) {
51
+ return rpcError(reply, error.status, `${error.code}: ${error.message}`, error.status === 401 ? challenge(req.url.split('?')[0]) : {});
52
+ }
53
+ return rpcError(reply, 502, `The ${options.product.title} API is not reachable; try again later.`);
54
+ }
55
+ const identity = token && options.oauth?.isOAuthToken(token) ? (await options.oauth.identity(hub.client)) ?? undefined : undefined;
56
+ const transport = await make(hub, identity);
57
+ const server = hub.createServer(route, params, langOf(req), true, token ? keyHash(token) : null);
58
+ await server.connect(transport);
59
+ return { hub, transport, identity };
60
+ }
61
+ for (const route of routes) {
62
+ const handler = async (req, reply) => {
63
+ const params = (req.params ?? {});
64
+ if (route.accepts && !route.accepts(params))
65
+ return rpcError(reply, 404, 'Unknown MCP endpoint.');
66
+ const path = req.url.split('?')[0];
67
+ const token = bearerOf(req.headers.authorization);
68
+ if (token && !accept(token))
69
+ return rpcError(reply, 401, 'Unauthorized: this bearer token is not accepted here.', challenge(path));
70
+ if (!token && !route.anonymous)
71
+ 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));
72
+ const hash = token ? keyHash(token) : null;
73
+ const paramsKey = JSON.stringify(params);
74
+ const sid = req.headers['mcp-session-id'];
75
+ const existing = typeof sid === 'string' ? sessions.get(sid) : undefined;
76
+ if (existing) {
77
+ if (!(existing.transport instanceof StreamableHTTPServerTransport))
78
+ return rpcError(reply, 400, 'This session uses the legacy SSE transport.');
79
+ if (existing.keyHash !== hash) {
80
+ const same = !!existing.identity && !!token && !!options.oauth?.isOAuthToken(token) && (await (async () => {
81
+ const prev = existing.hub.client;
82
+ prev.setKey(token);
83
+ const id = await options.oauth.identity(prev).catch(() => null);
84
+ return id === existing.identity;
85
+ })());
86
+ if (!same)
87
+ return rpcError(reply, 401, 'Unauthorized: this session was opened with another key.', challenge(path));
88
+ existing.keyHash = hash;
89
+ }
90
+ if (existing.route !== route.path || existing.params !== paramsKey)
91
+ return rpcError(reply, 400, 'This session belongs to another MCP endpoint.');
92
+ existing.lastSeen = Date.now();
93
+ }
94
+ if (req.method === 'POST') {
95
+ const body = req.body;
96
+ if (existing) {
97
+ reply.hijack();
98
+ return existing.transport.handleRequest(req.raw, reply.raw, body);
99
+ }
100
+ if (sid || !isInitializeRequest(body))
101
+ return rpcError(reply, 400, 'No valid session: start with an initialize request.');
102
+ let transport;
103
+ const opened = await open(route, req, reply, token, params, async (hub, identity) => {
104
+ transport = new StreamableHTTPServerTransport({
105
+ sessionIdGenerator: () => crypto.randomUUID(),
106
+ onsessioninitialized: (id) => {
107
+ sessions.set(id, { transport, keyHash: hash, route: route.path, params: paramsKey, lastSeen: Date.now(), hub, ...(identity ? { identity } : {}) });
108
+ },
109
+ });
110
+ transport.onclose = () => { if (transport.sessionId)
111
+ sessions.delete(transport.sessionId); };
112
+ return transport;
113
+ });
114
+ if (!opened || !('transport' in opened))
115
+ return opened;
116
+ reply.hijack();
117
+ await transport.handleRequest(req.raw, reply.raw, body);
118
+ return;
119
+ }
120
+ if (req.method === 'GET' || req.method === 'DELETE') {
121
+ if (!existing)
122
+ return rpcError(reply, 400, 'Unknown or missing mcp-session-id.');
123
+ reply.hijack();
124
+ return existing.transport.handleRequest(req.raw, reply.raw);
125
+ }
126
+ return rpcError(reply, 405, 'Method not allowed', { Allow: 'GET, POST, DELETE' });
127
+ };
128
+ app.route({ method: ['GET', 'POST', 'DELETE'], url: route.path, handler });
129
+ }
130
+ if (http.legacySse) {
131
+ const sse = http.legacySse;
132
+ const route = routes.find((r) => r.path === (sse.route ?? '/mcp')) ?? routes[0];
133
+ app.get(sse.ssePath, async (req, reply) => {
134
+ const token = bearerOf(req.headers.authorization);
135
+ if (token && !accept(token))
136
+ return rpcError(reply, 401, 'Unauthorized.', challenge(sse.ssePath));
137
+ if (!token && !route.anonymous)
138
+ return rpcError(reply, 401, 'Unauthorized: send "Authorization: Bearer <key>".', challenge(sse.ssePath));
139
+ let transport;
140
+ const opened = await open(route, req, reply, token, {}, async () => {
141
+ reply.hijack();
142
+ transport = new SSEServerTransport(sse.messagesPath, reply.raw);
143
+ return transport;
144
+ });
145
+ if (!opened || !('transport' in opened))
146
+ return;
147
+ sessions.set(transport.sessionId, { transport, keyHash: token ? keyHash(token) : null, route: route.path, params: '{}', lastSeen: Date.now(), hub: opened.hub });
148
+ transport.onclose = () => sessions.delete(transport.sessionId);
149
+ });
150
+ app.post(sse.messagesPath, async (req, reply) => {
151
+ const sid = req.query.sessionId;
152
+ const s = sid ? sessions.get(sid) : undefined;
153
+ if (!s || !(s.transport instanceof SSEServerTransport))
154
+ return rpcError(reply, 404, 'Unknown session.');
155
+ const token = bearerOf(req.headers.authorization);
156
+ if ((token ? keyHash(token) : null) !== s.keyHash)
157
+ return rpcError(reply, 401, 'Unauthorized: this session was opened with another key.');
158
+ s.lastSeen = Date.now();
159
+ reply.hijack();
160
+ await s.transport.handlePostMessage(req.raw, reply.raw, req.body);
161
+ });
162
+ }
163
+ const sweeper = setInterval(() => {
164
+ const now = Date.now();
165
+ for (const s of sessions.values())
166
+ if (now - s.lastSeen > idleMs)
167
+ void s.transport.close();
168
+ }, Math.min(idleMs, 60_000));
169
+ sweeper.unref();
170
+ await httpServer.start(app, { port: http.port, host: http.host });
171
+ return {
172
+ app,
173
+ pool,
174
+ sessions: () => sessions.size,
175
+ close: async () => {
176
+ clearInterval(sweeper);
177
+ for (const s of sessions.values())
178
+ await s.transport.close().catch(() => undefined);
179
+ sessions.clear();
180
+ pool.stop();
181
+ await app.close();
182
+ },
183
+ };
184
+ }
185
+ //# 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,oCAAoC,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,OAAO,EAAe,MAAM,UAAU,CAAC;AAazD,kFAAkF;AAClF,MAAM,CAAC,MAAM,aAAa,GAAa,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAExD,SAAS,QAAQ,CAAC,KAAmB,EAAE,MAAc,EAAE,OAAe,EAAE,UAAkC,EAAE;IAC1G,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;AAC3I,CAAC;AAED,wKAAwK;AACxK;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,OAA0B;IACxD,MAAM,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,IAAK,CAAC;IACtC,MAAM,IA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,CAAC,QAAQ,GAAG,MAAM;gBAAE,KAAK,CAAC,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IAC7F,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC7B,OAAO,CAAC,KAAK,EAAE,CAAC;IAEhB,MAAM,UAAU,CAAC,KAAK,CAAC,GAAG,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,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,43 @@
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 } from './options.js';
5
+ import { ResultStore } from './output.js';
6
+ /** sha256 of a key: cache key of its catalog (the secret itself is never a map key). */
7
+ export declare function keyHash(apiKey: string): string;
8
+ /**
9
+ * State of one key (or of anonymous access): API client, catalog, result cache. Every MCP session of the key gets its own
10
+ * `Server`; catalog changes notify all of them (tools/list_changed).
11
+ */
12
+ export declare class KeyHub {
13
+ readonly options: McpServiceOptions;
14
+ readonly client: ApiClient;
15
+ readonly catalog: Catalog | null;
16
+ readonly store: ResultStore;
17
+ private readonly servers;
18
+ private timer;
19
+ lastUsed: number;
20
+ constructor(options: McpServiceOptions, apiKey: string | null);
21
+ get sessions(): number;
22
+ private get refreshMs();
23
+ /** Loads the catalog when never loaded or stale; 401/403 propagate, other errors keep the last catalog. */
24
+ ensureFresh(): Promise<void>;
25
+ private notifyChanged;
26
+ /** Re-reads the catalog; notifies sessions on change. Errors keep the last catalog. */
27
+ refresh(): Promise<boolean>;
28
+ startTimer(): void;
29
+ stop(): void;
30
+ /** An MCP server for one session of `route` with its params. */
31
+ createServer(route: McpRoute, params: Record<string, string>, lang: string | null, closeTimerWhenIdle: boolean, keyId: string | null): Server;
32
+ }
33
+ /** HTTP mode: one KeyHub per key hash (+ one anonymous); idle hubs are evicted. */
34
+ export declare class HubPool {
35
+ readonly options: McpServiceOptions;
36
+ private readonly hubs;
37
+ constructor(options: McpServiceOptions);
38
+ get size(): number;
39
+ acquire(apiKey: string | null): Promise<KeyHub>;
40
+ private sweep;
41
+ stop(): void;
42
+ }
43
+ //# 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,EAAgB,MAAM,cAAc,CAAC;AAC9E,OAAO,EAAE,WAAW,EAA8C,MAAM,aAAa,CAAC;AAItF,wFAAwF;AACxF,wBAAgB,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAE9C;AAGD;;;GAGG;AACH,qBAAa,MAAM;IAQL,QAAQ,CAAC,OAAO,EAAE,iBAAiB;IAP/C,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;IAC3B,QAAQ,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IACjC,QAAQ,CAAC,KAAK,cAAqB;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAC7C,OAAO,CAAC,KAAK,CAA+B;IAC5C,QAAQ,SAAc;gBAED,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAUtE,IAAI,QAAQ,IAAI,MAAM,CAErB;IAED,OAAO,KAAK,SAAS,GAEpB;IAED,2GAA2G;IACrG,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;YAcpB,aAAa;IAI3B,uFAAuF;IACjF,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC;IAWjC,UAAU,IAAI,IAAI;IAMlB,IAAI,IAAI,IAAI;IAKZ,gEAAgE;IAChE,YAAY,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,kBAAkB,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM;CAsI9I;AAGD,mFAAmF;AACnF,qBAAa,OAAO;IAGN,QAAQ,CAAC,OAAO,EAAE,iBAAiB;IAF/C,OAAO,CAAC,QAAQ,CAAC,IAAI,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;IAWb,IAAI,IAAI,IAAI;CAIb"}
@@ -0,0 +1,275 @@
1
+ import crypto from 'node:crypto';
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { CallToolRequestSchema, ErrorCode, GetPromptRequestSchema, 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
+ // generated by Claude (Opus 5.5), 2026-11-14; SDD sdd-nativemind-backend-handmade
12
+ /** sha256 of a key: cache key of its catalog (the secret itself is never a map key). */
13
+ export function keyHash(apiKey) {
14
+ return crypto.createHash('sha256').update(apiKey).digest('hex');
15
+ }
16
+ // generated by Claude (Opus 5.5), 2026-11-14; SDD sdd-nativemind-backend-handmade (from dropexpired services/mcp/src/server.ts KeyHub)
17
+ /**
18
+ * State of one key (or of anonymous access): API client, catalog, result cache. Every MCP session of the key gets its own
19
+ * `Server`; catalog changes notify all of them (tools/list_changed).
20
+ */
21
+ export class KeyHub {
22
+ options;
23
+ client;
24
+ catalog;
25
+ store = new ResultStore();
26
+ servers = new Set();
27
+ timer = null;
28
+ lastUsed = Date.now();
29
+ constructor(options, apiKey) {
30
+ this.options = options;
31
+ this.client = new ApiClient(options.api.url, apiKey, {
32
+ basePath: options.api.basePath,
33
+ ...(options.api.clientHeaders ? { clientHeaders: options.api.clientHeaders } : {}),
34
+ userAgent: options.api.userAgent ?? `${options.product.name}/${options.product.version ?? '1'}`,
35
+ ...(options.api.fetch ? { fetch: options.api.fetch } : {}),
36
+ });
37
+ this.catalog = options.catalog?.enabled && apiKey !== null ? new Catalog(this.client, options.catalog.toolsets ? new Set(options.catalog.toolsets) : null) : null;
38
+ }
39
+ get sessions() {
40
+ return this.servers.size;
41
+ }
42
+ get refreshMs() {
43
+ return this.options.catalog?.refreshMs ?? 60_000;
44
+ }
45
+ /** Loads the catalog when never loaded or stale; 401/403 propagate, other errors keep the last catalog. */
46
+ async ensureFresh() {
47
+ if (!this.catalog)
48
+ return;
49
+ if (!this.catalog.isLoaded) {
50
+ await this.catalog.refresh();
51
+ }
52
+ else if (Date.now() - this.catalog.loadedAt >= this.refreshMs) {
53
+ try {
54
+ const changed = await this.catalog.refresh();
55
+ if (changed)
56
+ await this.notifyChanged();
57
+ }
58
+ catch (error) {
59
+ if (error instanceof ApiCallError && (error.status === 401 || error.status === 403))
60
+ throw error;
61
+ }
62
+ }
63
+ }
64
+ async notifyChanged() {
65
+ await Promise.all([...this.servers].map((s) => s.sendToolListChanged().catch(() => undefined)));
66
+ }
67
+ /** Re-reads the catalog; notifies sessions on change. Errors keep the last catalog. */
68
+ async refresh() {
69
+ if (!this.catalog)
70
+ return false;
71
+ try {
72
+ const changed = await this.catalog.refresh();
73
+ if (changed)
74
+ await this.notifyChanged();
75
+ return changed;
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ }
81
+ startTimer() {
82
+ if (this.timer || !this.catalog)
83
+ return;
84
+ this.timer = setInterval(() => void this.refresh(), this.refreshMs);
85
+ this.timer.unref();
86
+ }
87
+ stop() {
88
+ if (this.timer)
89
+ clearInterval(this.timer);
90
+ this.timer = null;
91
+ }
92
+ /** An MCP server for one session of `route` with its params. */
93
+ createServer(route, params, lang, closeTimerWhenIdle, keyId) {
94
+ const o = this.options;
95
+ const routeCtx = { params, lang, api: this.client };
96
+ const instructions = typeof route.instructions === 'function' ? route.instructions(routeCtx) : (route.instructions ?? o.product.instructions);
97
+ const server = new Server({ name: o.product.name, version: o.product.version ?? '1.0.0' }, {
98
+ capabilities: { tools: { listChanged: true }, resources: {}, ...(o.prompts ? { prompts: {} } : {}) },
99
+ ...(instructions ? { instructions } : {}),
100
+ });
101
+ this.servers.add(server);
102
+ this.lastUsed = Date.now();
103
+ this.startTimer();
104
+ server.onclose = () => {
105
+ this.servers.delete(server);
106
+ this.lastUsed = Date.now();
107
+ if (this.servers.size === 0 && closeTimerWhenIdle)
108
+ this.stop();
109
+ };
110
+ const limits = { maxRows: o.limits?.maxRows ?? 25, maxBytes: o.limits?.maxBytes ?? 8192, scheme: o.resultScheme ?? o.product.name.replace(/-mcp$/, '') };
111
+ const useCatalog = (route.catalog ?? o.catalog?.enabled ?? false) && this.catalog !== null;
112
+ const catalogOps = () => (useCatalog ? this.catalog.operations.filter((op) => !route.filter || route.filter(op, params)) : []);
113
+ const manual = () => {
114
+ const own = route.tools?.(routeCtx) ?? [];
115
+ const fb = feedbackTools({ product: o.product.title, basePath: o.api.basePath, ...(o.feedback ?? {}) });
116
+ const names = new Set(own.map((t) => t.name));
117
+ return [...own, ...fb.filter((t) => !names.has(t.name))];
118
+ };
119
+ const translate = (t) => {
120
+ if (!lang || !o.i18n)
121
+ return t;
122
+ const tr = o.i18n(t.name, lang);
123
+ if (!tr)
124
+ return t;
125
+ return { ...t, ...(tr.title ? { title: tr.title, annotations: { ...(t.annotations ?? {}), title: tr.title } } : {}), ...(tr.description ? { description: tr.description } : {}) };
126
+ };
127
+ const clientName = () => {
128
+ const ci = server.getClientVersion?.();
129
+ return ci?.name ? `${ci.name}${ci.version ? ` ${ci.version}` : ''}` : 'MCP';
130
+ };
131
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
132
+ if (useCatalog)
133
+ await this.ensureFresh().catch(() => undefined);
134
+ const ops = catalogOps();
135
+ const tools = ops.map((op) => catalogTool(op, o.catalog ?? {}));
136
+ if (o.catalog?.jobs && hasJobs(ops))
137
+ tools.push(...JOB_TOOLS.filter((j) => !tools.some((t) => t.name === j.name)));
138
+ const seen = new Set(tools.map((t) => t.name));
139
+ for (const t of manual()) {
140
+ if (seen.has(t.name))
141
+ continue;
142
+ seen.add(t.name);
143
+ tools.push({ name: t.name, title: t.title, description: t.description, inputSchema: t.inputSchema, annotations: { title: t.title, ...(t.annotations ?? {}) } });
144
+ }
145
+ return { tools: tools.map(translate) };
146
+ });
147
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
148
+ const started = Date.now();
149
+ const name = req.params.name;
150
+ let result;
151
+ try {
152
+ this.client.setHeaders({ 'X-NM-MCP-Client': clientName() });
153
+ const tool = manual().find((t) => t.name === name);
154
+ if (tool) {
155
+ const ctx = { api: this.client, params, lang, client: clientName(), extra: {} };
156
+ try {
157
+ const args = tool.parse ? tool.parse(req.params.arguments ?? {}) : (req.params.arguments ?? {});
158
+ const value = await tool.call(args, ctx);
159
+ result = isCallToolResult(value) ? value : toolResult({ data: value }, limits, this.store);
160
+ }
161
+ catch (error) {
162
+ if (error instanceof ZodError) {
163
+ result = errorResult(new ApiCallError(400, 'VALIDATION_ERROR', 'Invalid arguments.', error.issues.map((i) => ({ field: i.path.join('.'), reason: i.message }))));
164
+ }
165
+ else {
166
+ result = errorResult(error);
167
+ }
168
+ }
169
+ }
170
+ else {
171
+ const r = useCatalog
172
+ ? await callCatalogTool({
173
+ api: this.client, store: this.store, limits, options: o.catalog ?? {},
174
+ ...(o.catalog?.rewriteArgs ? { rewriteArgs: o.catalog.rewriteArgs } : {}),
175
+ ...(o.catalog?.resultExtra ? { resultExtra: o.catalog.resultExtra } : {}),
176
+ onScopeDenied: () => void this.refresh(),
177
+ }, catalogOps(), name, req.params.arguments)
178
+ : null;
179
+ 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.`));
180
+ }
181
+ }
182
+ catch (error) {
183
+ result = errorResult(error);
184
+ }
185
+ o.onCall?.({ tool: name, route: route.path, ok: !result.isError, ms: Date.now() - started, keyHash: keyId, params });
186
+ return result;
187
+ });
188
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: (await o.resources?.list?.(this.client)) ?? [] }));
189
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({
190
+ resourceTemplates: [
191
+ { uriTemplate: `${limits.scheme}://results/{token}`, name: 'Full tool result', mimeType: 'application/json', description: 'Full result of a truncated tool call' },
192
+ ...(o.resources?.templates?.() ?? []),
193
+ ],
194
+ }));
195
+ server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
196
+ const uri = req.params.uri;
197
+ const m = new RegExp(`^${limits.scheme}://results/([A-Za-z0-9_-]+)$`).exec(uri);
198
+ if (m) {
199
+ const value = this.store.get(m[1]);
200
+ if (value === undefined)
201
+ throw new McpError(ErrorCode.InvalidParams, `Unknown or expired result ${uri}`);
202
+ return { contents: [{ uri, mimeType: 'application/json', text: JSON.stringify(value) }] };
203
+ }
204
+ try {
205
+ const r = await o.resources?.read?.(uri, this.client);
206
+ if (r)
207
+ return r;
208
+ }
209
+ catch (error) {
210
+ const code = error instanceof ApiCallError ? error.code : 'MCP_ERROR';
211
+ throw new McpError(ErrorCode.InvalidParams, `${code}: ${error instanceof Error ? error.message : String(error)}`);
212
+ }
213
+ throw new McpError(ErrorCode.InvalidParams, `Unknown resource ${uri}`);
214
+ });
215
+ if (o.prompts) {
216
+ const prompts = o.prompts;
217
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: prompts.list() }));
218
+ server.setRequestHandler(GetPromptRequestSchema, async (req) => {
219
+ try {
220
+ return prompts.get(req.params.name, req.params.arguments ?? {});
221
+ }
222
+ catch (error) {
223
+ throw new McpError(ErrorCode.InvalidParams, error instanceof Error ? error.message : String(error));
224
+ }
225
+ });
226
+ }
227
+ return server;
228
+ }
229
+ }
230
+ // generated by Claude (Opus 5.5), 2026-11-14; SDD sdd-nativemind-backend-handmade (from dropexpired services/mcp/src/server.ts HubPool)
231
+ /** HTTP mode: one KeyHub per key hash (+ one anonymous); idle hubs are evicted. */
232
+ export class HubPool {
233
+ options;
234
+ hubs = new Map();
235
+ constructor(options) {
236
+ this.options = options;
237
+ }
238
+ get size() {
239
+ return this.hubs.size;
240
+ }
241
+ async acquire(apiKey) {
242
+ this.sweep();
243
+ const hash = apiKey === null ? 'anonymous' : keyHash(apiKey);
244
+ let hub = this.hubs.get(hash);
245
+ if (!hub) {
246
+ hub = new KeyHub(this.options, apiKey);
247
+ this.hubs.set(hash, hub);
248
+ }
249
+ try {
250
+ await hub.ensureFresh();
251
+ }
252
+ catch (error) {
253
+ if (!hub.catalog?.isLoaded)
254
+ this.hubs.delete(hash);
255
+ throw error;
256
+ }
257
+ return hub;
258
+ }
259
+ sweep() {
260
+ const idleMs = Math.max(10 * (this.options.catalog?.refreshMs ?? 60_000), 10 * 60_000);
261
+ const now = Date.now();
262
+ for (const [hash, hub] of this.hubs) {
263
+ if (hub.sessions === 0 && now - hub.lastUsed > idleMs) {
264
+ hub.stop();
265
+ this.hubs.delete(hash);
266
+ }
267
+ }
268
+ }
269
+ stop() {
270
+ for (const hub of this.hubs.values())
271
+ hub.stop();
272
+ this.hubs.clear();
273
+ }
274
+ }
275
+ //# sourceMappingURL=hub.js.map