rag-nextjs 1.0.0__py3-none-any.whl
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.
- rag_nextjs/__init__.py +1 -0
- rag_nextjs/__main__.py +4 -0
- rag_nextjs/answer.py +351 -0
- rag_nextjs/cli.py +47 -0
- rag_nextjs/console_status.py +171 -0
- rag_nextjs/indexing.py +49 -0
- rag_nextjs/mcp_docs.py +71 -0
- rag_nextjs-1.0.0.dist-info/METADATA +146 -0
- rag_nextjs-1.0.0.dist-info/RECORD +13 -0
- rag_nextjs-1.0.0.dist-info/WHEEL +5 -0
- rag_nextjs-1.0.0.dist-info/entry_points.txt +2 -0
- rag_nextjs-1.0.0.dist-info/licenses/LICENSE +201 -0
- rag_nextjs-1.0.0.dist-info/top_level.txt +1 -0
rag_nextjs/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Next.js 公式ドキュメントを next-devtools-mcp 経由で取得する RAG 用パッケージ。"""
|
rag_nextjs/__main__.py
ADDED
rag_nextjs/answer.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from mcp import ClientSession
|
|
9
|
+
from mcp.client.stdio import stdio_client
|
|
10
|
+
from openai import OpenAI
|
|
11
|
+
|
|
12
|
+
from rag_nextjs.console_status import ConsoleProgress, run_sync_blocking_with_spinner
|
|
13
|
+
from rag_nextjs.indexing import rank_doc_paths
|
|
14
|
+
from rag_nextjs.mcp_docs import (
|
|
15
|
+
fetch_nextjs_docs_page,
|
|
16
|
+
format_fetched_pages,
|
|
17
|
+
next_devtools_stdio_params,
|
|
18
|
+
read_llms_index,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _env_bool(name: str, default: bool) -> bool:
|
|
23
|
+
raw = os.getenv(name)
|
|
24
|
+
if raw is None or raw.strip() == "":
|
|
25
|
+
return default
|
|
26
|
+
return raw.strip().lower() in {"1", "true", "yes", "on"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _client_http_timeout() -> Any:
|
|
30
|
+
"""HTTP タイムアウト。巨大モデルや遅いゲートウェイ向けに環境変数で延長可能。"""
|
|
31
|
+
import httpx
|
|
32
|
+
|
|
33
|
+
raw = (
|
|
34
|
+
os.getenv("OPENAI_TIMEOUT")
|
|
35
|
+
or os.getenv("HTTP_TIMEOUT")
|
|
36
|
+
or os.getenv("CHAT_HTTP_TIMEOUT_SECONDS")
|
|
37
|
+
)
|
|
38
|
+
seconds = float(raw) if raw else 600.0
|
|
39
|
+
connect_raw = os.getenv("CHAT_HTTP_CONNECT_SECONDS")
|
|
40
|
+
connect = float(connect_raw) if connect_raw else 30.0
|
|
41
|
+
return httpx.Timeout(timeout=seconds, connect=connect)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _get_client() -> OpenAI:
|
|
45
|
+
base = os.getenv("OPENAI_BASE_URL") or os.getenv("NVIDIA_OPENAI_BASE_URL")
|
|
46
|
+
key = os.getenv("OPENAI_API_KEY") or os.getenv("NVIDIA_API_KEY")
|
|
47
|
+
if not key:
|
|
48
|
+
raise RuntimeError("OPENAI_API_KEY または NVIDIA_API_KEY を .env に設定してください")
|
|
49
|
+
kwargs: dict[str, Any] = {"api_key": key, "timeout": _client_http_timeout()}
|
|
50
|
+
if base:
|
|
51
|
+
kwargs["base_url"] = base
|
|
52
|
+
return OpenAI(**kwargs)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# OpenAI 互換 API が delta / message に載せる推論テキスト系フィールド(既定ではstdoutに出さない)
|
|
56
|
+
_DELTA_REASONING_KEYS: tuple[str, ...] = (
|
|
57
|
+
"reasoning_content",
|
|
58
|
+
"reasoning",
|
|
59
|
+
"thinking",
|
|
60
|
+
"thought",
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
# content が配列のとき、type で推論ブロックとみなして除外する値
|
|
64
|
+
_CONTENT_REASONING_TYPES: frozenset[str] = frozenset({"reasoning", "thinking", "thought"})
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _get_str_field(obj: Any, key: str) -> str | None:
|
|
68
|
+
if obj is None:
|
|
69
|
+
return None
|
|
70
|
+
if isinstance(obj, Mapping):
|
|
71
|
+
val = obj.get(key)
|
|
72
|
+
else:
|
|
73
|
+
val = getattr(obj, key, None)
|
|
74
|
+
if isinstance(val, str) and val:
|
|
75
|
+
return val
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _stringify_content_field(content: Any, *, include_reasoning: bool) -> str | None:
|
|
80
|
+
"""message / delta の content が str だけでなく list[dict] 形式のときに連結して返す。"""
|
|
81
|
+
if content is None:
|
|
82
|
+
return None
|
|
83
|
+
if isinstance(content, str):
|
|
84
|
+
return content if content.strip() else None
|
|
85
|
+
if isinstance(content, list):
|
|
86
|
+
parts: list[str] = []
|
|
87
|
+
for block in content:
|
|
88
|
+
if isinstance(block, str) and block:
|
|
89
|
+
parts.append(block)
|
|
90
|
+
continue
|
|
91
|
+
if isinstance(block, Mapping):
|
|
92
|
+
bt = block.get("type")
|
|
93
|
+
if (
|
|
94
|
+
not include_reasoning
|
|
95
|
+
and isinstance(bt, str)
|
|
96
|
+
and bt.strip().lower() in _CONTENT_REASONING_TYPES
|
|
97
|
+
):
|
|
98
|
+
continue
|
|
99
|
+
t = block.get("text")
|
|
100
|
+
if isinstance(t, str) and t:
|
|
101
|
+
parts.append(t)
|
|
102
|
+
continue
|
|
103
|
+
if block.get("type") == "text":
|
|
104
|
+
nested = block.get("text")
|
|
105
|
+
if isinstance(nested, str) and nested:
|
|
106
|
+
parts.append(nested)
|
|
107
|
+
return "".join(parts) if parts else None
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _iter_delta_text_parts(delta: Any, *, include_reasoning: bool) -> Iterator[str]:
|
|
112
|
+
"""ストリーミング chunk の delta から、表示すべき文字列を順に取り出す。"""
|
|
113
|
+
if delta is None:
|
|
114
|
+
return
|
|
115
|
+
if include_reasoning:
|
|
116
|
+
for key in _DELTA_REASONING_KEYS:
|
|
117
|
+
s = _get_str_field(delta, key)
|
|
118
|
+
if s:
|
|
119
|
+
yield s
|
|
120
|
+
ref = _get_str_field(delta, "refusal")
|
|
121
|
+
if ref:
|
|
122
|
+
yield ref
|
|
123
|
+
raw_c = getattr(delta, "content", None) if not isinstance(delta, Mapping) else delta.get("content")
|
|
124
|
+
c = _stringify_content_field(raw_c, include_reasoning=include_reasoning)
|
|
125
|
+
if c:
|
|
126
|
+
yield c
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _iter_message_text_parts(message: Any, *, include_reasoning: bool) -> Iterator[str]:
|
|
130
|
+
"""非ストリーミング応答の message から表示用テキストを取り出す。"""
|
|
131
|
+
if message is None:
|
|
132
|
+
return
|
|
133
|
+
if include_reasoning:
|
|
134
|
+
for key in _DELTA_REASONING_KEYS:
|
|
135
|
+
s = _get_str_field(message, key)
|
|
136
|
+
if s:
|
|
137
|
+
yield s
|
|
138
|
+
ref = _get_str_field(message, "refusal")
|
|
139
|
+
if ref:
|
|
140
|
+
yield ref
|
|
141
|
+
raw_c = getattr(message, "content", None) if not isinstance(message, Mapping) else message.get(
|
|
142
|
+
"content"
|
|
143
|
+
)
|
|
144
|
+
c = _stringify_content_field(raw_c, include_reasoning=include_reasoning)
|
|
145
|
+
if c:
|
|
146
|
+
yield c
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _iter_chunk_text_parts(chunk: Any, *, include_reasoning: bool) -> Iterator[str]:
|
|
150
|
+
"""ChatCompletionChunk 互換オブジェクトからテキスト断片を取り出す。"""
|
|
151
|
+
choices = getattr(chunk, "choices", None) or []
|
|
152
|
+
for choice in choices:
|
|
153
|
+
delta = getattr(choice, "delta", None)
|
|
154
|
+
yield from _iter_delta_text_parts(delta, include_reasoning=include_reasoning)
|
|
155
|
+
# 一部プロキシはストリーム終端付近で message に本文だけ載せる
|
|
156
|
+
msg = getattr(choice, "message", None)
|
|
157
|
+
yield from _iter_message_text_parts(msg, include_reasoning=include_reasoning)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _model_name() -> str:
|
|
161
|
+
return os.getenv("CHAT_MODEL", "nvidia/nemotron-3-nano-30b-a3b")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _build_messages(question: str, context: str) -> list[dict[str, str]]:
|
|
165
|
+
system = (
|
|
166
|
+
"あなたは Next.js の公式ドキュメント(与えられたコンテキスト)だけを根拠に回答するアシスタントです。"
|
|
167
|
+
"コンテキストに無い内容は推測せず、その旨を述べてください。"
|
|
168
|
+
"コード例は公式に沿った形で示し、必要なら path(ドキュメント上のパス)を引用してください。"
|
|
169
|
+
)
|
|
170
|
+
user = f"## 参照した公式ドキュメント\n\n{context}\n\n## 質問\n\n{question}"
|
|
171
|
+
return [
|
|
172
|
+
{"role": "system", "content": system},
|
|
173
|
+
{"role": "user", "content": user},
|
|
174
|
+
]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
async def gather_context(
|
|
178
|
+
session: ClientSession,
|
|
179
|
+
question: str,
|
|
180
|
+
top_k: int,
|
|
181
|
+
*,
|
|
182
|
+
on_phase: Callable[[str, str], None] | None = None,
|
|
183
|
+
) -> tuple[str, list[str]]:
|
|
184
|
+
if on_phase:
|
|
185
|
+
on_phase("インデックスを読み込み中", "")
|
|
186
|
+
index = await read_llms_index(session)
|
|
187
|
+
paths = rank_doc_paths(question, index, top_k=top_k)
|
|
188
|
+
if not paths:
|
|
189
|
+
return "", []
|
|
190
|
+
|
|
191
|
+
pages: list[dict[str, Any]] = []
|
|
192
|
+
for i, path in enumerate(paths, 1):
|
|
193
|
+
if on_phase:
|
|
194
|
+
on_phase("ドキュメント本文を取得中", f"{i}/{len(paths)} {path}")
|
|
195
|
+
try:
|
|
196
|
+
pages.append(await fetch_nextjs_docs_page(session, path))
|
|
197
|
+
except Exception as exc: # noqa: BLE001
|
|
198
|
+
pages.append({"path": path, "url": "", "content": f"[取得エラー: {exc}]"})
|
|
199
|
+
|
|
200
|
+
return format_fetched_pages(pages), paths
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _extra_body_from_env() -> dict[str, Any]:
|
|
204
|
+
raw_extra = os.getenv("CHAT_EXTRA_BODY")
|
|
205
|
+
if not raw_extra:
|
|
206
|
+
return {}
|
|
207
|
+
import json
|
|
208
|
+
|
|
209
|
+
return json.loads(raw_extra)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _build_chat_completion_kwargs(question: str, context: str, *, stream: bool) -> dict[str, Any]:
|
|
213
|
+
model = _model_name()
|
|
214
|
+
messages = _build_messages(question, context)
|
|
215
|
+
extra = _extra_body_from_env()
|
|
216
|
+
|
|
217
|
+
kwargs: dict[str, Any] = {
|
|
218
|
+
"model": model,
|
|
219
|
+
"messages": messages,
|
|
220
|
+
"temperature": float(os.getenv("CHAT_TEMPERATURE", "0.2")),
|
|
221
|
+
"stream": stream,
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
mt = os.getenv("CHAT_MAX_TOKENS")
|
|
225
|
+
if mt and mt.strip():
|
|
226
|
+
kwargs["max_tokens"] = int(mt.strip())
|
|
227
|
+
|
|
228
|
+
if extra:
|
|
229
|
+
kwargs["extra_body"] = extra
|
|
230
|
+
|
|
231
|
+
if stream and _env_bool("CHAT_STREAM_INCLUDE_USAGE", False):
|
|
232
|
+
kwargs["stream_options"] = {"include_usage": True}
|
|
233
|
+
|
|
234
|
+
return kwargs
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _non_stream_completion(
|
|
238
|
+
client: OpenAI,
|
|
239
|
+
kwargs: dict[str, Any],
|
|
240
|
+
*,
|
|
241
|
+
include_reasoning: bool,
|
|
242
|
+
) -> Iterator[str]:
|
|
243
|
+
kw = dict(kwargs)
|
|
244
|
+
kw["stream"] = False
|
|
245
|
+
kw.pop("stream_options", None)
|
|
246
|
+
resp = client.chat.completions.create(**kw)
|
|
247
|
+
choices = getattr(resp, "choices", None) or []
|
|
248
|
+
if not choices:
|
|
249
|
+
yield "[エラー] API 応答に choices がありません。"
|
|
250
|
+
return
|
|
251
|
+
msg = getattr(choices[0], "message", None)
|
|
252
|
+
parts = list(_iter_message_text_parts(msg, include_reasoning=include_reasoning))
|
|
253
|
+
if parts:
|
|
254
|
+
for p in parts:
|
|
255
|
+
yield p
|
|
256
|
+
return
|
|
257
|
+
first = choices[0]
|
|
258
|
+
yield (
|
|
259
|
+
"[エラー] メッセージ本文を取得できませんでした。"
|
|
260
|
+
f" finish_reason={getattr(first, 'finish_reason', None)!r}"
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def stream_answer(question: str, context: str) -> Iterator[str]:
|
|
265
|
+
"""OpenAI Chat Completions 互換エンドポイント向け。ストリーム非対応・空ストリームのモデルは非ストリームにフォールバック。"""
|
|
266
|
+
client = _get_client()
|
|
267
|
+
use_stream = _env_bool("CHAT_STREAM", True)
|
|
268
|
+
fb = _env_bool("CHAT_STREAM_FALLBACK", True)
|
|
269
|
+
include_reasoning = _env_bool("CHAT_SHOW_REASONING", False)
|
|
270
|
+
|
|
271
|
+
if not use_stream:
|
|
272
|
+
kwargs = _build_chat_completion_kwargs(question, context, stream=False)
|
|
273
|
+
yield from _non_stream_completion(client, kwargs, include_reasoning=include_reasoning)
|
|
274
|
+
return
|
|
275
|
+
|
|
276
|
+
kwargs_stream = _build_chat_completion_kwargs(question, context, stream=True)
|
|
277
|
+
stream = client.chat.completions.create(**kwargs_stream)
|
|
278
|
+
|
|
279
|
+
got_text = False
|
|
280
|
+
try:
|
|
281
|
+
for chunk in stream:
|
|
282
|
+
for piece in _iter_chunk_text_parts(chunk, include_reasoning=include_reasoning):
|
|
283
|
+
got_text = True
|
|
284
|
+
yield piece
|
|
285
|
+
finally:
|
|
286
|
+
close = getattr(stream, "close", None)
|
|
287
|
+
if callable(close):
|
|
288
|
+
close()
|
|
289
|
+
|
|
290
|
+
if not got_text and fb:
|
|
291
|
+
kwargs_ns = _build_chat_completion_kwargs(question, context, stream=False)
|
|
292
|
+
yield from _non_stream_completion(client, kwargs_ns, include_reasoning=include_reasoning)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
async def run_rag_cli(question: str, top_k: int, *, quiet: bool = False) -> None:
|
|
296
|
+
params = next_devtools_stdio_params()
|
|
297
|
+
|
|
298
|
+
quiet = quiet or _env_bool("RAG_QUIET", False)
|
|
299
|
+
progress = ConsoleProgress(enabled=not quiet)
|
|
300
|
+
|
|
301
|
+
context = ""
|
|
302
|
+
paths: list[str] = []
|
|
303
|
+
|
|
304
|
+
try:
|
|
305
|
+
progress.start("next-devtools-mcp を起動・接続中 …")
|
|
306
|
+
|
|
307
|
+
async with stdio_client(params) as (read, write):
|
|
308
|
+
async with ClientSession(read, write) as session:
|
|
309
|
+
await session.initialize()
|
|
310
|
+
progress.phase("next-devtools-mcp と通信中 …", "")
|
|
311
|
+
try:
|
|
312
|
+
await session.call_tool("init", {"project_path": os.getcwd()})
|
|
313
|
+
except Exception:
|
|
314
|
+
pass
|
|
315
|
+
|
|
316
|
+
context, paths = await gather_context(
|
|
317
|
+
session,
|
|
318
|
+
question,
|
|
319
|
+
top_k,
|
|
320
|
+
on_phase=lambda main, detail="": progress.phase(main, detail),
|
|
321
|
+
)
|
|
322
|
+
finally:
|
|
323
|
+
progress.stop_clear()
|
|
324
|
+
|
|
325
|
+
# MCP 子プロセスを閉じてから LLM ストリーム(空 choices チャンク等の異常時にセッションを巻き込まない)
|
|
326
|
+
if paths:
|
|
327
|
+
print("取得したドキュメント path:", ", ".join(paths))
|
|
328
|
+
print()
|
|
329
|
+
if not context.strip():
|
|
330
|
+
print("関連ドキュメントを取得できませんでした。質問の表現を変えて再度お試しください。")
|
|
331
|
+
return
|
|
332
|
+
|
|
333
|
+
iterator = iter(stream_answer(question, context))
|
|
334
|
+
first = run_sync_blocking_with_spinner(
|
|
335
|
+
lambda: next(iterator, None),
|
|
336
|
+
out=sys.stderr,
|
|
337
|
+
main="モデル応答を待機中",
|
|
338
|
+
detail=_model_name(),
|
|
339
|
+
enabled=(not quiet),
|
|
340
|
+
)
|
|
341
|
+
if first is None:
|
|
342
|
+
print()
|
|
343
|
+
return
|
|
344
|
+
|
|
345
|
+
sys.stdout.write(first)
|
|
346
|
+
sys.stdout.flush()
|
|
347
|
+
for piece in iterator:
|
|
348
|
+
sys.stdout.write(piece)
|
|
349
|
+
sys.stdout.flush()
|
|
350
|
+
sys.stdout.write("\n")
|
|
351
|
+
sys.stdout.flush()
|
rag_nextjs/cli.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Next.js 公式ドキュメント RAG のエントリポイント(コンソールスクリプト / python -m と共有)。
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import asyncio
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from dotenv import load_dotenv
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main() -> int:
|
|
16
|
+
load_dotenv()
|
|
17
|
+
if not os.getenv("NVIDIA_API_KEY") and not os.getenv("OPENAI_API_KEY"):
|
|
18
|
+
print(
|
|
19
|
+
"エラー: NVIDIA_API_KEY または OPENAI_API_KEY を .env に設定してください。",
|
|
20
|
+
file=sys.stderr,
|
|
21
|
+
)
|
|
22
|
+
return 1
|
|
23
|
+
|
|
24
|
+
parser = argparse.ArgumentParser(description="Next.js MCP 公式ドキュメント RAG")
|
|
25
|
+
parser.add_argument("question", help="Next.js についての質問")
|
|
26
|
+
parser.add_argument(
|
|
27
|
+
"--top-k",
|
|
28
|
+
type=int,
|
|
29
|
+
default=int(os.getenv("RAG_TOP_K", "4")),
|
|
30
|
+
help="取得するドキュメントページ数(既定 4)",
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument(
|
|
33
|
+
"-q",
|
|
34
|
+
"--quiet",
|
|
35
|
+
action="store_true",
|
|
36
|
+
help="進捗・スピナーを出さない(スクリプトからの利用向け)",
|
|
37
|
+
)
|
|
38
|
+
args = parser.parse_args()
|
|
39
|
+
|
|
40
|
+
from rag_nextjs.answer import run_rag_cli
|
|
41
|
+
|
|
42
|
+
asyncio.run(run_rag_cli(args.question, top_k=args.top_k, quiet=args.quiet))
|
|
43
|
+
return 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
if __name__ == "__main__":
|
|
47
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ターミナル用スピナーと進捗表示(回答の標準出力とは分離し stderr に表示)。
|
|
3
|
+
TTY でない場合はアニメーションの代わりに行単位のメッセージを出します。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
import sys
|
|
11
|
+
import threading
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import IO, TypeVar
|
|
14
|
+
|
|
15
|
+
_SPIN_FRAMES_ASCII = "|/-\\"
|
|
16
|
+
_SPIN_FRAMES_UNICODE = "⠋⠙⠹⠸⠼⠴⠦⠇⠏"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _env_bool(name: str, default: bool) -> bool:
|
|
20
|
+
raw = os.getenv(name)
|
|
21
|
+
if raw is None or raw.strip() == "":
|
|
22
|
+
return default
|
|
23
|
+
return raw.strip().lower() in {"1", "true", "yes", "on"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _use_unicode_spinner(stream: IO[str]) -> bool:
|
|
27
|
+
enc = getattr(stream, "encoding", None)
|
|
28
|
+
if isinstance(enc, str):
|
|
29
|
+
n = enc.lower().replace("_", "")
|
|
30
|
+
if n in {"utf-8", "utf8"}:
|
|
31
|
+
return True
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _format_status_line(prefix: str, main: str, detail: str) -> str:
|
|
36
|
+
cols = shutil.get_terminal_size(fallback=(88, 24)).columns
|
|
37
|
+
width = max(40, cols - 2)
|
|
38
|
+
body = f"{prefix} {main}"
|
|
39
|
+
if detail.strip():
|
|
40
|
+
body = f"{body} · {detail.strip()}"
|
|
41
|
+
if len(body) > width:
|
|
42
|
+
body = body[: width - 1] + "…"
|
|
43
|
+
return body
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class _SpinnerRunner(threading.Thread):
|
|
47
|
+
def __init__(self, out: IO[str], frames: str) -> None:
|
|
48
|
+
super().__init__(daemon=True)
|
|
49
|
+
self._out = out
|
|
50
|
+
self._frames = frames
|
|
51
|
+
self._stop = threading.Event()
|
|
52
|
+
self._lock = threading.Lock()
|
|
53
|
+
self._main = ""
|
|
54
|
+
self._detail = ""
|
|
55
|
+
|
|
56
|
+
def configure(self, main: str, detail: str = "") -> None:
|
|
57
|
+
with self._lock:
|
|
58
|
+
self._main = main
|
|
59
|
+
self._detail = detail
|
|
60
|
+
|
|
61
|
+
def halt(self) -> None:
|
|
62
|
+
self._stop.set()
|
|
63
|
+
|
|
64
|
+
def run(self) -> None:
|
|
65
|
+
i = 0
|
|
66
|
+
while not self._stop.wait(0.09):
|
|
67
|
+
with self._lock:
|
|
68
|
+
main, detail = self._main, self._detail
|
|
69
|
+
symbol = self._frames[i % len(self._frames)]
|
|
70
|
+
i += 1
|
|
71
|
+
line = _format_status_line(symbol, main, detail)
|
|
72
|
+
self._out.write(f"\r{line}\x1b[K")
|
|
73
|
+
self._out.flush()
|
|
74
|
+
|
|
75
|
+
def wipe(self) -> None:
|
|
76
|
+
self._out.write("\r\x1b[K")
|
|
77
|
+
self._out.flush()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class ConsoleProgress:
|
|
81
|
+
"""MCP・取得フェーズ用プログレス表示。"""
|
|
82
|
+
|
|
83
|
+
def __init__(self, *, enabled: bool, stream: IO[str] | None = None) -> None:
|
|
84
|
+
self._out: IO[str] = stream if stream is not None else sys.stderr
|
|
85
|
+
is_tty = getattr(self._out, "isatty", lambda: False)()
|
|
86
|
+
spinner_on = _env_bool("RAG_SPINNER", True)
|
|
87
|
+
force = _env_bool("RAG_SPINNER_FORCE", False)
|
|
88
|
+
frames = _SPIN_FRAMES_UNICODE if _use_unicode_spinner(self._out) else _SPIN_FRAMES_ASCII
|
|
89
|
+
self._enabled = enabled
|
|
90
|
+
self._animate = enabled and spinner_on and (is_tty or force)
|
|
91
|
+
self._runner: _SpinnerRunner | None = _SpinnerRunner(self._out, frames) if self._animate else None
|
|
92
|
+
self._started = False
|
|
93
|
+
self._last_plain: tuple[str, str] | None = None
|
|
94
|
+
|
|
95
|
+
def start(self, main: str, detail: str = "") -> None:
|
|
96
|
+
self.phase(main, detail)
|
|
97
|
+
if not self._enabled or self._started:
|
|
98
|
+
return
|
|
99
|
+
self._started = True
|
|
100
|
+
if self._runner:
|
|
101
|
+
self._runner.configure(main, detail)
|
|
102
|
+
self._runner.start()
|
|
103
|
+
|
|
104
|
+
def phase(self, main: str, detail: str = "") -> None:
|
|
105
|
+
if not self._enabled:
|
|
106
|
+
return
|
|
107
|
+
if self._runner and self._started and self._runner.is_alive():
|
|
108
|
+
self._runner.configure(main, detail)
|
|
109
|
+
return
|
|
110
|
+
if not self._animate:
|
|
111
|
+
key = (main, detail)
|
|
112
|
+
if key != self._last_plain:
|
|
113
|
+
self._last_plain = key
|
|
114
|
+
suffix = f" ({detail})" if detail.strip() else ""
|
|
115
|
+
self._out.write(f"[nextjs-rag]{suffix} {main}\n")
|
|
116
|
+
self._out.flush()
|
|
117
|
+
|
|
118
|
+
def stop_clear(self) -> None:
|
|
119
|
+
if not self._enabled:
|
|
120
|
+
return
|
|
121
|
+
if self._runner and self._started:
|
|
122
|
+
self._runner.halt()
|
|
123
|
+
self._runner.join(timeout=3.0)
|
|
124
|
+
self._runner.wipe()
|
|
125
|
+
self._started = False
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
T = TypeVar("T")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def run_sync_blocking_with_spinner(
|
|
132
|
+
fn: Callable[[], T],
|
|
133
|
+
*,
|
|
134
|
+
out: IO[str],
|
|
135
|
+
main: str,
|
|
136
|
+
detail: str = "",
|
|
137
|
+
enabled: bool,
|
|
138
|
+
) -> T:
|
|
139
|
+
"""同期ブロッキング処理(例: 最初のチャンクまで)を別スレッドのスピナー付きで包む。"""
|
|
140
|
+
if not enabled:
|
|
141
|
+
return fn()
|
|
142
|
+
|
|
143
|
+
is_tty = getattr(out, "isatty", lambda: False)()
|
|
144
|
+
spinner_on = _env_bool("RAG_SPINNER", True)
|
|
145
|
+
force = _env_bool("RAG_SPINNER_FORCE", False)
|
|
146
|
+
if not spinner_on or (not is_tty and not force):
|
|
147
|
+
out.write(f"[nextjs-rag] {main}{(' · ' + detail) if detail.strip() else ''}\n")
|
|
148
|
+
out.flush()
|
|
149
|
+
return fn()
|
|
150
|
+
|
|
151
|
+
frames = _SPIN_FRAMES_UNICODE if _use_unicode_spinner(out) else _SPIN_FRAMES_ASCII
|
|
152
|
+
stop = threading.Event()
|
|
153
|
+
|
|
154
|
+
def worker() -> None:
|
|
155
|
+
i = 0
|
|
156
|
+
while not stop.wait(0.09):
|
|
157
|
+
symbol = frames[i % len(frames)]
|
|
158
|
+
i += 1
|
|
159
|
+
line = _format_status_line(symbol, main, detail)
|
|
160
|
+
out.write(f"\r{line}\x1b[K")
|
|
161
|
+
out.flush()
|
|
162
|
+
|
|
163
|
+
th = threading.Thread(target=worker, daemon=True)
|
|
164
|
+
th.start()
|
|
165
|
+
try:
|
|
166
|
+
return fn()
|
|
167
|
+
finally:
|
|
168
|
+
stop.set()
|
|
169
|
+
th.join(timeout=3.0)
|
|
170
|
+
out.write("\r\x1b[K")
|
|
171
|
+
out.flush()
|
rag_nextjs/indexing.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections import Counter
|
|
5
|
+
|
|
6
|
+
# llms.txt 内の公式ドキュメント URL → nextjs_docs の path 引数
|
|
7
|
+
_DOC_PATH = re.compile(r"https://nextjs\.org(/docs[/a-zA-Z0-9._\-]+)")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def tokenize(text: str) -> list[str]:
|
|
11
|
+
return re.findall(r"[a-z0-9][a-z0-9_+\-/]*|[\u3040-\u30ff\u3400-\u9fff]+", text.lower())
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _line_score(query_counter: Counter[str], line: str) -> float:
|
|
15
|
+
line_counter = Counter(tokenize(line))
|
|
16
|
+
if not line_counter:
|
|
17
|
+
return 0.0
|
|
18
|
+
dot = sum(line_counter[w] * query_counter.get(w, 0) for w in line_counter)
|
|
19
|
+
return dot / (sum(line_counter.values()) ** 0.5 + 1e-9)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def extract_doc_paths_from_index(llms_index: str) -> list[tuple[str, str]]:
|
|
23
|
+
"""各行について (行テキスト, 最初の /docs パス) を返す。"""
|
|
24
|
+
rows: list[tuple[str, str]] = []
|
|
25
|
+
for line in llms_index.splitlines():
|
|
26
|
+
m = _DOC_PATH.search(line)
|
|
27
|
+
if m:
|
|
28
|
+
rows.append((line, m.group(1)))
|
|
29
|
+
return rows
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def rank_doc_paths(query: str, llms_index: str, top_k: int) -> list[str]:
|
|
33
|
+
"""クエリとインデックス行の簡易スコアリングで、重複のない path を最大 top_k 件選ぶ。"""
|
|
34
|
+
q = Counter(tokenize(query))
|
|
35
|
+
scored: list[tuple[float, str, str]] = []
|
|
36
|
+
for line, path in extract_doc_paths_from_index(llms_index):
|
|
37
|
+
scored.append((_line_score(q, line), path, line))
|
|
38
|
+
|
|
39
|
+
scored.sort(key=lambda x: x[0], reverse=True)
|
|
40
|
+
seen: set[str] = set()
|
|
41
|
+
out: list[str] = []
|
|
42
|
+
for _score, path, _line in scored:
|
|
43
|
+
if path in seen:
|
|
44
|
+
continue
|
|
45
|
+
seen.add(path)
|
|
46
|
+
out.append(path)
|
|
47
|
+
if len(out) >= top_k:
|
|
48
|
+
break
|
|
49
|
+
return out
|
rag_nextjs/mcp_docs.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import shlex
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from pydantic import AnyUrl
|
|
9
|
+
|
|
10
|
+
from mcp import StdioServerParameters
|
|
11
|
+
from mcp.client.stdio import stdio_client
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def next_devtools_stdio_params() -> StdioServerParameters:
|
|
15
|
+
"""環境変数 NEXTJS_MCP_COMMAND(既定: npx -y next-devtools-mcp)から起動コマンドを組み立てる。"""
|
|
16
|
+
raw = os.environ.get("NEXTJS_MCP_COMMAND", "npx -y next-devtools-mcp")
|
|
17
|
+
parts = shlex.split(raw)
|
|
18
|
+
if not parts:
|
|
19
|
+
raise ValueError("NEXTJS_MCP_COMMAND が空です")
|
|
20
|
+
return StdioServerParameters(command=parts[0], args=parts[1:])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def read_llms_index(session: ClientSession) -> str:
|
|
24
|
+
result = await session.read_resource(AnyUrl("nextjs-docs://llms-index"))
|
|
25
|
+
return "".join(c.text or "" for c in result.contents if c.text is not None)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _tool_text_payload(result: Any) -> str:
|
|
29
|
+
parts: list[str] = []
|
|
30
|
+
for block in getattr(result, "content", ()) or []:
|
|
31
|
+
if getattr(block, "type", None) == "text" and block.text:
|
|
32
|
+
parts.append(block.text)
|
|
33
|
+
return "\n".join(parts)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
async def fetch_nextjs_docs_page(session: ClientSession, path: str, anchor: str | None = None) -> dict[str, Any]:
|
|
37
|
+
args: dict[str, Any] = {"path": path}
|
|
38
|
+
if anchor:
|
|
39
|
+
args["anchor"] = anchor
|
|
40
|
+
result = await session.call_tool("nextjs_docs", args)
|
|
41
|
+
if result.isError:
|
|
42
|
+
payload = _tool_text_payload(result)
|
|
43
|
+
raise RuntimeError(f"nextjs_docs 失敗 path={path}: {payload}")
|
|
44
|
+
|
|
45
|
+
payload = _tool_text_payload(result)
|
|
46
|
+
data = json.loads(payload)
|
|
47
|
+
return data
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def format_fetched_pages(pages: list[dict[str, Any]], max_chars: int = 120_000) -> str:
|
|
51
|
+
chunks: list[str] = []
|
|
52
|
+
total = 0
|
|
53
|
+
for p in pages:
|
|
54
|
+
block = (
|
|
55
|
+
f"### path: {p.get('path')}\n"
|
|
56
|
+
f"url: {p.get('url')}\n\n"
|
|
57
|
+
f"{p.get('content', '')}"
|
|
58
|
+
)
|
|
59
|
+
if total + len(block) > max_chars:
|
|
60
|
+
remain = max_chars - total
|
|
61
|
+
if remain > 500:
|
|
62
|
+
chunks.append(block[:remain] + "\n\n[truncated]")
|
|
63
|
+
break
|
|
64
|
+
chunks.append(block)
|
|
65
|
+
total += len(block)
|
|
66
|
+
return "\n\n---\n\n".join(chunks)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def next_devtools_client():
|
|
70
|
+
"""stdio で next-devtools-mcp 子プロセスを起動する `stdio_client` 用コンテキストマネージャ。"""
|
|
71
|
+
return stdio_client(next_devtools_stdio_params())
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rag-nextjs
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Next.js 公式ドキュメント RAG CLI (next-devtools-mcp)
|
|
5
|
+
Author-email: econanringo <151092188+econanringo@users.noreply.github.com>
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: openai>=1.0.0
|
|
10
|
+
Requires-Dist: python-dotenv>=1.0.0
|
|
11
|
+
Requires-Dist: mcp>=1.27.0
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# Next.js 公式ドキュメント RAG(next-devtools-mcp)
|
|
15
|
+
|
|
16
|
+
[公式の `next-devtools-mcp`](https://www.npmjs.com/package/next-devtools-mcp) を経由して Next.js の公式ドキュメントを取得し、その内容だけを根拠に質問に答える Python の CLI です。MCP の `nextjs_docs` と `nextjs-docs://llms-index` を使うため、検索対象は常に公式が配布するインデックス/本文に沿います。
|
|
17
|
+
|
|
18
|
+
## 前提条件
|
|
19
|
+
|
|
20
|
+
- **Python 3.10+**(プロジェクトでは 3.14 付近で動作確認)
|
|
21
|
+
- **Node.js と `npx`**(MCP サーバーを `npx -y next-devtools-mcp` で起動するため)
|
|
22
|
+
- **OpenAI 互換の Chat API** に渡せる API キー(例: [NVIDIA Integrate API](https://build.nvidia.com/))
|
|
23
|
+
|
|
24
|
+
## セットアップ
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
cd /path/to/rag
|
|
28
|
+
python3 -m venv venv
|
|
29
|
+
source venv/bin/activate # Windows: venv\Scripts\activate
|
|
30
|
+
pip install -r requirements.txt
|
|
31
|
+
|
|
32
|
+
# (推奨)パスを通さなくても `rag-nextjs` で起動できるようにする
|
|
33
|
+
pip install -e .
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
環境変数用に `.env` を用意します。
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
cp .env.example .env
|
|
40
|
+
# .env を編集して API キーなどを設定
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## 環境変数
|
|
44
|
+
|
|
45
|
+
| 変数 | 必須 | 説明 |
|
|
46
|
+
|------|------|------|
|
|
47
|
+
| `NVIDIA_API_KEY` または `OPENAI_API_KEY` | はい | Chat API 用のキー |
|
|
48
|
+
| `NVIDIA_OPENAI_BASE_URL` または `OPENAI_BASE_URL` | 推奨 | 互換 API のベース URL(NVIDIA 利用時は `.env.example` の URL を参照) |
|
|
49
|
+
| `CHAT_MODEL` | いいえ | 既定: `nvidia/nemotron-3-nano-30b-a3b` |
|
|
50
|
+
| `CHAT_TEMPERATURE` | いいえ | 既定: `0.2` |
|
|
51
|
+
| `CHAT_EXTRA_BODY` | いいえ | `extra_body` に渡す JSON(例: Nemotron の推論オプション)。1 行の JSON 文字列 |
|
|
52
|
+
| `CHAT_STREAM` | いいえ | `1` / `true` / `yes` / `on` でストリーミング(既定)。`0` など falsy で常に **非ストリーミング** のみ送信 |
|
|
53
|
+
| `CHAT_STREAM_FALLBACK` | いいえ | 既定オン。ストリームを最後まで読んでも表示用テキストが一度も出ないとき、同じ入力で **非ストリーミングを 1 回** 試す |
|
|
54
|
+
| `CHAT_SHOW_REASONING` | いいえ | 既定オフ。オンにすると `reasoning_content` 等の **推論テキストも標準出力**に流す。推論付きモデルの通常利用ではオフのままがよい |
|
|
55
|
+
| `CHAT_MAX_TOKENS` | いいえ | 設定時のみ、`max_tokens` としてリクエストに付与 |
|
|
56
|
+
| `CHAT_STREAM_INCLUDE_USAGE` | いいえ | オン時、ストリーミング要求に `stream_options: {"include_usage": true}` を付与(使用量を最終チャンクで受け取る用途) |
|
|
57
|
+
| `CHAT_HTTP_TIMEOUT_SECONDS` | いいえ | 読み取り込みを含む HTTP タイムアウト(秒)。既定: `600` |
|
|
58
|
+
| `OPENAI_TIMEOUT` または `HTTP_TIMEOUT` | いいえ | 上記と同目的。評価は **`OPENAI_TIMEOUT` → `HTTP_TIMEOUT` → `CHAT_HTTP_TIMEOUT_SECONDS`** の先勝ち |
|
|
59
|
+
| `CHAT_HTTP_CONNECT_SECONDS` | いいえ | 接続確立までのタイムアウト(秒)。既定: `30`(遅い TLS でも切れにくくするため) |
|
|
60
|
+
| `NEXTJS_MCP_COMMAND` | いいえ | MCP 起動コマンド(シェルと同様に空白区切り)。既定: `npx -y next-devtools-mcp` |
|
|
61
|
+
| `RAG_TOP_K` | いいえ | `--top-k` の既定値(ページ取得数)。既定: `4` |
|
|
62
|
+
| `RAG_SPINNER` | いいえ | 進捗行のブラケット/スピナーアニメーション。既定オン(`1`)。`0` でアニメーションを無効にし、必要なときのみプレーンな `[nextjs-rag]` 行になる |
|
|
63
|
+
| `RAG_SPINNER_FORCE` | いいえ | `1` のとき **TTY でなくても** スピナーを描画(パイプ先が端末など特殊なとき向け)。既定オフ |
|
|
64
|
+
| `RAG_QUIET` | いいえ | `1` のとき **進捗表示をすべて出さない**(`-q` と同様の効果)。コマンドラインの `-q` と併用すると、どちらかが真なら抑止されます |
|
|
65
|
+
|
|
66
|
+
### Chat API(モデル差の吸収)
|
|
67
|
+
|
|
68
|
+
OpenAI の Chat Completions 互換エンドポイントを前提にしています。プロバイダやモデルによって次のような差があります。
|
|
69
|
+
|
|
70
|
+
- **ストリーム本文の欠落** … ゲートウェイ側でストリーミングの `delta` に本文が載らない場合がある → 既定では `CHAT_STREAM_FALLBACK` により **非ストリームで再試行**。
|
|
71
|
+
- **推論フィールドの名称** … `reasoning_content` 以外に `reasoning` / `thinking` / `thought` などで返す API がある → **既定ではユーザー向け回答の `content`(と `refusal`)だけ**を標準出力へ出し、推論は出しません。デバッグで推論も見たいときは `CHAT_SHOW_REASONING=1` を指定してください。
|
|
72
|
+
- **`content` の形** … 文字列だけでなく、`type: "text"` のブロックの配列で返す実装に対応します。
|
|
73
|
+
|
|
74
|
+
大規模モデル(例: `nvidia/nemotron-3-super-120b-a12b`)は **最初のトークンまで数十秒〜数分かかる**ことがあります。ログに path が出たあと無言に見える場合は、しばらく待つか、`CHAT_HTTP_TIMEOUT_SECONDS` をさらに延ばしてください。ストリームが不安定なら `CHAT_STREAM=0` で非ストリーム固定にすると確実です。
|
|
75
|
+
|
|
76
|
+
## 使い方
|
|
77
|
+
|
|
78
|
+
開発用にリポジトリへ **editable install** した場合(`pip install -e .`)、どこからでも次のように起動できます。
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
rag-nextjs "App Router で Server Actions を使うには?"
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
リポジトリ直下では従来どおり次も同じです(`main.py` に shebang があるため `./main.py` も可)。
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
python main.py "App Router で Server Actions を使うには?"
|
|
88
|
+
python -m rag_nextjs "App Router で Server Actions を使うには?"
|
|
89
|
+
./main.py --help
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
取得するドキュメントページ数を増やす:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
python main.py --top-k 5 "キャッシュの revalidate について"
|
|
96
|
+
rag-nextjs --top-k 5 "キャッシュの revalidate について"
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
ヘルプ:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
rag-nextjs --help
|
|
103
|
+
python -m rag_nextjs --help
|
|
104
|
+
python main.py --help
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
進捗は **標準エラー出力** に表示されます(処理中は `⠋ …` のようなアニメーションと、フェーズごとの説明。**ドキュメント取得中は何件目・どの path か**もここで更新されます。**モデル応答の初回トークン待ち**でも同様にスピナーを出します)。
|
|
108
|
+
|
|
109
|
+
**標準出力**には、`取得したドキュメント path: …` と空行のあと、続けて **回答本文**がストリーミングされます。回答だけファイルに残したいときは `2>/dev/null` で stderr を捨てるか、path 行を除去する必要があります。
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
rag-nextjs "質問…" 2>/dev/null > answer.txt
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
ログを抑えたいときは `-q` / `--quiet` または環境変数 `RAG_QUIET=1` を指定してください。回答は **できる限りストリーミング** され、非対応時は `CHAT_STREAM_FALLBACK` で非ストリーム再試行があります(オフにすると `CHAT_STREAM_FALLBACK=0`)。
|
|
116
|
+
|
|
117
|
+
## 動作の流れ(概要)
|
|
118
|
+
|
|
119
|
+
1. 子プロセスで `next-devtools-mcp` を起動し、MCP セッションを確立する。
|
|
120
|
+
2. リソース `nextjs-docs://llms-index` で公式インデックス(`llms.txt` 相当)を読む。
|
|
121
|
+
3. 質問文とインデックス行の単語重なりで、関連しそうなドキュメント path を最大 `top_k` 件選ぶ。
|
|
122
|
+
4. 各 path に対してツール `nextjs_docs` で本文を取得する。
|
|
123
|
+
5. 取得本文をコンテキストとして、設定した Chat モデルに送り、回答を生成する。
|
|
124
|
+
|
|
125
|
+
LLM は可能なら **ストリーミング** で逐次標準出力に表示し、(5) が本文ゼロで終わった場合のみ **同一プロンプトを非ストリーミングで再実行**します(`CHAT_STREAM_FALLBACK` がオンで、`CHAT_STREAM` がオンのとき)。進捗の見た目は stderr のスピナーが担います。
|
|
126
|
+
|
|
127
|
+
インデックス説明が英語中心のため、日本語のみの短い質問だと取得 path が外れやすい場合があります。そのときは **`--top-k` を大きくする**か、ドキュメントで使われている用語(Server Actions、Route Handler など)を混ぜてみてください。
|
|
128
|
+
|
|
129
|
+
この README の対象は **公式サイトのドキュメントを読む**経路です。
|
|
130
|
+
|
|
131
|
+
- **`nextjs_docs` / `llms-index`** … nextjs.org の公式ドキュメントに基づいて答える(本プロジェクトが利用)。
|
|
132
|
+
- **`nextjs_index` / `nextjs_call`** … ローカルで動いている **Next.js 16 以降の開発サーバー**の MCP(`/_next/mcp`)に接続し、コンパイルエラーやルート情報など**実行中アプリの状態**を調べる用途。
|
|
133
|
+
|
|
134
|
+
アプリのランタイム診断まで Python から行いたい場合は、別途 dev サーバーを起動したうえで、そのツール群を呼び出す実装が必要になります。
|
|
135
|
+
|
|
136
|
+
## トラブルシューティング
|
|
137
|
+
|
|
138
|
+
- **`npx` が見つからない** … Node.js をインストールし、`NEXTJS_MCP_COMMAND` でフルパスの `npx` を指定するか、`PATH` を通してください。
|
|
139
|
+
- **`next-devtools-mcp` の起動に失敗する** … ネットワークで npm レジストリに届くか、`npx -y next-devtools-mcp` を手動で実行できるか確認してください。
|
|
140
|
+
- **関連ドキュメントが取得できない** … 質問を変える、`--top-k` を増やす、英語キーワードを足す。
|
|
141
|
+
- **API エラー** … `.env` のベース URL・モデル名・キーが、そのプロバイダの OpenAI 互換仕様と一致しているか確認してください。
|
|
142
|
+
- **回答がずっと出ない(path のあとで止まる)** … stderr に「モデル応答を待機中…」のスピナーが動いていれば、まだ初回トークン待ちです。大モデルは数十秒〜かかることがあります。標準エラーを見ていないターミナルでは `2>&1 | tee log.txt` などで確認してください。長すぎる場合は `CHAT_HTTP_TIMEOUT_SECONDS` を延ばす。ストリームが空のまま終わる API では `CHAT_STREAM_FALLBACK`(既定オン)で非ストリームに切り替わるはずなので、それでもダメなら `CHAT_STREAM=0` や `CHAT_MAX_TOKENS` / `CHAT_EXTRA_BODY` でプロバイダ必須パラメータを渡す。
|
|
143
|
+
|
|
144
|
+
## ライセンス
|
|
145
|
+
|
|
146
|
+
リポジトリ側のライセンスに従ってください。`next-devtools-mcp` 本体は npm パッケージのライセンス(MIT)が適用されます。
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
rag_nextjs/__init__.py,sha256=ZJVW17NzZ9mw3vT64QSC9dCbzo1ilkrQTzeGPYs-J8I,108
|
|
2
|
+
rag_nextjs/__main__.py,sha256=x5LayGsEAhfzBvm77EHraFSDOaIMzbgt4wQvRj57KrI,89
|
|
3
|
+
rag_nextjs/answer.py,sha256=WSncmpwQVGm77IF5h3HRETugeAT29hr0vxJZ9C1JtfM,12288
|
|
4
|
+
rag_nextjs/cli.py,sha256=CqzDT_zJte23pH1-3DQ-ix-1sGh399rR9uGSfT0O9bs,1324
|
|
5
|
+
rag_nextjs/console_status.py,sha256=FPjT44aZbvk7Qs8Ycaclgx8K8-s-UjdhwaSysPbvZnI,5440
|
|
6
|
+
rag_nextjs/indexing.py,sha256=hU_D0equKYN9EVpreN-LmWrMiHVm0Y2HNPmo5oS7eS8,1705
|
|
7
|
+
rag_nextjs/mcp_docs.py,sha256=tWvMO__iS5GObkKSKiGMnM249x7nff5awUr59unap-w,2404
|
|
8
|
+
rag_nextjs-1.0.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
9
|
+
rag_nextjs-1.0.0.dist-info/METADATA,sha256=UkdBfnarW7A2OJIL7l9lvcW-m7ALcxOvBv6PUJ7EH1Y,11011
|
|
10
|
+
rag_nextjs-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
11
|
+
rag_nextjs-1.0.0.dist-info/entry_points.txt,sha256=idgnJ-AioDbACAeA6DDWkaJX09CaYeGkTM67YWchNws,51
|
|
12
|
+
rag_nextjs-1.0.0.dist-info/top_level.txt,sha256=N6YvEt4c5EE6K5Gx9YUlZKdd9Au7B_57NZJsG25bho8,11
|
|
13
|
+
rag_nextjs-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
rag_nextjs
|