Skip to content

Commit 24701f0

Browse files
committed
feat(server): bootstrap project path from cli
1 parent fe92732 commit 24701f0

File tree

5 files changed

+109
-2
lines changed

5 files changed

+109
-2
lines changed

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ The easiest way to get started with any MCP-compatible application:
4141
}
4242
}
4343
```
44+
> Optional: append `--project-path /absolute/path/to/repo` to the `args` array so the server
45+
> initializes with that repository automatically (equivalent to calling `set_project_path`
46+
> after startup).
4447
4548
2. **Restart your application**`uvx` automatically handles installation and execution
4649

@@ -51,6 +54,8 @@ The easiest way to get started with any MCP-compatible application:
5154
Search for "authentication" functions
5255
Analyze the main App.tsx file
5356
```
57+
*If you launch with `--project-path`, you can skip the first command above - the server already
58+
knows the project location.*
5459

5560
### Codex CLI Configuration
5661

@@ -63,6 +68,8 @@ type = "stdio"
6368
command = "uvx"
6469
args = ["code-index-mcp"]
6570
```
71+
> You can append `--project-path C:/absolute/path/to/repo` to the `args` list to set the project
72+
> automatically on startup (same effect as running the `set_project_path` tool).
6673
6774
On Windows, `uvx` needs the standard profile directories to be present.
6875
Keep the environment override in the same block so the MCP starts reliably:

README_ja.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ Code Index MCPは、AIモデルと複雑なコードベースの橋渡しをす
4242
}
4343
```
4444

45+
> 起動時にプロジェクトを自動設定したい場合は、`args` 配列の末尾に
46+
> `--project-path /absolute/path/to/repo` を追加してください。これで起動直後に
47+
> `set_project_path` を呼び出した場合と同じ状態になります。
4548
2. **アプリケーションを再起動**`uvx`がインストールと実行を自動処理
4649

4750
3. **使用開始**(AIアシスタントにこれらのプロンプトを与える):
@@ -51,6 +54,7 @@ Code Index MCPは、AIモデルと複雑なコードベースの橋渡しをす
5154
「authentication」関連関数を検索
5255
メインのApp.tsxファイルを解析
5356
```
57+
*起動時に `--project-path` を付けた場合は、最初のコマンドは不要です。サーバーが既にパスを認識しています。*
5458

5559
### Codex CLI 設定
5660

@@ -63,6 +67,8 @@ type = "stdio"
6367
command = "uvx"
6468
args = ["code-index-mcp"]
6569
```
70+
> 起動時にプロジェクトを設定したい場合は、`args` リストに `--project-path C:/absolute/path/to/repo` を追加してください。
71+
> これは起動後に `set_project_path` ツールを呼び出すのと同じ効果です。
6672
6773
Windows の `uvx` は標準ユーザープロファイルディレクトリが必要です。
6874
MCP を安定して起動するために、同じブロックに次の環境変数を残してください。

README_ko.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ Code Index MCP는 [Model Context Protocol](https://modelcontextprotocol.io) 기
4242
}
4343
```
4444

45+
> 시작할 때 프로젝트를 자동으로 지정하려면 `args` 배열 끝에
46+
> `--project-path /absolute/path/to/repo` 를 추가하세요. 이렇게 하면 시작 직후 `set_project_path` 를 호출한 것과 동일한 상태가 됩니다.
4547
2. **애플리케이션 재시작**`uvx`가 설치와 실행을 자동으로 처리합니다.
4648

4749
3. **사용 시작** (AI 어시스턴트에게 아래 프롬프트를 전달)
@@ -51,6 +53,7 @@ Code Index MCP는 [Model Context Protocol](https://modelcontextprotocol.io) 기
5153
"authentication" 관련 함수를 검색해줘
5254
src/App.tsx 파일을 분석해줘
5355
```
56+
*실행 시 `--project-path` 옵션을 사용했다면 첫 번째 명령은 건너뛰어도 됩니다. 서버가 이미 경로를 알고 있습니다.*
5457

5558
### Codex CLI 설정
5659

@@ -63,6 +66,8 @@ type = "stdio"
6366
command = "uvx"
6467
args = ["code-index-mcp"]
6568
```
69+
> 실행 시 프로젝트를 자동으로 지정하려면 `args` 리스트에 `--project-path C:/absolute/path/to/repo` 를 추가하세요.
70+
> 이는 이후에 `set_project_path` 도구를 호출하는 것과 같은 효과입니다.
6671
6772
Windows의 `uvx`는 기본 사용자 프로필 디렉터리가 필요합니다.
6873
MCP가 안정적으로 시작되도록 같은 블록에 아래 환경 변수 덮어쓰기를 유지하세요.

README_zh.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@
4141
}
4242
}
4343
```
44+
> 若想在啟動時自動設定專案路徑,可在 `args` 陣列末尾加入
45+
> `--project-path /絕對/路徑`,效果等同於啟動後呼叫 `set_project_path`
4446
4547
2. **重新啟動應用程式**`uvx` 會自動處理安裝和執行
4648

