@moxn/mcp-kb 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/proxy.js CHANGED
@@ -7,20 +7,25 @@
7
7
  * Authentication is lazy - it only happens on the first actual request,
8
8
  * allowing the server to respond to MCP initialize immediately.
9
9
  *
10
- * File upload transformation: When LLMs provide content blocks with
11
- * `type: "file"` and a local path, the proxy uploads the file to
12
- * Supabase storage and transforms the block to `type: "storage"`
13
- * before forwarding to the server.
10
+ * Two tools are served here rather than remotely: `pull` and `push` move a
11
+ * document body to and from local disk so it never passes through the model
12
+ * (see checkout.ts). Everything else is forwarded.
14
13
  */
15
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
16
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
17
- import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
18
- import * as fs from 'node:fs/promises';
19
- import * as path from 'node:path';
14
+ import { McpServer } from '@modelcontextprotocol/server';
15
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
16
+ import { SkillsExtension } from '@modelcontextprotocol/server/ext/skills';
17
+ import { homedir } from 'node:os';
18
+ import { createRequire } from 'node:module';
19
+ import { checkoutTools, isCheckoutTool, resolveCheckoutRoot, runCheckoutTool, } from './checkout.js';
20
20
  import { getAuth, buildBaseUrl, parseFilesystems, parseWorkspace, } from './auth.js';
21
21
  import { SchemaRefresher } from './schema-refresh.js';
22
22
  import { createSharedSchemaCache } from './shared-schema-cache.js';
23
23
  import { vercelBypassHeaders } from './vercel-bypass.js';
24
+ import { RemoteRpcError, parseSkillsView, remoteSkillSource, withSkillsView, } from './skills.js';
25
+ /** The skills version this proxy asks the remote for (see skills.ts). */
26
+ const skillsView = parseSkillsView();
27
+ const MODERN_REVISION = '2026-07-28';
28
+ const PROXY_VERSION = createRequire(import.meta.url)('../package.json').version;
24
29
  // Filesystem filter from CLI args (injected into tool calls that support it)
25
30
  const filesystemFilter = parseFilesystems();
26
31
  // Tools that accept a `filesystem` parameter
@@ -47,6 +52,44 @@ function extractAuthenticateField(header, fieldName) {
47
52
  }
48
53
  return match[1] || match[2];
49
54
  }
