Skip to content

Commit 6402c82

Browse files
m2declaude
authored andcommitted
fix: improve basePath resolution for npx execution support
Updated MCPServer.resolveBasePath() to use a 3-stage resolution strategy consistent with BaseLoader: check cwd/dist first, walk up from argv[1] to find dist/, then fall back to argv[1] dirname. This fixes #101 where npx execution failed because argv[1] pointed to a temp directory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 58ea5e3 commit 6402c82

1 file changed

Lines changed: 32 additions & 3 deletions

File tree

src/core/MCPServer.ts

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
import { ToolProtocol } from '../tools/BaseTool.js';
1515
import { PromptProtocol } from '../prompts/BasePrompt.js';
1616
import { ResourceProtocol } from '../resources/BaseResource.js';
17-
import { readFileSync } from 'fs';
17+
import { readFileSync, existsSync } from 'fs';
1818
import { join, resolve, dirname } from 'path';
1919
import { logger } from './Logger.js';
2020
import { ToolLoader } from '../loaders/toolLoader.js';
@@ -103,9 +103,38 @@ export class MCPServer {
103103
if (configPath) {
104104
return configPath;
105105
}
106-
if (process.argv[1]) {
107-
return dirname(process.argv[1]);
106+
107+
// 1. Check project root dist/ directory (most common case)
108+
const projectRoot = process.cwd();
109+
const distPath = join(projectRoot, 'dist');
110+
if (existsSync(distPath)) {
111+
logger.debug(`Using project's dist directory: ${distPath}`);
112+
return distPath;
108113
}
114+
115+
// 2. Walk up from the main module (process.argv[1]) to find dist/.
116+
// Handles npx where argv[1] is deep inside a temp/cache directory.
117+
const mainModulePath = process.argv[1];
118+
if (mainModulePath) {
119+
let searchDir = dirname(mainModulePath);
120+
for (let i = 0; i < 5; i++) {
121+
const candidate = join(searchDir, 'dist');
122+
if (existsSync(candidate)) {
123+
logger.debug(`Found dist/ by walking up from argv[1]: ${candidate}`);
124+
return candidate;
125+
}
126+
const parent = dirname(searchDir);
127+
if (parent === searchDir) break;
128+
searchDir = parent;
129+
}
130+
131+
// 3. Fallback: use argv[1] dirname directly
132+
const moduleDir = dirname(mainModulePath);
133+
const basePath = moduleDir.endsWith('dist') ? moduleDir : join(moduleDir, 'dist');
134+
logger.debug(`Using module path-based resolution: ${basePath}`);
135+
return basePath;
136+
}
137+
109138
return process.cwd();
110139
}
111140

0 commit comments

Comments
 (0)