@@ -51,6 +53,7 @@
5153
搜尋「authentication」相關函數
5254
分析主要的 App.tsx 檔案
5355
```
56+
*如果啟動時已提供 `--project-path`,可以略過第一個指令,伺服器會自動記住路徑。*
5457

5558
### Codex CLI 設定
5659

@@ -63,6 +66,8 @@ type = "stdio"
6366
command = "uvx"
6467
args = ["code-index-mcp"]
6568
```
69+
> 如需要啟動時自動設定專案,請把 `--project-path C:/絕對/路徑` 加到 `args`
70+
> 清單中,與手動呼叫 `set_project_path` 的結果相同。
6671
6772
在 Windows 中,`uvx` 需要找到標準的使用者目錄。保留下列環境變數覆寫設定,才能讓 MCP 穩定啟動:
6873

src/code_index_mcp/server.py

Lines changed: 86 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
"""
1010

1111
# Standard library imports
12+
import argparse
13+
import inspect
1214
import sys
1315
import logging
1416
from contextlib import asynccontextmanager
@@ -52,6 +54,7 @@ def setup_indexing_performance_logging():
5254

5355
# Initialize logging (no file handlers)
5456
setup_indexing_performance_logging()
57+
logger = logging.getLogger(__name__)
5558

5659
@dataclass
5760
class CodeIndexerContext:
@@ -61,6 +64,24 @@ class CodeIndexerContext:
6164
file_count: int = 0
6265
file_watcher_service: FileWatcherService = None
6366

67+
68+
@dataclass
69+
class _CLIConfig:
70+
"""Holds CLI configuration for bootstrap operations."""
71+
project_path: str | None = None
72+
73+
74+
class _BootstrapRequestContext:
75+
"""Minimal request context to reuse business services during bootstrap."""
76+
77+
def __init__(self, lifespan_context: CodeIndexerContext):
78+
self.lifespan_context = lifespan_context
79+
self.session = None
80+
self.meta = None
81+
82+
83+
_CLI_CONFIG = _CLIConfig()
84+
6485
@asynccontextmanager
6586
async def indexer_lifespan(_server: FastMCP) -> AsyncIterator[CodeIndexerContext]:
6687
"""Manage the lifecycle of the Code Indexer MCP server."""
@@ -78,6 +99,23 @@ async def indexer_lifespan(_server: FastMCP) -> AsyncIterator[CodeIndexerContext
7899
)
79100

80101
try:
102+
# Bootstrap project path when provided via CLI.
103+
if _CLI_CONFIG.project_path:
104+
bootstrap_ctx = Context(
105+
request_context=_BootstrapRequestContext(context),
106+
fastmcp=mcp
107+
)
108+
try:
109+
message = ProjectManagementService(bootstrap_ctx).initialize_project(
110+
_CLI_CONFIG.project_path
111+
)
112+
logger.info("Project initialized from CLI flag: %s", message)
113+
except Exception as exc: # pylint: disable=broad-except
114+
logger.error("Failed to initialize project from CLI flag: %s", exc)
115+
raise RuntimeError(
116+
f"Failed to initialize project path '{_CLI_CONFIG.project_path}'"
117+
) from exc
118+
81119
# Provide context to the server
82120
yield context
83121
finally:
@@ -300,9 +338,55 @@ def configure_file_watcher(
300338
# ----- PROMPTS -----
301339
# Removed: analyze_code, code_search, set_project prompts
302340

303-
def main():
341+
def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
342+
"""Parse CLI arguments for the MCP server."""
343+
parser = argparse.ArgumentParser(description="Code Index MCP server")
344+
parser.add_argument(
345+
"--project-path",
346+
dest="project_path",
347+
help="Set the project path on startup (equivalent to calling set_project_path)."
348+
)
349+
parser.add_argument(
350+
"--transport",
351+
choices=["stdio", "sse", "streamable-http"],
352+
default="stdio",
353+
help="Transport protocol to use (default: stdio)."
354+
)
355+
parser.add_argument(
356+
"--mount-path",
357+
dest="mount_path",
358+
default=None,
359+
help="Mount path when using SSE transport."
360+
)
361+
return parser.parse_args(argv)
362+
363+
364+
def main(argv: list[str] | None = None):
304365
"""Main function to run the MCP server."""
305-
mcp.run()
366+
args = _parse_args(argv)
367+
368+
# Store CLI configuration for lifespan bootstrap.
369+
_CLI_CONFIG.project_path = args.project_path
370+
371+
run_kwargs = {"transport": args.transport}
372+
if args.transport == "sse" and args.mount_path:
373+
run_signature = inspect.signature(mcp.run)
374+
if "mount_path" in run_signature.parameters:
375+
run_kwargs["mount_path"] = args.mount_path
376+
else:
377+
logger.warning(
378+
"Ignoring --mount-path because this FastMCP version "
379+
"does not accept the parameter."
380+
)
381+
382+
try:
383+
mcp.run(**run_kwargs)
384+
except RuntimeError as exc:
385+
logger.error("MCP server terminated with error: %s", exc)
386+
raise SystemExit(1) from exc
387+
except Exception as exc: # pylint: disable=broad-except
388+
logger.error("Unexpected MCP server error: %s", exc)
389+
raise
306390

307391
if __name__ == '__main__':
308392
main()

0 commit comments

Comments
 (0)