@moxn/mcp-kb 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # @moxn/mcp-kb
2
+
3
+ MCP (Model Context Protocol) client for [Moxn Knowledge Base](https://moxn.dev). Connects Claude Code to your Moxn workspace via stdio transport.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install -g @moxn/mcp-kb
9
+ ```
10
+
11
+ Or use directly with npx:
12
+
13
+ ```bash
14
+ npx @moxn/mcp-kb --workspace=your-workspace-slug
15
+ ```
16
+
17
+ ## Configuration
18
+
19
+ ### Claude Code
20
+
21
+ Add to your `.mcp.json`:
22
+
23
+ ```json
24
+ {
25
+ "mcpServers": {
26
+ "moxn-kb": {
27
+ "command": "npx",
28
+ "args": ["-y", "@moxn/mcp-kb", "--workspace=your-workspace-slug"]
29
+ }
30
+ }
31
+ }
32
+ ```
33
+
34
+ ### Authentication
35
+
36
+ On first run, the client will:
37
+
38
+ 1. Register an OAuth client with Clerk (Dynamic Client Registration)
39
+ 2. Open your browser to authenticate
40
+ 3. Store credentials in `~/.moxn/credentials.json`
41
+
42
+ Subsequent runs use the stored credentials automatically.
43
+
44
+ ### Environment Variables
45
+
46
+ | Variable | Description |
47
+ |----------|-------------|
48
+ | `MOXN_TOKEN` | Skip OAuth flow and use this token directly |
49
+ | `MOXN_WORKSPACE` | Default workspace (alternative to `--workspace` flag) |
50
+ | `MOXN_BASE_URL` | Override API URL (for local development) |
51
+ | `MOXN_AUTH_SERVER` | Override auth server URL (for local development) |
52
+
53
+ ## Available Tools
54
+
55
+ Once connected, Claude Code has access to these Knowledge Base tools:
56
+
57
+ - **find** - List documents, sections, or folders
58
+ - **read** - Read document/section content
59
+ - **documents** - Create, update, delete documents; manage branches and tags
60
+ - **sections** - Create, update, delete, reorder sections
61
+ - **search** - Search content across the knowledge base
62
+
63
+ ## Development
64
+
65
+ ```bash
66
+ # Clone the repo
67
+ git clone https://github.com/moxn-ai/moxn.git
68
+ cd moxn/packages/mcp-kb
69
+
70
+ # Install dependencies
71
+ npm install
72
+
73
+ # Build
74
+ npm run build
75
+
76
+ # Test locally
77
+ node dist/index.js --workspace=your-workspace-slug
78
+ ```
79
+
80
+ ## License
81
+
82
+ MIT
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../dist/index.js';
package/dist/auth.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Authentication module for Moxn MCP KB client.
3
+ *
4
+ * Implements OAuth 2.0 with PKCE for Clerk authentication.
5
+ */
6
+ export interface AuthConfig {
7
+ token: string;
8
+ workspace: string;
9
+ }
10
+ /**
11
+ * Get authentication configuration.
12
+ *
13
+ * Checks for stored credentials first, then runs OAuth flow if needed.
14
+ * Also supports MOXN_TOKEN env var for testing.
15
+ */
16
+ export declare function getAuth(): Promise<AuthConfig>;
17
+ /**
18
+ * Build the base URL for the MCP API
19
+ */
20
+ export declare function buildBaseUrl(workspace: string): string;
21
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAQH,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;CACnB;AAoXD;;;;;GAKG;AACH,wBAAsB,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,CAkCnD;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAKtD"}
package/dist/auth.js ADDED
@@ -0,0 +1,341 @@
1
+ /**
2
+ * Authentication module for Moxn MCP KB client.
3
+ *
4
+ * Implements OAuth 2.0 with PKCE for Clerk authentication.
5
+ */
6
+ import { createServer } from 'node:http';
7
+ import { randomBytes, createHash } from 'node:crypto';
8
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
9
+ import { homedir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ const CREDENTIALS_DIR = join(homedir(), '.moxn');
12
+ const CREDENTIALS_FILE = join(CREDENTIALS_DIR, 'credentials.json');
13
+ const CALLBACK_PORT = 9876; // Port for OAuth callback
14
+ const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;
15
+ /**
16
+ * Parse CLI arguments to extract workspace
17
+ */
18
+ function parseWorkspace() {
19
+ const workspaceArg = process.argv.find((arg) => arg.startsWith('--workspace='));
20
+ if (workspaceArg) {
21
+ return workspaceArg.split('=')[1];
22
+ }
23
+ const idx = process.argv.indexOf('--workspace');
24
+ if (idx !== -1 && process.argv[idx + 1]) {
25
+ return process.argv[idx + 1];
26
+ }
27
+ return process.env.MOXN_WORKSPACE;
28
+ }
29
+ /**
30
+ * Generate PKCE code verifier and challenge
31
+ */
32
+ function generatePKCE() {
33
+ const codeVerifier = randomBytes(32)
34
+ .toString('base64url')
35
+ .replace(/[^a-zA-Z0-9]/g, '')
36
+ .slice(0, 43);
37
+ const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url');
38
+ return { codeVerifier, codeChallenge };
39
+ }
40
+ /**
41
+ * Load stored credentials
42
+ */
43
+ async function loadCredentials() {
44
+ try {
45
+ const data = await readFile(CREDENTIALS_FILE, 'utf-8');
46
+ return JSON.parse(data);
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ /**
53
+ * Save credentials to disk
54
+ */
55
+ async function saveCredentials(creds) {
56
+ await mkdir(CREDENTIALS_DIR, { recursive: true });
57
+ await writeFile(CREDENTIALS_FILE, JSON.stringify(creds, null, 2));
58
+ console.error(`[moxn-mcp-kb] Credentials saved to ${CREDENTIALS_FILE}`);
59
+ }
60
+ /**
61
+ * Check if credentials are expired
62
+ */
63
+ function isExpired(creds) {
64
+ const expiresAt = new Date(creds.expiresAt);
65
+ // Consider expired 5 minutes early to be safe
66
+ return expiresAt.getTime() - 5 * 60 * 1000 < Date.now();
67
+ }
68
+ /**
69
+ * Start callback server and wait for OAuth redirect
70
+ */
71
+ function waitForCallback() {
72
+ return new Promise((resolve, reject) => {
73
+ let server;
74
+ const timeout = setTimeout(() => {
75
+ server?.close();
76
+ reject(new Error('OAuth callback timed out after 5 minutes'));
77
+ }, 5 * 60 * 1000);
78
+ server = createServer((req, res) => {
79
+ const url = new URL(req.url || '/', `http://localhost:${CALLBACK_PORT}`);
80
+ if (url.pathname === '/callback') {
81
+ const code = url.searchParams.get('code');
82
+ const state = url.searchParams.get('state');
83
+ const error = url.searchParams.get('error');
84
+ if (error) {
85
+ res.writeHead(400, { 'Content-Type': 'text/html' });
86
+ res.end(`
87
+ <html><body>
88
+ <h1>Authentication Failed</h1>
89
+ <p>Error: ${error}</p>
90
+ <p>You can close this window.</p>
91
+ </body></html>
92
+ `);
93
+ clearTimeout(timeout);
94
+ server.close();
95
+ reject(new Error(`OAuth error: ${error}`));
96
+ return;
97
+ }
98
+ if (code && state) {
99
+ res.writeHead(200, { 'Content-Type': 'text/html' });
100
+ res.end(`
101
+ <html><body>
102
+ <h1>Authentication Successful!</h1>
103
+ <p>You can close this window and return to your terminal.</p>
104
+ <script>window.close();</script>
105
+ </body></html>
106
+ `);
107
+ clearTimeout(timeout);
108
+ server.close();
109
+ resolve({ code, state });
110
+ }
111
+ else {
112
+ res.writeHead(400, { 'Content-Type': 'text/plain' });
113
+ res.end('Missing code or state parameter');
114
+ }
115
+ }
116
+ else {
117
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
118
+ res.end('Not found');
119
+ }
120
+ });
121
+ server.listen(CALLBACK_PORT, () => {
122
+ console.error(`[moxn-mcp-kb] Callback server listening on port ${CALLBACK_PORT}`);
123
+ });
124
+ server.on('error', (err) => {
125
+ clearTimeout(timeout);
126
+ reject(err);
127
+ });
128
+ });
129
+ }
130
+ /**
131
+ * Discover OAuth endpoints from the protected resource metadata
132
+ *
133
+ * For local development, set MOXN_AUTH_SERVER=https://clerk.moxn.dev to skip
134
+ * resource metadata discovery (which can be slow on localhost).
135
+ */
136
+ async function discoverOAuthEndpoints(workspace) {
137
+ // Allow skipping resource metadata discovery for local dev
138
+ const authServerOverride = process.env.MOXN_AUTH_SERVER;
139
+ let authServer;
140
+ if (authServerOverride) {
141
+ console.error(`[moxn-mcp-kb] Using auth server from MOXN_AUTH_SERVER: ${authServerOverride}`);
142
+ authServer = authServerOverride;
143
+ }
144
+ else {
145
+ // Build discovery URL based on MOXN_BASE_URL or default to production
146
+ let resourceUrl;
147
+ const baseUrl = process.env.MOXN_BASE_URL;
148
+ if (baseUrl) {
149
+ // Local dev: derive discovery URL from base URL
150
+ const url = new URL(baseUrl);
151
+ const resourcePath = url.pathname;
152
+ resourceUrl = `${url.origin}/.well-known/oauth-protected-resource${resourcePath}`;
153
+ }
154
+ else {
155
+ // Production: use subdomain routing
156
+ resourceUrl = `https://${workspace}.moxn.dev/.well-known/oauth-protected-resource/api/mcp/http`;
157
+ }
158
+ console.error(`[moxn-mcp-kb] Discovering OAuth endpoints from ${resourceUrl}`);
159
+ const resourceRes = await fetch(resourceUrl);
160
+ if (!resourceRes.ok) {
161
+ throw new Error(`Failed to fetch resource metadata: ${resourceRes.status}`);
162
+ }
163
+ const resourceMeta = (await resourceRes.json());
164
+ authServer = resourceMeta.authorization_servers[0];
165
+ if (!authServer) {
166
+ throw new Error('No authorization server found in resource metadata');
167
+ }
168
+ }
169
+ // Get OAuth Authorization Server metadata (RFC 8414) which includes registration_endpoint
170
+ const oauthAsUrl = `${authServer}/.well-known/oauth-authorization-server`;
171
+ console.error(`[moxn-mcp-kb] Fetching OAuth AS metadata from ${oauthAsUrl}`);
172
+ const oauthAsRes = await fetch(oauthAsUrl);
173
+ if (!oauthAsRes.ok) {
174
+ throw new Error(`Failed to fetch OAuth AS metadata: ${oauthAsRes.status}`);
175
+ }
176
+ const oauthAsConfig = (await oauthAsRes.json());
177
+ if (!oauthAsConfig.registration_endpoint) {
178
+ throw new Error('Authorization server does not support dynamic client registration');
179
+ }
180
+ return {
181
+ authorizationEndpoint: oauthAsConfig.authorization_endpoint,
182
+ tokenEndpoint: oauthAsConfig.token_endpoint,
183
+ registrationEndpoint: oauthAsConfig.registration_endpoint,
184
+ };
185
+ }
186
+ /**
187
+ * Register a new OAuth client dynamically (RFC 7591)
188
+ */
189
+ async function registerClient(registrationEndpoint) {
190
+ console.error('[moxn-mcp-kb] Registering OAuth client dynamically...');
191
+ const clientMetadata = {
192
+ client_name: 'moxn-mcp-kb',
193
+ redirect_uris: [REDIRECT_URI],
194
+ grant_types: ['authorization_code', 'refresh_token'],
195
+ response_types: ['code'],
196
+ token_endpoint_auth_method: 'none', // Public client (PKCE only)
197
+ };
198
+ const res = await fetch(registrationEndpoint, {
199
+ method: 'POST',
200
+ headers: {
201
+ 'Content-Type': 'application/json',
202
+ },
203
+ body: JSON.stringify(clientMetadata),
204
+ });
205
+ if (!res.ok) {
206
+ const errorText = await res.text();
207
+ throw new Error(`Client registration failed: ${res.status} ${errorText}`);
208
+ }
209
+ const clientInfo = (await res.json());
210
+ console.error(`[moxn-mcp-kb] Client registered: ${clientInfo.client_id}`);
211
+ return {
212
+ clientId: clientInfo.client_id,
213
+ clientSecret: clientInfo.client_secret,
214
+ };
215
+ }
216
+ /**
217
+ * Run the OAuth flow
218
+ */
219
+ async function runOAuthFlow(workspace) {
220
+ const { authorizationEndpoint, tokenEndpoint, registrationEndpoint } = await discoverOAuthEndpoints(workspace);
221
+ // Check if we have cached client credentials, otherwise register a new client
222
+ const stored = await loadCredentials();
223
+ let clientId;
224
+ let clientSecret;
225
+ if (stored?.clientId) {
226
+ console.error('[moxn-mcp-kb] Using cached client credentials');
227
+ clientId = stored.clientId;
228
+ clientSecret = stored.clientSecret;
229
+ }
230
+ else {
231
+ // Register a new OAuth client dynamically
232
+ const clientInfo = await registerClient(registrationEndpoint);
233
+ clientId = clientInfo.clientId;
234
+ clientSecret = clientInfo.clientSecret;
235
+ }
236
+ const { codeVerifier, codeChallenge } = generatePKCE();
237
+ const state = randomBytes(16).toString('hex');
238
+ // Build authorization URL
239
+ const authUrl = new URL(authorizationEndpoint);
240
+ authUrl.searchParams.set('response_type', 'code');
241
+ authUrl.searchParams.set('client_id', clientId);
242
+ authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
243
+ authUrl.searchParams.set('scope', 'profile email');
244
+ authUrl.searchParams.set('state', state);
245
+ authUrl.searchParams.set('code_challenge', codeChallenge);
246
+ authUrl.searchParams.set('code_challenge_method', 'S256');
247
+ console.error('[moxn-mcp-kb] Opening browser for authentication...');
248
+ console.error(`[moxn-mcp-kb] If browser doesn't open, visit: ${authUrl.toString()}`);
249
+ // Dynamic import of 'open' package
250
+ const { default: open } = await import('open');
251
+ await open(authUrl.toString());
252
+ // Wait for callback
253
+ const { code, state: returnedState } = await waitForCallback();
254
+ if (returnedState !== state) {
255
+ throw new Error('State mismatch - possible CSRF attack');
256
+ }
257
+ // Exchange code for tokens
258
+ console.error('[moxn-mcp-kb] Exchanging authorization code for tokens...');
259
+ const tokenParams = {
260
+ grant_type: 'authorization_code',
261
+ client_id: clientId,
262
+ code,
263
+ redirect_uri: REDIRECT_URI,
264
+ code_verifier: codeVerifier,
265
+ };
266
+ // Add client_secret if we have one (confidential client)
267
+ if (clientSecret) {
268
+ tokenParams.client_secret = clientSecret;
269
+ }
270
+ const tokenRes = await fetch(tokenEndpoint, {
271
+ method: 'POST',
272
+ headers: {
273
+ 'Content-Type': 'application/x-www-form-urlencoded',
274
+ },
275
+ body: new URLSearchParams(tokenParams),
276
+ });
277
+ if (!tokenRes.ok) {
278
+ const errorText = await tokenRes.text();
279
+ throw new Error(`Token exchange failed: ${tokenRes.status} ${errorText}`);
280
+ }
281
+ const tokenData = (await tokenRes.json());
282
+ // Calculate expiry (default to 1 hour if not specified)
283
+ const expiresIn = tokenData.expires_in || 3600;
284
+ const expiresAt = new Date(Date.now() + expiresIn * 1000).toISOString();
285
+ // Save credentials (including client credentials for future use)
286
+ await saveCredentials({
287
+ accessToken: tokenData.access_token,
288
+ refreshToken: tokenData.refresh_token,
289
+ expiresAt,
290
+ workspace,
291
+ clientId,
292
+ clientSecret,
293
+ });
294
+ console.error('[moxn-mcp-kb] Authentication successful!');
295
+ return tokenData.access_token;
296
+ }
297
+ /**
298
+ * Get authentication configuration.
299
+ *
300
+ * Checks for stored credentials first, then runs OAuth flow if needed.
301
+ * Also supports MOXN_TOKEN env var for testing.
302
+ */
303
+ export async function getAuth() {
304
+ const workspace = parseWorkspace();
305
+ if (!workspace) {
306
+ console.error('Error: --workspace=<slug> is required or set MOXN_WORKSPACE env var');
307
+ console.error('Example: moxn-mcp-kb --workspace=smoggy-azure-hummingbird');
308
+ process.exit(1);
309
+ }
310
+ // Check for env var token (for testing/CI)
311
+ const envToken = process.env.MOXN_TOKEN;
312
+ if (envToken) {
313
+ console.error('[moxn-mcp-kb] Using token from MOXN_TOKEN env var');
314
+ return { token: envToken, workspace };
315
+ }
316
+ // Check for stored credentials
317
+ const stored = await loadCredentials();
318
+ if (stored && stored.workspace === workspace && !isExpired(stored)) {
319
+ console.error('[moxn-mcp-kb] Using stored credentials');
320
+ return { token: stored.accessToken, workspace };
321
+ }
322
+ // Need to run OAuth flow
323
+ if (stored && isExpired(stored)) {
324
+ console.error('[moxn-mcp-kb] Stored credentials expired, re-authenticating...');
325
+ }
326
+ else {
327
+ console.error('[moxn-mcp-kb] No stored credentials, starting OAuth flow...');
328
+ }
329
+ const token = await runOAuthFlow(workspace);
330
+ return { token, workspace };
331
+ }
332
+ /**
333
+ * Build the base URL for the MCP API
334
+ */
335
+ export function buildBaseUrl(workspace) {
336
+ if (process.env.MOXN_BASE_URL) {
337
+ return process.env.MOXN_BASE_URL;
338
+ }
339
+ return `https://${workspace}.moxn.dev/api/mcp/http`;
340
+ }
341
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE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BAA+B;IAC/B,MAAM,MAAM,GAAG,MAAM,eAAe,EAAE,CAAC;IACvC,IAAI,MAAM,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC;QACnE,OAAO,CAAC,KAAK,CAAC,wCAAwC,CAAC,CAAC;QACxD,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,WAAW,EAAE,SAAS,EAAE,CAAC;IAClD,CAAC;IAED,yBAAyB;IACzB,IAAI,MAAM,IAAI,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC;QAChC,OAAO,CAAC,KAAK,CAAC,gEAAgE,CAAC,CAAC;IAClF,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,6DAA6D,CAAC,CAAC;IAC/E,CAAC;IAED,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,SAAS,CAAC,CAAC;IAC5C,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;AAC9B,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,SAAiB;IAC5C,IAAI,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,CAAC;QAC9B,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;IACnC,CAAC;IACD,OAAO,WAAW,SAAS,wBAAwB,CAAC;AACtD,CAAC"}
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Moxn MCP KB Client
4
+ *
5
+ * A local MCP server that proxies requests to the Moxn Knowledge Base API.
6
+ *
7
+ * Usage:
8
+ * moxn-mcp-kb --workspace=<workspace-slug>
9
+ *
10
+ * Environment variables:
11
+ * MOXN_TOKEN - Bearer token for authentication (skips OAuth)
12
+ * MOXN_WORKSPACE - Workspace slug (alternative to --workspace arg)
13
+ * MOXN_BASE_URL - Override base URL for local development
14
+ *
15
+ * Authentication happens lazily on first tool request, not on startup.
16
+ * This allows the stdio server to respond to MCP initialize immediately.
17
+ */
18
+ export {};
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;GAeG"}
package/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Moxn MCP KB Client
4
+ *
5
+ * A local MCP server that proxies requests to the Moxn Knowledge Base API.
6
+ *
7
+ * Usage:
8
+ * moxn-mcp-kb --workspace=<workspace-slug>
9
+ *
10
+ * Environment variables:
11
+ * MOXN_TOKEN - Bearer token for authentication (skips OAuth)
12
+ * MOXN_WORKSPACE - Workspace slug (alternative to --workspace arg)
13
+ * MOXN_BASE_URL - Override base URL for local development
14
+ *
15
+ * Authentication happens lazily on first tool request, not on startup.
16
+ * This allows the stdio server to respond to MCP initialize immediately.
17
+ */
18
+ import { startProxy } from './proxy.js';
19
+ async function main() {
20
+ try {
21
+ // Start the proxy server immediately (auth happens lazily on first request)
22
+ await startProxy();
23
+ }
24
+ catch (error) {
25
+ const message = error instanceof Error ? error.message : 'Unknown error';
26
+ console.error(`[moxn-mcp-kb] Fatal error: ${message}`);
27
+ process.exit(1);
28
+ }
29
+ }
30
+ main();
31
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAExC,KAAK,UAAU,IAAI;IACjB,IAAI,CAAC;QACH,4EAA4E;QAC5E,MAAM,UAAU,EAAE,CAAC;IACrB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,CAAC;QACzE,OAAO,CAAC,KAAK,CAAC,8BAA8B,OAAO,EAAE,CAAC,CAAC;QACvD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Stdio to HTTP proxy for Moxn MCP KB.
3
+ *
4
+ * Creates a local MCP server using stdio transport that proxies
5
+ * all requests to the remote Moxn MCP HTTP server.
6
+ *
7
+ * Authentication is lazy - it only happens on the first actual request,
8
+ * allowing the server to respond to MCP initialize immediately.
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.
14
+ */
15
+ /**
16
+ * Create and start the proxy server.
17
+ * Server starts immediately; authentication happens lazily on first request.
18
+ */
19
+ export declare function startProxy(): Promise<void>;
20
+ //# sourceMappingURL=proxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAoUH;;;GAGG;AACH,wBAAsB,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAiJhD"}
package/dist/proxy.js ADDED
@@ -0,0 +1,354 @@
1
+ /**
2
+ * Stdio to HTTP proxy for Moxn MCP KB.
3
+ *
4
+ * Creates a local MCP server using stdio transport that proxies
5
+ * all requests to the remote Moxn MCP HTTP server.
6
+ *
7
+ * Authentication is lazy - it only happens on the first actual request,
8
+ * allowing the server to respond to MCP initialize immediately.
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.
14
+ */
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';
20
+ import { getAuth, buildBaseUrl } from './auth.js';
21
+ // Lazy-loaded auth config - only populated on first request
22
+ let authConfig = null;
23
+ /**
24
+ * Get auth config lazily. This triggers OAuth flow on first call
25
+ * if no valid credentials exist.
26
+ */
27
+ async function getAuthConfig() {
28
+ if (!authConfig) {
29
+ console.error('[moxn-mcp-kb] No cached auth, starting authentication...');
30
+ try {
31
+ authConfig = await getAuth();
32
+ console.error(`[moxn-mcp-kb] Auth successful for workspace: ${authConfig.workspace}`);
33
+ }
34
+ catch (error) {
35
+ const message = error instanceof Error ? error.message : String(error);
36
+ console.error(`[moxn-mcp-kb] Auth FAILED: ${message}`);
37
+ throw error; // Re-throw so caller knows auth failed
38
+ }
39
+ }
40
+ else {
41
+ console.error('[moxn-mcp-kb] Using cached auth config');
42
+ }
43
+ return authConfig;
44
+ }
45
+ /**
46
+ * Make a JSON-RPC 2.0 request to the MCP HTTP server.
47
+ * Auth happens lazily on first call.
48
+ */
49
+ async function mcpFetch(method, params) {
50
+ console.error(`[moxn-mcp-kb] mcpFetch: ${method}`);
51
+ // Get auth lazily - may trigger OAuth flow
52
+ const config = await getAuthConfig();
53
+ const baseUrl = buildBaseUrl(config.workspace);
54
+ console.error(`[moxn-mcp-kb] POST ${baseUrl}`);
55
+ const body = {
56
+ jsonrpc: '2.0',
57
+ id: Date.now(),
58
+ method,
59
+ params: params || {},
60
+ };
61
+ const response = await fetch(baseUrl, {
62
+ method: 'POST',
63
+ headers: {
64
+ 'Content-Type': 'application/json',
65
+ Accept: 'application/json, text/event-stream',
66
+ Authorization: `Bearer ${config.token}`,
67
+ },
68
+ body: JSON.stringify(body),
69
+ });
70
+ console.error(`[moxn-mcp-kb] Response status: ${response.status}`);
71
+ if (!response.ok) {
72
+ const text = await response.text();
73
+ console.error(`[moxn-mcp-kb] Response body: ${text}`);
74
+ throw new Error(`MCP request failed: ${response.status} ${text}`);
75
+ }
76
+ const result = await response.json();
77
+ // Handle JSON-RPC error response
78
+ if (result.error) {
79
+ console.error(`[moxn-mcp-kb] JSON-RPC error: ${JSON.stringify(result.error)}`);
80
+ throw new Error(result.error.message || 'Unknown MCP error');
81
+ }
82
+ return result.result;
83
+ }
84
+ // ============================================
85
+ // File Upload Infrastructure
86
+ // ============================================
87
+ /**
88
+ * Infer MIME type from file path extension
89
+ */
90
+ function inferMimeType(filePath) {
91
+ const ext = path.extname(filePath).toLowerCase();
92
+ const mimeMap = {
93
+ '.png': 'image/png',
94
+ '.jpg': 'image/jpeg',
95
+ '.jpeg': 'image/jpeg',
96
+ '.gif': 'image/gif',
97
+ '.webp': 'image/webp',
98
+ '.pdf': 'application/pdf',
99
+ };
100
+ return mimeMap[ext] || 'application/octet-stream';
101
+ }
102
+ /**
103
+ * Check if MIME type is an image
104
+ */
105
+ function isImageMimeType(mimeType) {
106
+ return mimeType.startsWith('image/');
107
+ }
108
+ /**
109
+ * Validate file path for security
110
+ *
111
+ * Only allows absolute paths to prevent directory traversal.
112
+ * Does not restrict to specific directories - trusts LLM's file path.
113
+ */
114
+ function validateFilePath(filePath) {
115
+ if (!path.isAbsolute(filePath)) {
116
+ throw new Error(`File path must be absolute: ${filePath}`);
117
+ }
118
+ }
119
+ /**
120
+ * Upload a local file to Moxn storage via presigned URL
121
+ *
122
+ * Flow:
123
+ * 1. Read file from local disk
124
+ * 2. Get presigned upload URL from Moxn API
125
+ * 3. Upload file directly to Supabase
126
+ * 4. Return storage key for use in content block
127
+ */
128
+ async function uploadLocalFile(filePath, token, workspace, mediaTypeOverride) {
129
+ validateFilePath(filePath);
130
+ // Read file from disk
131
+ const fileBuffer = await fs.readFile(filePath);
132
+ const fileName = path.basename(filePath);
133
+ const mimeType = mediaTypeOverride || inferMimeType(filePath);
134
+ console.error(`[moxn-mcp-kb] Uploading file: ${fileName} (${mimeType}, ${fileBuffer.length} bytes)`);
135
+ // Determine which endpoint to use based on MIME type
136
+ const isImage = isImageMimeType(mimeType);
137
+ const endpointPath = isImage ? 'images' : 'files';
138
+ // Build the upload URL endpoint
139
+ // Production: https://{workspace}.moxn.dev/api/{workspace}/signed-media/{images|files}/upload-url
140
+ // Local: derived from MOXN_BASE_URL
141
+ let uploadUrlEndpoint;
142
+ if (process.env.MOXN_BASE_URL) {
143
+ // Local dev: replace /api/mcp/http with the signed-media endpoint
144
+ const baseUrl = new URL(process.env.MOXN_BASE_URL);
145
+ uploadUrlEndpoint = `${baseUrl.origin}/api/${workspace}/signed-media/${endpointPath}/upload-url`;
146
+ }
147
+ else {
148
+ uploadUrlEndpoint = `https://${workspace}.moxn.dev/api/${workspace}/signed-media/${endpointPath}/upload-url`;
149
+ }
150
+ console.error(`[moxn-mcp-kb] Getting presigned URL from ${uploadUrlEndpoint}`);
151
+ // Request presigned upload URL
152
+ const uploadUrlBody = {
153
+ type: mimeType,
154
+ };
155
+ if (!isImage) {
156
+ uploadUrlBody.filename = fileName;
157
+ }
158
+ const uploadUrlRes = await fetch(uploadUrlEndpoint, {
159
+ method: 'POST',
160
+ headers: {
161
+ 'Content-Type': 'application/json',
162
+ Authorization: `Bearer ${token}`,
163
+ },
164
+ body: JSON.stringify(uploadUrlBody),
165
+ });
166
+ if (!uploadUrlRes.ok) {
167
+ const text = await uploadUrlRes.text();
168
+ throw new Error(`Failed to get upload URL: ${uploadUrlRes.status} ${text}`);
169
+ }
170
+ const { path: storagePath, token: uploadToken } = (await uploadUrlRes.json());
171
+ console.error(`[moxn-mcp-kb] Uploading to storage path: ${storagePath}`);
172
+ // Upload file directly to Supabase via presigned URL
173
+ const uploadRes = await fetch(uploadToken, {
174
+ method: 'PUT',
175
+ headers: {
176
+ 'Content-Type': mimeType,
177
+ },
178
+ body: fileBuffer,
179
+ });
180
+ if (!uploadRes.ok) {
181
+ const text = await uploadRes.text();
182
+ throw new Error(`Failed to upload file: ${uploadRes.status} ${text}`);
183
+ }
184
+ console.error(`[moxn-mcp-kb] File uploaded successfully: ${storagePath}`);
185
+ return { key: storagePath, mimeType };
186
+ }
187
+ /**
188
+ * Check if a content block has type: 'file'
189
+ */
190
+ function isFileContentBlock(block) {
191
+ return block.type === 'file' && typeof block.path === 'string';
192
+ }
193
+ /**
194
+ * Transform content blocks - upload local files before sending to server
195
+ *
196
+ * For each content block with `type: "file"`:
197
+ * 1. Upload the file to Supabase storage
198
+ * 2. Transform the block to `type: "storage"` with the storage key
199
+ */
200
+ async function transformContentBlocks(blocks, token, workspace) {
201
+ const transformed = [];
202
+ for (const block of blocks) {
203
+ if (isFileContentBlock(block)) {
204
+ // Upload the file and transform to storage block
205
+ const { key, mimeType } = await uploadLocalFile(block.path, token, workspace, block.mediaType);
206
+ const storageBlock = {
207
+ blockType: block.blockType,
208
+ type: 'storage',
209
+ key,
210
+ mediaType: mimeType,
211
+ };
212
+ // Preserve optional fields
213
+ if (block.alt)
214
+ storageBlock.alt = block.alt;
215
+ if (block.filename)
216
+ storageBlock.filename = block.filename;
217
+ transformed.push(storageBlock);
218
+ }
219
+ else {
220
+ // Pass through unchanged
221
+ transformed.push(block);
222
+ }
223
+ }
224
+ return transformed;
225
+ }
226
+ /**
227
+ * Check if any content blocks in the arguments need file upload transformation
228
+ */
229
+ function hasFileBlocks(args) {
230
+ const content = args.content;
231
+ if (!content || !Array.isArray(content)) {
232
+ return false;
233
+ }
234
+ return content.some(isFileContentBlock);
235
+ }
236
+ /**
237
+ * Create and start the proxy server.
238
+ * Server starts immediately; authentication happens lazily on first request.
239
+ */
240
+ export async function startProxy() {
241
+ // Parse workspace from args for logging (auth happens lazily)
242
+ const workspaceArg = process.argv.find((arg) => arg.startsWith('--workspace='));
243
+ const workspace = workspaceArg?.split('=')[1] || process.env.MOXN_WORKSPACE || 'unknown';
244
+ console.error(`[moxn-mcp-kb] Starting server for workspace: ${workspace}`);
245
+ const server = new Server({
246
+ name: 'moxn-kb',
247
+ version: '0.1.0',
248
+ }, {
249
+ capabilities: {
250
+ tools: {},
251
+ resources: {},
252
+ },
253
+ });
254
+ // Proxy tools/list requests (auth happens lazily on first call)
255
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
256
+ console.error('[moxn-mcp-kb] tools/list requested');
257
+ try {
258
+ console.error('[moxn-mcp-kb] Fetching tools from remote server...');
259
+ const result = (await mcpFetch('tools/list'));
260
+ console.error(`[moxn-mcp-kb] Got ${result.tools?.length ?? 0} tools from remote`);
261
+ // Log tool names for debugging
262
+ if (result.tools?.length > 0) {
263
+ const names = result.tools
264
+ .map((t) => t.name)
265
+ .join(', ');
266
+ console.error(`[moxn-mcp-kb] Tools: ${names}`);
267
+ }
268
+ return result;
269
+ }
270
+ catch (error) {
271
+ const message = error instanceof Error ? error.message : String(error);
272
+ console.error(`[moxn-mcp-kb] ERROR listing tools: ${message}`);
273
+ return { tools: [] };
274
+ }
275
+ });
276
+ // Proxy tools/call requests with file upload transformation
277
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
278
+ try {
279
+ let args = request.params.arguments;
280
+ // Special handling for sections tool - transform file blocks to storage blocks
281
+ if (request.params.name === 'sections' && args) {
282
+ // Check both content (for create) and newContent (for update)
283
+ const hasFilesInContent = hasFileBlocks(args);
284
+ const hasFilesInNewContent = args.newContent
285
+ ? hasFileBlocks({ content: args.newContent })
286
+ : false;
287
+ if (hasFilesInContent || hasFilesInNewContent) {
288
+ // Get auth config for upload (may trigger OAuth if not already authenticated)
289
+ const config = await getAuthConfig();
290
+ console.error('[moxn-mcp-kb] Transforming file blocks to storage blocks...');
291
+ // Clone args to avoid mutating the original
292
+ args = { ...args };
293
+ if (hasFilesInContent) {
294
+ const content = args.content;
295
+ const transformedContent = await transformContentBlocks(content, config.token, config.workspace);
296
+ args.content = transformedContent;
297
+ }
298
+ if (hasFilesInNewContent) {
299
+ const newContent = args.newContent;
300
+ const transformedNewContent = await transformContentBlocks(newContent, config.token, config.workspace);
301
+ args.newContent = transformedNewContent;
302
+ }
303
+ console.error('[moxn-mcp-kb] File transformation complete, forwarding to server');
304
+ }
305
+ }
306
+ const result = await mcpFetch('tools/call', {
307
+ name: request.params.name,
308
+ arguments: args,
309
+ });
310
+ return result;
311
+ }
312
+ catch (error) {
313
+ const message = error instanceof Error ? error.message : 'Unknown error';
314
+ console.error('[moxn-mcp-kb] Error calling tool:', message);
315
+ return {
316
+ content: [{ type: 'text', text: JSON.stringify({ error: message }) }],
317
+ isError: true,
318
+ };
319
+ }
320
+ });
321
+ // Proxy resources/list requests (if the server supports them)
322
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
323
+ try {
324
+ const result = (await mcpFetch('resources/list'));
325
+ return result;
326
+ }
327
+ catch {
328
+ // Resources might not be supported, return empty list
329
+ return { resources: [] };
330
+ }
331
+ });
332
+ // Proxy resources/read requests
333
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
334
+ try {
335
+ const result = await mcpFetch('resources/read', {
336
+ uri: request.params.uri,
337
+ });
338
+ return result;
339
+ }
340
+ catch (error) {
341
+ const message = error instanceof Error ? error.message : 'Unknown error';
342
+ console.error('[moxn-mcp-kb] Error reading resource:', message);
343
+ return {
344
+ contents: [{ uri: request.params.uri, text: `Error: ${message}` }],
345
+ };
346
+ }
347
+ });
348
+ // Connect to stdio transport IMMEDIATELY
349
+ // This allows the server to respond to MCP initialize before auth
350
+ const transport = new StdioServerTransport();
351
+ await server.connect(transport);
352
+ console.error('[moxn-mcp-kb] Server started, listening on stdio');
353
+ }
354
+ //# sourceMappingURL=proxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,0BAA0B,EAC1B,yBAAyB,GAC1B,MAAM,oCAAoC,CAA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AAC,eAAe,CAAC;YACzE,OAAO,CAAC,KAAK,CAAC,uCAAuC,EAAE,OAAO,CAAC,CAAC;YAChE,OAAO;gBACL,QAAQ,EAAE,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,EAAE,UAAU,OAAO,EAAE,EAAE,CAAC;aACnE,CAAC;QACJ,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,yCAAyC;IACzC,kEAAkE;IAClE,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAEhC,OAAO,CAAC,KAAK,CAAC,kDAAkD,CAAC,CAAC;AACpE,CAAC"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@moxn/mcp-kb",
3
+ "version": "0.1.0",
4
+ "description": "MCP client for Moxn Knowledge Base - connects Claude Code to your Moxn workspace via stdio",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "bin": {
9
+ "moxn-mcp-kb": "./bin/moxn-mcp-kb"
10
+ },
11
+ "scripts": {
12
+ "build": "tsc",
13
+ "dev": "tsc --watch",
14
+ "prepublishOnly": "npm run build"
15
+ },
16
+ "dependencies": {
17
+ "@modelcontextprotocol/sdk": "^1.0.0",
18
+ "open": "^10.0.0"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^20.0.0",
22
+ "typescript": "^5.0.0"
23
+ },
24
+ "engines": {
25
+ "node": ">=18.0.0"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "bin"
30
+ ],
31
+ "keywords": [
32
+ "mcp",
33
+ "moxn",
34
+ "knowledge-base",
35
+ "claude",
36
+ "ai",
37
+ "llm"
38
+ ],
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/moxn-ai/moxn.git",
42
+ "directory": "packages/mcp-kb"
43
+ },
44
+ "homepage": "https://moxn.dev",
45
+ "bugs": {
46
+ "url": "https://github.com/moxn-ai/moxn/issues"
47
+ },
48
+ "author": "Moxn <support@moxn.dev>",
49
+ "license": "MIT",
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
53
+ }