55
+ /** Cap on how much of a server error body is ever repeated back. */
56
+ const ERROR_BODY_MAX = 500;
57
+ /**
58
+ * Secret shapes that can appear inside a server error payload — a stack trace,
59
+ * an echoed request, or a failed query's bind parameters (drizzle builds a
60
+ * query failure's message as `Failed query: … params: <values>`).
61
+ */
62
+ const SECRET_PATTERNS = [
63
+ /moxn_[A-Za-z0-9_-]{8,}/g,
64
+ /gh[psuor]_[A-Za-z0-9]{20,}/g,
65
+ /github_pat_[A-Za-z0-9_]{20,}/g,
66
+ /sk_[A-Za-z0-9_-]{20,}/g,
67
+ /eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,
68
+ /(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{16,}/gi,
69
+ ];
70
+ /**
71
+ * Make a server error body safe to repeat into a log or an error message.
72
+ *
73
+ * Both destinations persist: stderr goes to the MCP host's log file, and a
74
+ * thrown message reaches model context. An unbounded verbatim echo of a
75
+ * server payload puts whatever the server happened to include — secrets in a
76
+ * stack trace, bind parameters — into both. Truncate and scrub instead.
77
+ */
78
+ export function summarizeErrorBody(body) {
79
+ let out = body;
80
+ if (/Failed query:/.test(out)) {
81
+ // Bind parameters are arbitrary application values; no pattern covers
82
+ // them, so the whole message goes.
83
+ return '[server database error — query and bind parameters withheld]';
84
+ }
85
+ for (const pattern of SECRET_PATTERNS) {
86
+ pattern.lastIndex = 0;
87
+ out = out.replace(pattern, '[redacted]');
88
+ }
89
+ return out.length > ERROR_BODY_MAX
90
+ ? `${out.slice(0, ERROR_BODY_MAX)}… [truncated, ${out.length} bytes total]`
91
+ : out;
92
+ }
50
93
  /**
51
94
  * Parse OAuth challenge details from WWW-Authenticate header.
52
95
  */
@@ -121,20 +164,44 @@ async function mcpFetch(method, params, options = {}) {
121
164
  console.error(`[moxn-mcp-kb] mcpFetch: ${method}`);
122
165
  // Get auth lazily - may trigger OAuth flow
123
166
  const config = await getAuthConfig();
124
- const baseUrl = buildBaseUrl(config.workspace);
167
+ const baseUrl = withSkillsView(buildBaseUrl(config.workspace), skillsView);
125
168
  console.error(`[moxn-mcp-kb] POST ${baseUrl}`);
126
169
  const body = {
127
170
  jsonrpc: '2.0',
128
171
  id: Date.now(),
129
172
  method,
130
- params: params || {},
173
+ params: options.modern
174
+ ? {
175
+ ...(params || {}),
176
+ _meta: {
177
+ 'io.modelcontextprotocol/protocolVersion': MODERN_REVISION,
178
+ 'io.modelcontextprotocol/clientInfo': {
179
+ name: 'moxn-mcp-kb',
180
+ version: PROXY_VERSION,
181
+ },
182
+ 'io.modelcontextprotocol/clientCapabilities': {},
183
+ },
184
+ }
185
+ : params || {},
131
186
  };
187
+ const routingName = typeof params?.name === 'string'
188
+ ? params.name
189
+ : typeof params?.uri === 'string'
190
+ ? params.uri
191
+ : undefined;
132
192
  const response = await fetch(baseUrl, {
133
193
  method: 'POST',
134
194
  headers: {
135
195
  'Content-Type': 'application/json',
136
196
  Accept: 'application/json, text/event-stream',
137
197
  Authorization: `Bearer ${config.token}`,
198
+ ...(options.modern
199
+ ? {
200
+ 'MCP-Protocol-Version': MODERN_REVISION,
201
+ 'Mcp-Method': method,
202
+ ...(routingName ? { 'Mcp-Name': routingName } : {}),
203
+ }
204
+ : {}),
138
205
  // Clears the Vercel Auth wall on a protected deployment (staging/preview).
139
206
  // No-op unless MOXN_VERCEL_BYPASS is set AND baseUrl is our origin.
140
207
  ...vercelBypassHeaders(baseUrl),
@@ -145,7 +212,24 @@ async function mcpFetch(method, params, options = {}) {
145
212
  if (!response.ok) {
146
213
  const challenge = parseAuthChallenge(response.headers);
147
214
  const text = await response.text();
148
- console.error(`[moxn-mcp-kb] Response body: ${text}`);
215
+ // Truncated and scrubbed, never echoed whole. This is a SERVER error
216
+ // payload of unknown shape landing in the MCP host's log and — through
217
+ // the thrown errors below — in model context, both of which persist far
218
+ // longer than the request. A server-side stack trace can carry a failed
219
+ // query's bind parameters (drizzle puts them in the message).
220
+ console.error(`[moxn-mcp-kb] Response body: ${summarizeErrorBody(text)}`);
221
+ // The key rail's auth failures are terminal. A static MOXN_API_KEY is
222
+ // either valid or it isn't — there is no refresh/re-mint to attempt, and
223
+ // the server never sends a WWW-Authenticate challenge on this rail (see
224
+ // authenticate.ts's bareError), so retrying would just resubmit the same
225
+ // env var and fail again. Mirrors kb-cli's documented convention: a bad
226
+ // key fails fast and says so (packages/kb-cli/src/auth.ts).
227
+ if (config.rail === 'api-key' &&
228
+ (response.status === 401 || response.status === 403)) {
229
+ throw new Error(`[moxn-mcp-kb] MOXN_API_KEY rejected (${response.status}): ${summarizeErrorBody(text)}. ` +
230
+ 'Static keys are not retried automatically — verify the key is valid, ' +
231
+ 'unrevoked, and has access to this workspace, or unset MOXN_API_KEY to use OAuth.');
232
+ }
149
233
  // Auto-recover from invalid/revoked tokens and scope challenges.
150
234
  // Retry exactly once to prevent infinite loops. Skipped entirely when the
151
235
  // caller opted out of auth recovery (background schema checks).
@@ -168,175 +252,16 @@ async function mcpFetch(method, params, options = {}) {
168
252
  console.error('[moxn-mcp-kb] Re-authentication complete, retrying request...');
169
253
  return mcpFetch(method, params, { ...options, attempt: attempt + 1 });
170
254
  }
171
- throw new Error(`MCP request failed: ${response.status} ${text}`);
255
+ throw new Error(`MCP request failed: ${response.status} ${summarizeErrorBody(text)}`);
172
256
  }
173
257
  const result = await response.json();
174
258
  // Handle JSON-RPC error response
175
259
  if (result.error) {
176
260
  console.error(`[moxn-mcp-kb] JSON-RPC error: ${JSON.stringify(result.error)}`);
177
- throw new Error(result.error.message || 'Unknown MCP error');
261
+ throw new RemoteRpcError(result.error.message || 'Unknown MCP error', result.error.code);
178
262
  }
179
263
  return result.result;
180
264
  }
181
- // ============================================
182
- // File Upload Infrastructure
183
- // ============================================
184
- /**
185
- * Infer MIME type from file path extension
186
- */
187
- function inferMimeType(filePath) {
188
- const ext = path.extname(filePath).toLowerCase();
189
- const mimeMap = {
190
- // Images
191
- '.png': 'image/png',
192
- '.jpg': 'image/jpeg',
193
- '.jpeg': 'image/jpeg',
194
- '.gif': 'image/gif',
195
- '.webp': 'image/webp',
196
- // PDF
197
- '.pdf': 'application/pdf',
198
- // CSV
199
- '.csv': 'text/csv',
200
- // Documents
201
- '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
202
- '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
203
- '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
204
- '.doc': 'application/msword',
205
- '.xls': 'application/vnd.ms-excel',
206
- '.ppt': 'application/vnd.ms-powerpoint',
207
- '.odt': 'application/vnd.oasis.opendocument.text',
208
- '.ods': 'application/vnd.oasis.opendocument.spreadsheet',
209
- '.rtf': 'application/rtf',
210
- // Text/Code
211
- '.txt': 'text/plain',
212
- '.md': 'text/markdown',
213
- '.json': 'application/json',
214
- '.xml': 'application/xml',
215
- '.yaml': 'text/yaml',
216
- '.yml': 'text/yaml',
217
- '.html': 'text/html',
218
- '.htm': 'text/html',
219
- // Archives
220
- '.zip': 'application/zip',
221
- '.gz': 'application/gzip',
222
- '.tar': 'application/x-tar',
223
- // Other
224
- '.svg': 'image/svg+xml',
225
- '.epub': 'application/epub+zip',
226
- };
227
- return mimeMap[ext] || 'application/octet-stream';
228
- }
229
- /**
230
- * Validate file path for security
231
- *
232
- * Only allows absolute paths to prevent directory traversal.
233
- * Does not restrict to specific directories - trusts LLM's file path.
234
- */
235
- function validateFilePath(filePath) {
236
- if (!path.isAbsolute(filePath)) {
237
- throw new Error(`File path must be absolute: ${filePath}`);
238
- }
239
- }
240
- /**
241
- * Upload a local file to Moxn storage via presigned URL
242
- *
243
- * Flow:
244
- * 1. Read file from local disk
245
- * 2. Get presigned upload URL from Moxn API
246
- * 3. Upload file directly to Supabase
247
- * 4. Return storage key for use in content block
248
- */
249
- async function uploadLocalFile(filePath, mediaTypeOverride) {
250
- validateFilePath(filePath);
251
- // Read file from disk
252
- const fileBuffer = await fs.readFile(filePath);
253
- const fileName = path.basename(filePath);
254
- const mimeType = mediaTypeOverride || inferMimeType(filePath);
255
- console.error(`[moxn-mcp-kb] Uploading file: ${fileName} (${mimeType}, ${fileBuffer.length} bytes)`);
256
- // Call MCP tool to get presigned upload URL
257
- // This uses the same OAuth auth flow as other MCP tools
258
- console.error(`[moxn-mcp-kb] Calling upload_url MCP tool...`);
259
- const uploadUrlResult = (await mcpFetch('tools/call', {
260
- name: 'upload_url',
261
- arguments: { type: mimeType, filename: fileName },
262
- }));
263
- // Parse the JSON result from the tool response
264
- const resultText = uploadUrlResult.content?.[0]?.text;
265
- if (!resultText) {
266
- throw new Error('No response from upload_url tool');
267
- }
268
- const { path: storagePath, token: uploadToken } = JSON.parse(resultText);
269
- console.error(`[moxn-mcp-kb] Uploading to storage path: ${storagePath}`);
270
- // Upload file directly to Supabase via presigned URL
271
- const uploadRes = await fetch(uploadToken, {
272
- method: 'PUT',
273
- headers: {
274
- 'Content-Type': mimeType,
275
- ...vercelBypassHeaders(uploadToken),
276
- },
277
- body: fileBuffer,
278
- });
279
- if (!uploadRes.ok) {
280
- const text = await uploadRes.text();
281
- throw new Error(`Failed to upload file: ${uploadRes.status} ${text}`);
282
- }
283
- console.error(`[moxn-mcp-kb] File uploaded successfully: ${storagePath}`);
284
- return { key: storagePath, mimeType };
285
- }
286
- /**
287
- * Check if a content block has type: 'file'
288
- */
289
- function isFileContentBlock(block) {
290
- return block.type === 'file' && typeof block.path === 'string';
291
- }
292
- /**
293
- * Transform content blocks - upload local files before sending to server
294
- *
295
- * For each content block with `type: "file"`:
296
- * 1. Upload the file to Supabase storage
297
- * 2. Transform the block to `type: "storage"` with the storage key
298
- */
299
- async function transformContentBlocks(blocks) {
300
- const transformed = [];
301
- for (const block of blocks) {
302
- if (isFileContentBlock(block)) {
303
- // Upload the file and transform to storage block
304
- const { key, mimeType } = await uploadLocalFile(block.path, block.mediaType);
305
- const storageBlock = {
306
- blockType: block.blockType,
307
- type: 'storage',
308
- key,
309
- mediaType: mimeType,
310
- };
311
- // Preserve optional fields
312
- if (block.alt)
313
- storageBlock.alt = block.alt;
314
- if (block.filename)
315
- storageBlock.filename = block.filename;
316
- // Preserve CSV-specific fields
317
- if (block.headers)
318
- storageBlock.headers = block.headers;
319
- if (block.rowCount !== undefined)
320
- storageBlock.rowCount = block.rowCount;
321
- transformed.push(storageBlock);
322
- }
323
- else {
324
- // Pass through unchanged
325
- transformed.push(block);
326
- }
327
- }
328
- return transformed;
329
- }
330
- /**
331
- * Check if any content blocks in the arguments need file upload transformation
332
- */
333
- function hasFileBlocks(args) {
334
- const content = args.content;
335
- if (!content || !Array.isArray(content)) {
336
- return false;
337
- }
338
- return content.some(isFileContentBlock);
339
- }
340
265
  /**
341
266
  * Create and start the proxy server.
342
267
  * Server starts immediately; authentication happens lazily on first request.
@@ -346,21 +271,10 @@ export async function startProxy() {
346
271
  // (auth happens lazily)
347
272
  const workspace = parseWorkspace();
348
273
  console.error(`[moxn-mcp-kb] Starting server for workspace: ${workspace ?? 'unknown'}`);
349
- const server = new Server({
350
- name: 'moxn-kb',
351
- version: '0.1.0',
352
- }, {
353
- capabilities: {
354
- // listChanged: the remote HTTP server is stateless and cannot push
355
- // schema updates, so the PROXY owns staleness detection — it
356
- // re-checks the remote tools/list on tool activity and emits
357
- // notifications/tools/list_changed when the schema moves (e.g. after
358
- // a server deploy). Claude Code honors the notification and re-pulls
359
- // schemas.
360
- tools: { listChanged: true },
361
- resources: {},
362
- },
363
- });
274
+ // The instance serving the connection. `serveStdio` builds one per
275
+ // connection (plus a `server/discover` probe it may discard), so the
276
+ // refresher notifies whichever instance is current.
277
+ let current = null;
364
278
  // Detects remote tool-schema drift and notifies the client. There is no
365
279
  // background timer — checks piggyback on tool activity (noteToolActivity),
366
280
  // dedupe machine-wide through a shared cache, and stop after repeated auth
@@ -376,7 +290,15 @@ export async function startProxy() {
376
290
  }));
377
291
  return result.tools ?? [];
378
292
  },
379
- notifyToolListChanged: () => server.sendToolListChanged(),
293
+ notifyToolListChanged: async () => {
294
+ try {
295
+ await current?.server.sendToolListChanged();
296
+ }
297
+ catch (error) {
298
+ const message = error instanceof Error ? error.message : String(error);
299
+ console.error(`[moxn-mcp-kb] tools/list_changed not delivered: ${message}`);
300
+ }
301
+ },
380
302
  canFetch: () => authConfig !== null,
381
303
  intervalMs: Number.isFinite(intervalOverride) && intervalOverride > 0
382
304
  ? intervalOverride
@@ -390,8 +312,7 @@ export async function startProxy() {
390
312
  : undefined,
391
313
  log: (message) => console.error(`[moxn-mcp-kb] ${message}`),
392
314
  });
393
- // Proxy tools/list requests (auth happens lazily on first call)
394
- server.setRequestHandler(ListToolsRequestSchema, async () => {
315
+ async function listTools() {
395
316
  console.error('[moxn-mcp-kb] tools/list requested');
396
317
  try {
397
318
  console.error('[moxn-mcp-kb] Fetching tools from remote server...');
@@ -405,12 +326,20 @@ export async function startProxy() {
405
326
  console.error(`[moxn-mcp-kb] Tools: ${names}`);
406
327
  }
407
328
  // Baseline for staleness detection: "changed" means "differs from the
408
- // list the client actually saw".
329
+ // list the client actually saw". The local tools never change at runtime
330
+ // and every background check compares against the REMOTE list, so they
331
+ // stay out of the baseline or every check would report a change.
409
332
  schemaRefresher.recordServedTools(result.tools ?? []);
410
333
  // Publish to the machine-wide cache so sibling proxies (other Claude
411
334
  // Code sessions on this workspace) skip their own remote check.
412
335
  schemaRefresher.noteRemoteToolList(result.tools ?? []);
413
- return result;
336
+ return {
337
+ ...result,
338
+ tools: [
339
+ ...(result.tools ?? []).filter((tool) => !isCheckoutTool(tool.name)),
340
+ ...checkoutTools,
341
+ ],
342
+ };
414
343
  }
415
344
  catch (error) {
416
345
  const message = error instanceof Error ? error.message : String(error);
@@ -438,84 +367,99 @@ export async function startProxy() {
438
367
  schemaRefresher.recordServedTools(fallback.tools);
439
368
  return fallback;
440
369
  }
441
- });
442
- // Proxy tools/call requests with file upload transformation
443
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
444
- try {
445
- let args = request.params.arguments;
446
- // Special handling for sections tool - transform file blocks to storage blocks
447
- if (request.params.name === 'sections' && args) {
448
- // Check both content (for create) and newContent (for update)
449
- const hasFilesInContent = hasFileBlocks(args);
450
- const hasFilesInNewContent = args.newContent
451
- ? hasFileBlocks({ content: args.newContent })
452
- : false;
453
- if (hasFilesInContent || hasFilesInNewContent) {
454
- console.error('[moxn-mcp-kb] Transforming file blocks to storage blocks...');
455
- // Clone args to avoid mutating the original
456
- args = { ...args };
457
- if (hasFilesInContent) {
458
- const content = args.content;
459
- const transformedContent = await transformContentBlocks(content);
460
- args.content = transformedContent;
461
- }
462
- if (hasFilesInNewContent) {
463
- const newContent = args.newContent;
464
- const transformedNewContent = await transformContentBlocks(newContent);
465
- args.newContent = transformedNewContent;
466
- }
467
- console.error('[moxn-mcp-kb] File transformation complete, forwarding to server');
370
+ }
371
+ /**
372
+ * Forward one tool call to the remote server: the hard filesystem boundary,
373
+ * then the request, then the staleness checks. `pull` and `push` go through
374
+ * this too, so they get the same treatment as the same call from the model.
375
+ */
376
+ async function callRemoteTool(name, rawArgs) {
377
+ let args = rawArgs;
378
+ // Enforce filesystem boundary from --filesystems CLI arg / MOXN_FILESYSTEMS env var.
379
+ // This is a hard boundary: the agent cannot escape the configured filesystem scope.
380
+ if (filesystemFilter &&
381
+ filesystemFilter.length > 0 &&
382
+ FILESYSTEM_AWARE_TOOLS.has(name)) {
383
+ args = args ? { ...args } : {};
384
+ const agentFs = args.filesystem;
385
+ if (agentFs) {
386
+ // Agent specified a filesystem — verify it's in the allowed list
387
+ if (!filesystemFilter.includes(agentFs)) {
388
+ return {
389
+ content: [
390
+ {
391
+ type: 'text',
392
+ text: JSON.stringify({
393
+ error: `Filesystem "${agentFs}" is not in the allowed list. This connection is restricted to: ${filesystemFilter.join(', ')}`,
394
+ }),
395
+ },
396
+ ],
397
+ isError: true,
398
+ };
468
399
  }
400
+ // Agent's choice is allowed — pass through
469
401
  }
470
- // Enforce filesystem boundary from --filesystems CLI arg / MOXN_FILESYSTEMS env var.
471
- // This is a hard boundary: the agent cannot escape the configured filesystem scope.
472
- if (filesystemFilter &&
473
- filesystemFilter.length > 0 &&
474
- FILESYSTEM_AWARE_TOOLS.has(request.params.name)) {
475
- args = args ? { ...args } : {};
476
- const agentFs = args.filesystem;
477
- if (agentFs) {
478
- // Agent specified a filesystem — verify it's in the allowed list
479
- if (!filesystemFilter.includes(agentFs)) {
480
- return {
481
- content: [
482
- {
483
- type: 'text',
484
- text: JSON.stringify({
485
- error: `Filesystem "${agentFs}" is not in the allowed list. This connection is restricted to: ${filesystemFilter.join(', ')}`,
486
- }),
487
- },
488
- ],
489
- isError: true,
490
- };
491
- }
492
- // Agent's choice is allowed — pass through
493
- }
494
- else {
495
- // Agent didn't specify — inject the configured default
496
- if (filesystemFilter.length === 1) {
497
- args.filesystem = filesystemFilter[0];
498
- }
499
- // If multiple allowed filesystems and agent didn't pick,
500
- // don't inject — let server return results from all allowed FSes.
501
- // The server-side authCtx still scopes to the user's accessible FSes.
402
+ else {
403
+ // Agent didn't specify — inject the configured default
404
+ if (filesystemFilter.length === 1) {
405
+ args.filesystem = filesystemFilter[0];
502
406
  }
407
+ // If multiple allowed filesystems and agent didn't pick,
408
+ // don't inject — let server return results from all allowed FSes.
409
+ // The server-side authCtx still scopes to the user's accessible FSes.
503
410
  }
504
- const result = (await mcpFetch('tools/call', {
505
- name: request.params.name,
506
- arguments: args,
507
- }));
508
- // A tool-level error whose text smells like a zod schema mismatch is
509
- // the fingerprint of a stale cached schema — kick a background
510
- // re-check (fire-and-forget; must not delay the response).
511
- if (result?.isError) {
512
- schemaRefresher.refreshAfterToolError(JSON.stringify(result.content ?? []));
411
+ }
412
+ const result = (await mcpFetch('tools/call', {
413
+ name,
414
+ arguments: args,
415
+ }));
416
+ // A tool-level error whose text smells like a zod schema mismatch is
417
+ // the fingerprint of a stale cached schema — kick a background
418
+ // re-check (fire-and-forget; must not delay the response).
419
+ if (result?.isError) {
420
+ schemaRefresher.refreshAfterToolError(JSON.stringify(result.content ?? []));
421
+ }
422
+ // The round trip succeeded (auth + transport work) — piggyback a
423
+ // throttled staleness check so active sessions track server deploys.
424
+ // Fire-and-forget; must not delay the response.
425
+ void schemaRefresher.noteToolActivity();
426
+ return result;
427
+ }
428
+ /**
429
+ * The MCP roots the client reports, or [] when it has none to offer. Roots
430
+ * are a 2025-era server→client request; a 2026-07-28 connection has no such
431
+ * channel (the SDK throws), so checkout falls back to its other roots.
432
+ */
433
+ async function clientRoots() {
434
+ try {
435
+ const low = current?.server;
436
+ if (!low?.getClientCapabilities()?.roots)
437
+ return [];
438
+ const { roots } = await low.listRoots(undefined, { timeout: 3_000 });
439
+ return roots.map((root) => root.uri);
440
+ }
441
+ catch {
442
+ return [];
443
+ }
444
+ }
445
+ // tools/call — pull and push are handled locally, everything else forwarded.
446
+ async function callTool(name, args) {
447
+ try {
448
+ if (isCheckoutTool(name)) {
449
+ const config = await getAuthConfig();
450
+ return await runCheckoutTool(name, args, {
451
+ workspace: config.workspace,
452
+ baseUrl: buildBaseUrl(config.workspace),
453
+ root: () => resolveCheckoutRoot({
454
+ override: process.env.MOXN_CHECKOUT_ROOT,
455
+ listRoots: clientRoots,
456
+ cwd: process.cwd(),
457
+ home: homedir(),
458
+ }),
459
+ callTool: callRemoteTool,
460
+ });
513
461
  }
514
- // The round trip succeeded (auth + transport work) — piggyback a
515
- // throttled staleness check so active sessions track server deploys.
516
- // Fire-and-forget; must not delay the response.
517
- void schemaRefresher.noteToolActivity();
518
- return result;
462
+ return await callRemoteTool(name, args);
519
463
  }
520
464
  catch (error) {
521
465
  const message = error instanceof Error ? error.message : 'Unknown error';
@@ -529,38 +473,40 @@ export async function startProxy() {
529
473
  isError: true,
530
474
  };
531
475
  }
476
+ }
477
+ /**
478
+ * One server per connection. The SAME factory serves both protocol eras
479
+ * (`serveStdio` picks by the opening exchange): a 2025-era host gets the
480
+ * tools exactly as before; a 2026-07-28 host (Claude Code with Skills over
481
+ * MCP) also gets the workspace's skills through the Skills extension,
482
+ * forwarded to the remote's modern leg.
483
+ */
484
+ function buildServer() {
485
+ const mcp = new McpServer({ name: 'moxn-kb', version: PROXY_VERSION });
486
+ // listChanged: the remote HTTP server is stateless and cannot push
487
+ // schema updates, so the PROXY owns staleness detection — it re-checks
488
+ // the remote tools/list on tool activity and emits
489
+ // notifications/tools/list_changed when the schema moves (e.g. after a
490
+ // server deploy). Claude Code honors the notification and re-pulls.
491
+ mcp.server.registerCapabilities({ tools: { listChanged: true } });
492
+ // Low-level handlers: the tool list is the REMOTE's, fetched lazily, so
493
+ // it cannot be declared up front through registerTool.
494
+ mcp.server.setRequestHandler('tools/list', async () => (await listTools()));
495
+ mcp.server.setRequestHandler('tools/call', async (request) => (await callTool(request.params.name, request.params.arguments)));
496
+ new SkillsExtension({
497
+ source: remoteSkillSource((method, params) => mcpFetch(method, params, { modern: true })),
498
+ // The remote's own hint is 0 by default; the proxy adds no caching.
499
+ cacheHint: { ttlMs: 0, cacheScope: 'private' },
500
+ onWarning: (w) => console.error(`[moxn-mcp-kb] skills: ${w.path}: ${w.message}`),
501
+ }).attach(mcp);
502
+ current = mcp;
503
+ return mcp;
504
+ }
505
+ // Serve stdio IMMEDIATELY — the host's opening exchange (initialize or
506
+ // server/discover) is answered before any auth; auth stays lazy.
507
+ serveStdio(buildServer, {
508
+ onerror: (error) => console.error(`[moxn-mcp-kb] ${error.message}`),
532
509
  });
533
- // Proxy resources/list requests (if the server supports them)
534
- server.setRequestHandler(ListResourcesRequestSchema, async () => {
535
- try {
536
- const result = (await mcpFetch('resources/list'));
537
- return result;
538
- }
539
- catch {
540
- // Resources might not be supported, return empty list
541
- return { resources: [] };
542
- }
543
- });
544
- // Proxy resources/read requests
545
- server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
546
- try {
547
- const result = await mcpFetch('resources/read', {
548
- uri: request.params.uri,
549
- });
550
- return result;
551
- }
552
- catch (error) {
553
- const message = error instanceof Error ? error.message : 'Unknown error';
554
- console.error('[moxn-mcp-kb] Error reading resource:', message);
555
- return {
556
- contents: [{ uri: request.params.uri, text: `Error: ${message}` }],
557
- };
558
- }
559
- });
560
- // Connect to stdio transport IMMEDIATELY
561
- // This allows the server to respond to MCP initialize before auth
562
- const transport = new StdioServerTransport();
563
- await server.connect(transport);
564
510
  console.error('[moxn-mcp-kb] Server started, listening on stdio');
565
511
  }
566
512
  //# sourceMappingURL=proxy.js.map