@moxn/mcp-kb 0.5.0 → 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/README.md +8 -6
- package/dist/checkout.d.ts +86 -0
- package/dist/checkout.d.ts.map +1 -0
- package/dist/checkout.js +582 -0
- package/dist/checkout.js.map +1 -0
- package/dist/proxy.d.ts +12 -4
- package/dist/proxy.d.ts.map +1 -1
- package/dist/proxy.js +232 -298
- package/dist/proxy.js.map +1 -1
- package/dist/skills.d.ts +32 -0
- package/dist/skills.d.ts.map +1 -0
- package/dist/skills.js +86 -0
- package/dist/skills.js.map +1 -0
- package/package.json +4 -3
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
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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 {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import
|
|
19
|
-
import
|
|
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:
|
|
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,12 @@ 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
|
-
|
|
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)}`);
|
|
149
221
|
// The key rail's auth failures are terminal. A static MOXN_API_KEY is
|
|
150
222
|
// either valid or it isn't — there is no refresh/re-mint to attempt, and
|
|
151
223
|
// the server never sends a WWW-Authenticate challenge on this rail (see
|
|
@@ -154,7 +226,7 @@ async function mcpFetch(method, params, options = {}) {
|
|
|
154
226
|
// key fails fast and says so (packages/kb-cli/src/auth.ts).
|
|
155
227
|
if (config.rail === 'api-key' &&
|
|
156
228
|
(response.status === 401 || response.status === 403)) {
|
|
157
|
-
throw new Error(`[moxn-mcp-kb] MOXN_API_KEY rejected (${response.status}): ${text}. ` +
|
|
229
|
+
throw new Error(`[moxn-mcp-kb] MOXN_API_KEY rejected (${response.status}): ${summarizeErrorBody(text)}. ` +
|
|
158
230
|
'Static keys are not retried automatically — verify the key is valid, ' +
|
|
159
231
|
'unrevoked, and has access to this workspace, or unset MOXN_API_KEY to use OAuth.');
|
|
160
232
|
}
|
|
@@ -180,175 +252,16 @@ async function mcpFetch(method, params, options = {}) {
|
|
|
180
252
|
console.error('[moxn-mcp-kb] Re-authentication complete, retrying request...');
|
|
181
253
|
return mcpFetch(method, params, { ...options, attempt: attempt + 1 });
|
|
182
254
|
}
|
|
183
|
-
throw new Error(`MCP request failed: ${response.status} ${text}`);
|
|
255
|
+
throw new Error(`MCP request failed: ${response.status} ${summarizeErrorBody(text)}`);
|
|
184
256
|
}
|
|
185
257
|
const result = await response.json();
|
|
186
258
|
// Handle JSON-RPC error response
|
|
187
259
|
if (result.error) {
|
|
188
260
|
console.error(`[moxn-mcp-kb] JSON-RPC error: ${JSON.stringify(result.error)}`);
|
|
189
|
-
throw new
|
|
261
|
+
throw new RemoteRpcError(result.error.message || 'Unknown MCP error', result.error.code);
|
|
190
262
|
}
|
|
191
263
|
return result.result;
|
|
192
264
|
}
|
|
193
|
-
// ============================================
|
|
194
|
-
// File Upload Infrastructure
|
|
195
|
-
// ============================================
|
|
196
|
-
/**
|
|
197
|
-
* Infer MIME type from file path extension
|
|
198
|
-
*/
|
|
199
|
-
function inferMimeType(filePath) {
|
|
200
|
-
const ext = path.extname(filePath).toLowerCase();
|
|
201
|
-
const mimeMap = {
|
|
202
|
-
// Images
|
|
203
|
-
'.png': 'image/png',
|
|
204
|
-
'.jpg': 'image/jpeg',
|
|
205
|
-
'.jpeg': 'image/jpeg',
|
|
206
|
-
'.gif': 'image/gif',
|
|
207
|
-
'.webp': 'image/webp',
|
|
208
|
-
// PDF
|
|
209
|
-
'.pdf': 'application/pdf',
|
|
210
|
-
// CSV
|
|
211
|
-
'.csv': 'text/csv',
|
|
212
|
-
// Documents
|
|
213
|
-
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
214
|
-
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
215
|
-
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
216
|
-
'.doc': 'application/msword',
|
|
217
|
-
'.xls': 'application/vnd.ms-excel',
|
|
218
|
-
'.ppt': 'application/vnd.ms-powerpoint',
|
|
219
|
-
'.odt': 'application/vnd.oasis.opendocument.text',
|
|
220
|
-
'.ods': 'application/vnd.oasis.opendocument.spreadsheet',
|
|
221
|
-
'.rtf': 'application/rtf',
|
|
222
|
-
// Text/Code
|
|
223
|
-
'.txt': 'text/plain',
|
|
224
|
-
'.md': 'text/markdown',
|
|
225
|
-
'.json': 'application/json',
|
|
226
|
-
'.xml': 'application/xml',
|
|
227
|
-
'.yaml': 'text/yaml',
|
|
228
|
-
'.yml': 'text/yaml',
|
|
229
|
-
'.html': 'text/html',
|
|
230
|
-
'.htm': 'text/html',
|
|
231
|
-
// Archives
|
|
232
|
-
'.zip': 'application/zip',
|
|
233
|
-
'.gz': 'application/gzip',
|
|
234
|
-
'.tar': 'application/x-tar',
|
|
235
|
-
// Other
|
|
236
|
-
'.svg': 'image/svg+xml',
|
|
237
|
-
'.epub': 'application/epub+zip',
|
|
238
|
-
};
|
|
239
|
-
return mimeMap[ext] || 'application/octet-stream';
|
|
240
|
-
}
|
|
241
|
-
/**
|
|
242
|
-
* Validate file path for security
|
|
243
|
-
*
|
|
244
|
-
* Only allows absolute paths to prevent directory traversal.
|
|
245
|
-
* Does not restrict to specific directories - trusts LLM's file path.
|
|
246
|
-
*/
|
|
247
|
-
function validateFilePath(filePath) {
|
|
248
|
-
if (!path.isAbsolute(filePath)) {
|
|
249
|
-
throw new Error(`File path must be absolute: ${filePath}`);
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
/**
|
|
253
|
-
* Upload a local file to Moxn storage via presigned URL
|
|
254
|
-
*
|
|
255
|
-
* Flow:
|
|
256
|
-
* 1. Read file from local disk
|
|
257
|
-
* 2. Get presigned upload URL from Moxn API
|
|
258
|
-
* 3. Upload file directly to Supabase
|
|
259
|
-
* 4. Return storage key for use in content block
|
|
260
|
-
*/
|
|
261
|
-
async function uploadLocalFile(filePath, mediaTypeOverride) {
|
|
262
|
-
validateFilePath(filePath);
|
|
263
|
-
// Read file from disk
|
|
264
|
-
const fileBuffer = await fs.readFile(filePath);
|
|
265
|
-
const fileName = path.basename(filePath);
|
|
266
|
-
const mimeType = mediaTypeOverride || inferMimeType(filePath);
|
|
267
|
-
console.error(`[moxn-mcp-kb] Uploading file: ${fileName} (${mimeType}, ${fileBuffer.length} bytes)`);
|
|
268
|
-
// Call MCP tool to get presigned upload URL
|
|
269
|
-
// This uses the same OAuth auth flow as other MCP tools
|
|
270
|
-
console.error(`[moxn-mcp-kb] Calling upload_url MCP tool...`);
|
|
271
|
-
const uploadUrlResult = (await mcpFetch('tools/call', {
|
|
272
|
-
name: 'upload_url',
|
|
273
|
-
arguments: { type: mimeType, filename: fileName },
|
|
274
|
-
}));
|
|
275
|
-
// Parse the JSON result from the tool response
|
|
276
|
-
const resultText = uploadUrlResult.content?.[0]?.text;
|
|
277
|
-
if (!resultText) {
|
|
278
|
-
throw new Error('No response from upload_url tool');
|
|
279
|
-
}
|
|
280
|
-
const { path: storagePath, token: uploadToken } = JSON.parse(resultText);
|
|
281
|
-
console.error(`[moxn-mcp-kb] Uploading to storage path: ${storagePath}`);
|
|
282
|
-
// Upload file directly to Supabase via presigned URL
|
|
283
|
-
const uploadRes = await fetch(uploadToken, {
|
|
284
|
-
method: 'PUT',
|
|
285
|
-
headers: {
|
|
286
|
-
'Content-Type': mimeType,
|
|
287
|
-
...vercelBypassHeaders(uploadToken),
|
|
288
|
-
},
|
|
289
|
-
body: fileBuffer,
|
|
290
|
-
});
|
|
291
|
-
if (!uploadRes.ok) {
|
|
292
|
-
const text = await uploadRes.text();
|
|
293
|
-
throw new Error(`Failed to upload file: ${uploadRes.status} ${text}`);
|
|
294
|
-
}
|
|
295
|
-
console.error(`[moxn-mcp-kb] File uploaded successfully: ${storagePath}`);
|
|
296
|
-
return { key: storagePath, mimeType };
|
|
297
|
-
}
|
|
298
|
-
/**
|
|
299
|
-
* Check if a content block has type: 'file'
|
|
300
|
-
*/
|
|
301
|
-
function isFileContentBlock(block) {
|
|
302
|
-
return block.type === 'file' && typeof block.path === 'string';
|
|
303
|
-
}
|
|
304
|
-
/**
|
|
305
|
-
* Transform content blocks - upload local files before sending to server
|
|
306
|
-
*
|
|
307
|
-
* For each content block with `type: "file"`:
|
|
308
|
-
* 1. Upload the file to Supabase storage
|
|
309
|
-
* 2. Transform the block to `type: "storage"` with the storage key
|
|
310
|
-
*/
|
|
311
|
-
async function transformContentBlocks(blocks) {
|
|
312
|
-
const transformed = [];
|
|
313
|
-
for (const block of blocks) {
|
|
314
|
-
if (isFileContentBlock(block)) {
|
|
315
|
-
// Upload the file and transform to storage block
|
|
316
|
-
const { key, mimeType } = await uploadLocalFile(block.path, block.mediaType);
|
|
317
|
-
const storageBlock = {
|
|
318
|
-
blockType: block.blockType,
|
|
319
|
-
type: 'storage',
|
|
320
|
-
key,
|
|
321
|
-
mediaType: mimeType,
|
|
322
|
-
};
|
|
323
|
-
// Preserve optional fields
|
|
324
|
-
if (block.alt)
|
|
325
|
-
storageBlock.alt = block.alt;
|
|
326
|
-
if (block.filename)
|
|
327
|
-
storageBlock.filename = block.filename;
|
|
328
|
-
// Preserve CSV-specific fields
|
|
329
|
-
if (block.headers)
|
|
330
|
-
storageBlock.headers = block.headers;
|
|
331
|
-
if (block.rowCount !== undefined)
|
|
332
|
-
storageBlock.rowCount = block.rowCount;
|
|
333
|
-
transformed.push(storageBlock);
|
|
334
|
-
}
|
|
335
|
-
else {
|
|
336
|
-
// Pass through unchanged
|
|
337
|
-
transformed.push(block);
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
return transformed;
|
|
341
|
-
}
|
|
342
|
-
/**
|
|
343
|
-
* Check if any content blocks in the arguments need file upload transformation
|
|
344
|
-
*/
|
|
345
|
-
function hasFileBlocks(args) {
|
|
346
|
-
const content = args.content;
|
|
347
|
-
if (!content || !Array.isArray(content)) {
|
|
348
|
-
return false;
|
|
349
|
-
}
|
|
350
|
-
return content.some(isFileContentBlock);
|
|
351
|
-
}
|
|
352
265
|
/**
|
|
353
266
|
* Create and start the proxy server.
|
|
354
267
|
* Server starts immediately; authentication happens lazily on first request.
|
|
@@ -358,21 +271,10 @@ export async function startProxy() {
|
|
|
358
271
|
// (auth happens lazily)
|
|
359
272
|
const workspace = parseWorkspace();
|
|
360
273
|
console.error(`[moxn-mcp-kb] Starting server for workspace: ${workspace ?? 'unknown'}`);
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
capabilities: {
|
|
366
|
-
// listChanged: the remote HTTP server is stateless and cannot push
|
|
367
|
-
// schema updates, so the PROXY owns staleness detection — it
|
|
368
|
-
// re-checks the remote tools/list on tool activity and emits
|
|
369
|
-
// notifications/tools/list_changed when the schema moves (e.g. after
|
|
370
|
-
// a server deploy). Claude Code honors the notification and re-pulls
|
|
371
|
-
// schemas.
|
|
372
|
-
tools: { listChanged: true },
|
|
373
|
-
resources: {},
|
|
374
|
-
},
|
|
375
|
-
});
|
|
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;
|
|
376
278
|
// Detects remote tool-schema drift and notifies the client. There is no
|
|
377
279
|
// background timer — checks piggyback on tool activity (noteToolActivity),
|
|
378
280
|
// dedupe machine-wide through a shared cache, and stop after repeated auth
|
|
@@ -388,7 +290,15 @@ export async function startProxy() {
|
|
|
388
290
|
}));
|
|
389
291
|
return result.tools ?? [];
|
|
390
292
|
},
|
|
391
|
-
notifyToolListChanged: () =>
|
|
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
|
+
},
|
|
392
302
|
canFetch: () => authConfig !== null,
|
|
393
303
|
intervalMs: Number.isFinite(intervalOverride) && intervalOverride > 0
|
|
394
304
|
? intervalOverride
|
|
@@ -402,8 +312,7 @@ export async function startProxy() {
|
|
|
402
312
|
: undefined,
|
|
403
313
|
log: (message) => console.error(`[moxn-mcp-kb] ${message}`),
|
|
404
314
|
});
|
|
405
|
-
|
|
406
|
-
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
315
|
+
async function listTools() {
|
|
407
316
|
console.error('[moxn-mcp-kb] tools/list requested');
|
|
408
317
|
try {
|
|
409
318
|
console.error('[moxn-mcp-kb] Fetching tools from remote server...');
|
|
@@ -417,12 +326,20 @@ export async function startProxy() {
|
|
|
417
326
|
console.error(`[moxn-mcp-kb] Tools: ${names}`);
|
|
418
327
|
}
|
|
419
328
|
// Baseline for staleness detection: "changed" means "differs from the
|
|
420
|
-
// 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.
|
|
421
332
|
schemaRefresher.recordServedTools(result.tools ?? []);
|
|
422
333
|
// Publish to the machine-wide cache so sibling proxies (other Claude
|
|
423
334
|
// Code sessions on this workspace) skip their own remote check.
|
|
424
335
|
schemaRefresher.noteRemoteToolList(result.tools ?? []);
|
|
425
|
-
return
|
|
336
|
+
return {
|
|
337
|
+
...result,
|
|
338
|
+
tools: [
|
|
339
|
+
...(result.tools ?? []).filter((tool) => !isCheckoutTool(tool.name)),
|
|
340
|
+
...checkoutTools,
|
|
341
|
+
],
|
|
342
|
+
};
|
|
426
343
|
}
|
|
427
344
|
catch (error) {
|
|
428
345
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -450,84 +367,99 @@ export async function startProxy() {
|
|
|
450
367
|
schemaRefresher.recordServedTools(fallback.tools);
|
|
451
368
|
return fallback;
|
|
452
369
|
}
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
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
|
+
};
|
|
480
399
|
}
|
|
400
|
+
// Agent's choice is allowed — pass through
|
|
481
401
|
}
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
FILESYSTEM_AWARE_TOOLS.has(request.params.name)) {
|
|
487
|
-
args = args ? { ...args } : {};
|
|
488
|
-
const agentFs = args.filesystem;
|
|
489
|
-
if (agentFs) {
|
|
490
|
-
// Agent specified a filesystem — verify it's in the allowed list
|
|
491
|
-
if (!filesystemFilter.includes(agentFs)) {
|
|
492
|
-
return {
|
|
493
|
-
content: [
|
|
494
|
-
{
|
|
495
|
-
type: 'text',
|
|
496
|
-
text: JSON.stringify({
|
|
497
|
-
error: `Filesystem "${agentFs}" is not in the allowed list. This connection is restricted to: ${filesystemFilter.join(', ')}`,
|
|
498
|
-
}),
|
|
499
|
-
},
|
|
500
|
-
],
|
|
501
|
-
isError: true,
|
|
502
|
-
};
|
|
503
|
-
}
|
|
504
|
-
// Agent's choice is allowed — pass through
|
|
505
|
-
}
|
|
506
|
-
else {
|
|
507
|
-
// Agent didn't specify — inject the configured default
|
|
508
|
-
if (filesystemFilter.length === 1) {
|
|
509
|
-
args.filesystem = filesystemFilter[0];
|
|
510
|
-
}
|
|
511
|
-
// If multiple allowed filesystems and agent didn't pick,
|
|
512
|
-
// don't inject — let server return results from all allowed FSes.
|
|
513
|
-
// 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];
|
|
514
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.
|
|
515
410
|
}
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
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
|
+
});
|
|
525
461
|
}
|
|
526
|
-
|
|
527
|
-
// throttled staleness check so active sessions track server deploys.
|
|
528
|
-
// Fire-and-forget; must not delay the response.
|
|
529
|
-
void schemaRefresher.noteToolActivity();
|
|
530
|
-
return result;
|
|
462
|
+
return await callRemoteTool(name, args);
|
|
531
463
|
}
|
|
532
464
|
catch (error) {
|
|
533
465
|
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
@@ -541,38 +473,40 @@ export async function startProxy() {
|
|
|
541
473
|
isError: true,
|
|
542
474
|
};
|
|
543
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}`),
|
|
544
509
|
});
|
|
545
|
-
// Proxy resources/list requests (if the server supports them)
|
|
546
|
-
server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
547
|
-
try {
|
|
548
|
-
const result = (await mcpFetch('resources/list'));
|
|
549
|
-
return result;
|
|
550
|
-
}
|
|
551
|
-
catch {
|
|
552
|
-
// Resources might not be supported, return empty list
|
|
553
|
-
return { resources: [] };
|
|
554
|
-
}
|
|
555
|
-
});
|
|
556
|
-
// Proxy resources/read requests
|
|
557
|
-
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
558
|
-
try {
|
|
559
|
-
const result = await mcpFetch('resources/read', {
|
|
560
|
-
uri: request.params.uri,
|
|
561
|
-
});
|
|
562
|
-
return result;
|
|
563
|
-
}
|
|
564
|
-
catch (error) {
|
|
565
|
-
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
566
|
-
console.error('[moxn-mcp-kb] Error reading resource:', message);
|
|
567
|
-
return {
|
|
568
|
-
contents: [{ uri: request.params.uri, text: `Error: ${message}` }],
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
|
-
});
|
|
572
|
-
// Connect to stdio transport IMMEDIATELY
|
|
573
|
-
// This allows the server to respond to MCP initialize before auth
|
|
574
|
-
const transport = new StdioServerTransport();
|
|
575
|
-
await server.connect(transport);
|
|
576
510
|
console.error('[moxn-mcp-kb] Server started, listening on stdio');
|
|
577
511
|
}
|
|
578
512
|
//# sourceMappingURL=proxy.js.map
|