spaider-cli 0.1.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.
- spaider_cli/__init__.py +14 -0
- spaider_cli/commands/__init__.py +6 -0
- spaider_cli/commands/agent.py +178 -0
- spaider_cli/commands/doctor.py +231 -0
- spaider_cli/commands/init.py +405 -0
- spaider_cli/commands/mcp.py +193 -0
- spaider_cli/lib/__init__.py +10 -0
- spaider_cli/lib/api.py +160 -0
- spaider_cli/lib/docker.py +117 -0
- spaider_cli/lib/env.py +135 -0
- spaider_cli/lib/llm.py +87 -0
- spaider_cli/lib/mcp.py +285 -0
- spaider_cli/main.py +71 -0
- spaider_cli/skills/__init__.py +8 -0
- spaider_cli/skills/claude_code.md +151 -0
- spaider_cli-0.1.0.dist-info/METADATA +121 -0
- spaider_cli-0.1.0.dist-info/RECORD +21 -0
- spaider_cli-0.1.0.dist-info/WHEEL +5 -0
- spaider_cli-0.1.0.dist-info/entry_points.txt +2 -0
- spaider_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
- spaider_cli-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
"""``spaider init`` — first-time install wizard.
|
|
2
|
+
|
|
3
|
+
Takes a fresh checkout from "git clone" to "working Studio + MCP-integrated
|
|
4
|
+
Claude Code" in one command. The interactive prompts can be skipped via
|
|
5
|
+
flags so the wizard is automation-friendly.
|
|
6
|
+
|
|
7
|
+
Order of operations:
|
|
8
|
+
|
|
9
|
+
1. Check Docker (CLI present + daemon running).
|
|
10
|
+
2. Prompt for LLM provider + API key; validate the key with a real probe.
|
|
11
|
+
3. Generate the secrets the user shouldn't have to type (JWT, connector key,
|
|
12
|
+
Neo4j password).
|
|
13
|
+
4. Merge the values into the ``.env`` file (creating from ``.env.example`` if
|
|
14
|
+
needed, preserving any user-set keys, backing up any prior version).
|
|
15
|
+
5. ``docker compose up -d backend-api``; wait for ``/health`` to go healthy.
|
|
16
|
+
6. Provision a dev agent named ``dev-${USER}`` (or rotate it if it already
|
|
17
|
+
exists).
|
|
18
|
+
7. Install the MCP server entry + skill file into ``~/.claude/`` (skip with
|
|
19
|
+
``--skip-mcp``).
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import os
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
import typer
|
|
27
|
+
from rich.console import Console
|
|
28
|
+
from rich.panel import Panel
|
|
29
|
+
from rich.prompt import Prompt
|
|
30
|
+
|
|
31
|
+
from spaider_cli.lib import api as api_client
|
|
32
|
+
from spaider_cli.lib import docker as docker_lib
|
|
33
|
+
from spaider_cli.lib import env as env_lib
|
|
34
|
+
from spaider_cli.lib import llm as llm_lib
|
|
35
|
+
from spaider_cli.lib import mcp as mcp_lib
|
|
36
|
+
|
|
37
|
+
console = Console()
|
|
38
|
+
err_console = Console(stderr=True)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def run(
|
|
42
|
+
repo: Path = typer.Option(
|
|
43
|
+
Path.cwd(),
|
|
44
|
+
"--repo",
|
|
45
|
+
help="Path to the SpAIder checkout. Defaults to the current directory.",
|
|
46
|
+
),
|
|
47
|
+
provider: str | None = typer.Option(
|
|
48
|
+
None,
|
|
49
|
+
"--provider",
|
|
50
|
+
help="LLM provider: openai, anthropic, or ollama. Prompted if omitted.",
|
|
51
|
+
),
|
|
52
|
+
llm_key: str | None = typer.Option(
|
|
53
|
+
None,
|
|
54
|
+
"--llm-key",
|
|
55
|
+
help="API key for the chosen --provider. Not needed for ollama. Prompted if omitted.",
|
|
56
|
+
),
|
|
57
|
+
llm_base_url: str | None = typer.Option(
|
|
58
|
+
None,
|
|
59
|
+
"--llm-base-url",
|
|
60
|
+
help="Base URL for self-hosted providers (e.g. Ollama). Prompted for ollama if omitted.",
|
|
61
|
+
),
|
|
62
|
+
skip_docker: bool = typer.Option(
|
|
63
|
+
False,
|
|
64
|
+
"--skip-docker",
|
|
65
|
+
help="Do not run docker compose up. Useful when the stack is already running.",
|
|
66
|
+
),
|
|
67
|
+
skip_mcp: bool = typer.Option(
|
|
68
|
+
False,
|
|
69
|
+
"--skip-mcp",
|
|
70
|
+
help="Do not write to ~/.claude/. The agent + .env are still configured.",
|
|
71
|
+
),
|
|
72
|
+
agent_name: str | None = typer.Option(
|
|
73
|
+
None,
|
|
74
|
+
"--agent",
|
|
75
|
+
help="Override the auto-generated agent name (default: dev-${USER}).",
|
|
76
|
+
),
|
|
77
|
+
) -> None:
|
|
78
|
+
"""Run the first-time install wizard."""
|
|
79
|
+
repo = repo.expanduser().resolve()
|
|
80
|
+
console.print(
|
|
81
|
+
Panel.fit(
|
|
82
|
+
"[bold cyan]SpAIder init[/]\n"
|
|
83
|
+
"Memory infrastructure for AI agents — let's get you set up.",
|
|
84
|
+
border_style="cyan",
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# 1. Docker
|
|
89
|
+
console.print("\n[bold][1/6] Checking Docker[/]")
|
|
90
|
+
status = docker_lib.check_docker_available()
|
|
91
|
+
if not status.cli_present:
|
|
92
|
+
err_console.print(
|
|
93
|
+
"[red]✗[/] docker CLI not found in PATH. Install Docker Desktop first: "
|
|
94
|
+
"https://www.docker.com/products/docker-desktop/"
|
|
95
|
+
)
|
|
96
|
+
raise typer.Exit(code=1)
|
|
97
|
+
if not status.daemon_running:
|
|
98
|
+
err_console.print(
|
|
99
|
+
f"[red]✗[/] Docker daemon not running. Start Docker Desktop and try again.\n"
|
|
100
|
+
f" Underlying error: {status.error}"
|
|
101
|
+
)
|
|
102
|
+
raise typer.Exit(code=1)
|
|
103
|
+
console.print(" [green]✓[/] Docker CLI present + daemon running")
|
|
104
|
+
|
|
105
|
+
# 2. LLM provider + credentials
|
|
106
|
+
console.print("\n[bold][2/6] LLM provider[/]")
|
|
107
|
+
provider_overrides = _configure_providers(
|
|
108
|
+
provider_opt=provider, llm_key=llm_key, base_url_opt=llm_base_url,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
# 3. Secrets
|
|
112
|
+
# Re-run safety: NEVER regenerate a secret that already exists in .env.
|
|
113
|
+
# The running Neo4j container is created with whatever NEO4J_PASSWORD was in
|
|
114
|
+
# .env at first boot; rewriting it on a re-run would lock the backend out of
|
|
115
|
+
# its own database (and silently invalidate JWTs / connector ciphertext).
|
|
116
|
+
# So generate only the secrets that are missing/empty, and preserve the rest.
|
|
117
|
+
console.print("\n[bold][3/6] Generating secrets[/]")
|
|
118
|
+
env_path = repo / ".env"
|
|
119
|
+
existing = (
|
|
120
|
+
env_lib.parse_env_text(env_path.read_text(encoding="utf-8"))
|
|
121
|
+
if env_path.exists()
|
|
122
|
+
else {}
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def _keep_or_generate(key: str, generator) -> tuple[str, bool]:
|
|
126
|
+
current = existing.get(key, "").strip()
|
|
127
|
+
return (current, True) if current else (generator(), False)
|
|
128
|
+
|
|
129
|
+
jwt, jwt_kept = _keep_or_generate("JWT_SECRET", env_lib.generate_jwt_secret)
|
|
130
|
+
connector_key, ck_kept = _keep_or_generate("CONNECTOR_SECRET_KEY", env_lib.generate_connector_key)
|
|
131
|
+
neo4j_pw, neo_kept = _keep_or_generate("NEO4J_PASSWORD", env_lib.generate_neo4j_password)
|
|
132
|
+
if jwt_kept or ck_kept or neo_kept:
|
|
133
|
+
console.print(" [green]✓[/] Reused existing secrets where present (re-run safe)")
|
|
134
|
+
else:
|
|
135
|
+
console.print(" [green]✓[/] JWT signing secret, connector encryption key, Neo4j password")
|
|
136
|
+
|
|
137
|
+
# 4. .env
|
|
138
|
+
console.print("\n[bold][4/6] Writing .env[/]")
|
|
139
|
+
overrides = {
|
|
140
|
+
**provider_overrides,
|
|
141
|
+
"JWT_SECRET": jwt,
|
|
142
|
+
"CONNECTOR_SECRET_KEY": connector_key,
|
|
143
|
+
"NEO4J_PASSWORD": neo4j_pw,
|
|
144
|
+
}
|
|
145
|
+
example_path = repo / ".env.example"
|
|
146
|
+
try:
|
|
147
|
+
backup = env_lib.write_env_file(
|
|
148
|
+
target=env_path, example=example_path, overrides=overrides,
|
|
149
|
+
)
|
|
150
|
+
except FileNotFoundError as exc:
|
|
151
|
+
err_console.print(f" [red]✗[/] {exc}")
|
|
152
|
+
raise typer.Exit(code=1)
|
|
153
|
+
if backup:
|
|
154
|
+
console.print(f" [green]✓[/] {env_path} (backup: {backup})")
|
|
155
|
+
else:
|
|
156
|
+
console.print(f" [green]✓[/] {env_path}")
|
|
157
|
+
|
|
158
|
+
# 5. Stack up
|
|
159
|
+
if skip_docker:
|
|
160
|
+
console.print("\n[bold][5/6] Stack startup[/] [dim](skipped via --skip-docker)[/]")
|
|
161
|
+
else:
|
|
162
|
+
console.print("\n[bold][5/6] Starting Docker stack[/]")
|
|
163
|
+
compose = docker_lib.compose_up(repo)
|
|
164
|
+
if not compose.ok:
|
|
165
|
+
err_console.print(
|
|
166
|
+
f" [red]✗[/] docker compose up failed (rc={compose.returncode}):\n"
|
|
167
|
+
f" {compose.stderr.strip()[:400]}"
|
|
168
|
+
)
|
|
169
|
+
raise typer.Exit(code=1)
|
|
170
|
+
console.print(" Containers starting…")
|
|
171
|
+
if not docker_lib.wait_for_backend():
|
|
172
|
+
err_console.print(
|
|
173
|
+
" [red]✗[/] backend-api did not become healthy within 120s. "
|
|
174
|
+
"Run [bold]docker compose logs backend-api[/] to investigate."
|
|
175
|
+
)
|
|
176
|
+
raise typer.Exit(code=1)
|
|
177
|
+
console.print(" [green]✓[/] backend-api healthy on :8000")
|
|
178
|
+
|
|
179
|
+
# 6. Agent + MCP
|
|
180
|
+
resolved_agent = agent_name or _default_agent_name()
|
|
181
|
+
console.print(f"\n[bold][6/6] Provisioning agent '{resolved_agent}'[/]")
|
|
182
|
+
try:
|
|
183
|
+
existing = api_client.find_agent_by_name(resolved_agent)
|
|
184
|
+
if existing is None:
|
|
185
|
+
agent = api_client.create_agent(resolved_agent)
|
|
186
|
+
agent_id = agent.id
|
|
187
|
+
agent_key = agent.api_key or ""
|
|
188
|
+
else:
|
|
189
|
+
agent_id = existing.id
|
|
190
|
+
agent_key = api_client.rotate_key(existing.id)
|
|
191
|
+
except api_client.SpaiderApiError as exc:
|
|
192
|
+
err_console.print(f" [red]✗[/] agent provisioning failed: {exc}")
|
|
193
|
+
raise typer.Exit(code=1)
|
|
194
|
+
console.print(f" [green]✓[/] agent ready (id={agent_id})")
|
|
195
|
+
|
|
196
|
+
if skip_mcp:
|
|
197
|
+
console.print("\n[dim]Skipping MCP install (--skip-mcp).[/]")
|
|
198
|
+
_print_success_summary(agent_name=resolved_agent, agent_key=agent_key, mcp_done=False)
|
|
199
|
+
return
|
|
200
|
+
|
|
201
|
+
console.print("\n[bold]Installing MCP into Claude Code[/]")
|
|
202
|
+
report = mcp_lib.install_for_claude_code(
|
|
203
|
+
url="http://localhost:8000/api/v1/mcp/sse",
|
|
204
|
+
api_key=agent_key,
|
|
205
|
+
)
|
|
206
|
+
console.print(f" [green]✓[/] {report.config_path}")
|
|
207
|
+
console.print(f" [green]✓[/] {report.skill_path}")
|
|
208
|
+
|
|
209
|
+
_print_success_summary(
|
|
210
|
+
agent_name=resolved_agent, agent_key=agent_key, mcp_done=True,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# ---------------------------------------------------------------------------
|
|
215
|
+
# Prompts + final summary
|
|
216
|
+
# ---------------------------------------------------------------------------
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# Per-provider defaults written to .env. The backend (LiteLLM) derives the
|
|
220
|
+
# provider prefix from LLM_PROVIDER + LLM_BASE_URL, so these only need the bare
|
|
221
|
+
# model id. EMBEDDING_DIMENSIONS MUST match the embedding model's real output —
|
|
222
|
+
# a wrong value silently breaks the Neo4j vector index.
|
|
223
|
+
_PROVIDERS = ("openai", "anthropic", "ollama")
|
|
224
|
+
_LLM_DEFAULT_MODEL = {
|
|
225
|
+
"openai": "gpt-4o",
|
|
226
|
+
"anthropic": "claude-sonnet-4-5",
|
|
227
|
+
"ollama": "llama3.1",
|
|
228
|
+
}
|
|
229
|
+
_OLLAMA_DEFAULT_URL = "http://host.docker.internal:11434"
|
|
230
|
+
_EMBED_OPENAI = {"model": "text-embedding-3-small", "dims": "1536"}
|
|
231
|
+
_EMBED_OLLAMA = {"model": "embeddinggemma:300m", "dims": "768"}
|
|
232
|
+
_OPENAI_KEY_URL = "https://platform.openai.com/api-keys"
|
|
233
|
+
_ANTHROPIC_KEY_URL = "https://console.anthropic.com/"
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _configure_providers(
|
|
237
|
+
*, provider_opt: str | None, llm_key: str | None,
|
|
238
|
+
base_url_opt: str | None = None,
|
|
239
|
+
) -> dict[str, str]:
|
|
240
|
+
"""Resolve the LLM + embedding provider config and return .env overrides.
|
|
241
|
+
|
|
242
|
+
Prompts (and validates) interactively unless the relevant flags are
|
|
243
|
+
supplied (``--provider`` / ``--llm-key`` / ``--llm-base-url``).
|
|
244
|
+
"""
|
|
245
|
+
provider = (provider_opt or _prompt_provider_choice()).lower().strip()
|
|
246
|
+
if provider not in _PROVIDERS:
|
|
247
|
+
err_console.print(
|
|
248
|
+
f" [red]✗[/] unknown provider '{provider}'. "
|
|
249
|
+
f"Choose one of: {', '.join(_PROVIDERS)}."
|
|
250
|
+
)
|
|
251
|
+
raise typer.Exit(code=1)
|
|
252
|
+
|
|
253
|
+
llm_api_key = ""
|
|
254
|
+
llm_base_url = ""
|
|
255
|
+
|
|
256
|
+
if provider == "openai":
|
|
257
|
+
key = llm_key or _prompt_api_key("OpenAI", _OPENAI_KEY_URL)
|
|
258
|
+
llm_api_key = _validate_openai_loop(key)
|
|
259
|
+
embed = _embed_openai(llm_api_key)
|
|
260
|
+
elif provider == "anthropic":
|
|
261
|
+
key = llm_key or _prompt_api_key("Anthropic", _ANTHROPIC_KEY_URL)
|
|
262
|
+
llm_api_key = _validate_anthropic_loop(key)
|
|
263
|
+
# Anthropic has no embedding API — pick a separate embedding backend.
|
|
264
|
+
embed = _configure_embeddings_for_anthropic()
|
|
265
|
+
else: # ollama — local, no key
|
|
266
|
+
base_url = base_url_opt or _prompt_base_url(default=_OLLAMA_DEFAULT_URL)
|
|
267
|
+
llm_base_url = _validate_ollama_loop(base_url)
|
|
268
|
+
embed = _embed_ollama(llm_base_url)
|
|
269
|
+
|
|
270
|
+
model = _LLM_DEFAULT_MODEL[provider]
|
|
271
|
+
console.print(
|
|
272
|
+
f" [green]✓[/] LLM=[bold]{provider}[/] ({model}) · "
|
|
273
|
+
f"embeddings=[bold]{embed['EMBEDDING_PROVIDER']}[/] "
|
|
274
|
+
f"({embed['EMBEDDING_MODEL']}, {embed['EMBEDDING_DIMENSIONS']}d)"
|
|
275
|
+
)
|
|
276
|
+
if provider != "openai":
|
|
277
|
+
console.print(" [dim]Edit LLM_MODEL in .env if you want a different model.[/]")
|
|
278
|
+
|
|
279
|
+
return {
|
|
280
|
+
"LLM_PROVIDER": provider,
|
|
281
|
+
"LLM_MODEL": model,
|
|
282
|
+
"LLM_API_KEY": llm_api_key,
|
|
283
|
+
"LLM_BASE_URL": llm_base_url,
|
|
284
|
+
**embed,
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _embed_openai(api_key: str) -> dict[str, str]:
|
|
289
|
+
return {
|
|
290
|
+
"EMBEDDING_PROVIDER": "openai",
|
|
291
|
+
"EMBEDDING_MODEL": _EMBED_OPENAI["model"],
|
|
292
|
+
"EMBEDDING_API_KEY": api_key,
|
|
293
|
+
"EMBEDDING_BASE_URL": "",
|
|
294
|
+
"EMBEDDING_DIMENSIONS": _EMBED_OPENAI["dims"],
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _embed_ollama(base_url: str) -> dict[str, str]:
|
|
299
|
+
return {
|
|
300
|
+
"EMBEDDING_PROVIDER": "ollama",
|
|
301
|
+
"EMBEDDING_MODEL": _EMBED_OLLAMA["model"],
|
|
302
|
+
"EMBEDDING_API_KEY": "",
|
|
303
|
+
"EMBEDDING_BASE_URL": base_url,
|
|
304
|
+
"EMBEDDING_DIMENSIONS": _EMBED_OLLAMA["dims"],
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _configure_embeddings_for_anthropic() -> dict[str, str]:
|
|
309
|
+
console.print(
|
|
310
|
+
" [dim]Anthropic has no embedding API — choose a separate embedding "
|
|
311
|
+
"provider.[/]"
|
|
312
|
+
)
|
|
313
|
+
choice = Prompt.ask(
|
|
314
|
+
" Embedding provider", choices=["openai", "ollama"], default="openai",
|
|
315
|
+
)
|
|
316
|
+
if choice == "openai":
|
|
317
|
+
key = _validate_openai_loop(
|
|
318
|
+
_prompt_api_key("OpenAI (for embeddings)", _OPENAI_KEY_URL)
|
|
319
|
+
)
|
|
320
|
+
return _embed_openai(key)
|
|
321
|
+
return _embed_ollama(_validate_ollama_loop(_prompt_base_url(default=_OLLAMA_DEFAULT_URL)))
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# --- validation loops -------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _validate_openai_loop(key: str) -> str:
|
|
328
|
+
console.print(" Validating key with OpenAI…")
|
|
329
|
+
result = llm_lib.validate_openai_key(key)
|
|
330
|
+
while not result.ok:
|
|
331
|
+
err_console.print(f" [red]✗[/] {result.detail}")
|
|
332
|
+
key = _prompt_api_key("OpenAI", _OPENAI_KEY_URL, retry=True)
|
|
333
|
+
console.print(" Validating key with OpenAI…")
|
|
334
|
+
result = llm_lib.validate_openai_key(key)
|
|
335
|
+
console.print(" [green]✓[/] OpenAI key works")
|
|
336
|
+
return key
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _validate_anthropic_loop(key: str) -> str:
|
|
340
|
+
result = llm_lib.validate_anthropic_key(key)
|
|
341
|
+
while not result.ok:
|
|
342
|
+
err_console.print(f" [red]✗[/] {result.detail}")
|
|
343
|
+
key = _prompt_api_key("Anthropic", _ANTHROPIC_KEY_URL, retry=True)
|
|
344
|
+
result = llm_lib.validate_anthropic_key(key)
|
|
345
|
+
console.print(" [green]✓[/] Anthropic key accepted")
|
|
346
|
+
return key
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _validate_ollama_loop(base_url: str) -> str:
|
|
350
|
+
console.print(f" Checking Ollama at {base_url}…")
|
|
351
|
+
result = llm_lib.validate_ollama_local(base_url)
|
|
352
|
+
while not result.ok:
|
|
353
|
+
err_console.print(f" [red]✗[/] {result.detail}")
|
|
354
|
+
base_url = _prompt_base_url(default=base_url, retry=True)
|
|
355
|
+
console.print(f" Checking Ollama at {base_url}…")
|
|
356
|
+
result = llm_lib.validate_ollama_local(base_url)
|
|
357
|
+
console.print(" [green]✓[/] Ollama reachable")
|
|
358
|
+
return base_url
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# --- prompts ----------------------------------------------------------------
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _prompt_provider_choice() -> str:
|
|
365
|
+
console.print(" [dim]Which LLM provider should SpAIder use?[/]")
|
|
366
|
+
return Prompt.ask(" Provider", choices=list(_PROVIDERS), default="openai")
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _prompt_api_key(label: str, url: str, *, retry: bool = False) -> str:
|
|
370
|
+
prefix = "Try again — your key wasn't accepted" if retry else "Get a key at"
|
|
371
|
+
console.print(f" [dim]{prefix} {'' if retry else url}[/]")
|
|
372
|
+
return Prompt.ask(f" {label} API key", password=True).strip()
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _prompt_base_url(*, default: str, retry: bool = False) -> str:
|
|
376
|
+
if retry:
|
|
377
|
+
console.print(" [dim]Make sure Ollama is running (`ollama serve`).[/]")
|
|
378
|
+
return Prompt.ask(" Ollama base URL", default=default).strip()
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _default_agent_name() -> str:
|
|
382
|
+
user = os.environ.get("USER") or os.environ.get("USERNAME") or "user"
|
|
383
|
+
return f"dev-{user}"
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _print_success_summary(*, agent_name: str, agent_key: str, mcp_done: bool) -> None:
|
|
387
|
+
body = (
|
|
388
|
+
f"\n[bold green]🎉 SpAIder is ready.[/]\n\n"
|
|
389
|
+
f" Studio : [link=http://localhost:3000]http://localhost:3000[/link]\n"
|
|
390
|
+
f" Agent : [bold]{agent_name}[/]\n"
|
|
391
|
+
f" API key : [bold yellow]{agent_key}[/]\n"
|
|
392
|
+
)
|
|
393
|
+
if mcp_done:
|
|
394
|
+
body += (
|
|
395
|
+
"\n [yellow]Restart Claude Code[/] so it picks up the new MCP server "
|
|
396
|
+
"and skill file.\n"
|
|
397
|
+
" After restart, ask Claude something like \"what do you remember about "
|
|
398
|
+
"this project?\" — it should reach for [bold]spaider.list_recent[/] automatically.\n"
|
|
399
|
+
)
|
|
400
|
+
else:
|
|
401
|
+
body += (
|
|
402
|
+
"\n [dim]Run [bold]spaider mcp install[/] when you're ready to wire "
|
|
403
|
+
"SpAIder into Claude Code.[/]\n"
|
|
404
|
+
)
|
|
405
|
+
console.print(body)
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""``spaider mcp install`` — write SpAIder into MCP client configs.
|
|
2
|
+
|
|
3
|
+
Two things land for the chosen client:
|
|
4
|
+
|
|
5
|
+
1. The MCP server entry (URL + Authorization Bearer header).
|
|
6
|
+
2. The skill file — the agent-side usage protocol that converts "MCP server
|
|
7
|
+
present" into "LLM reflexively reaches for SpAIder when context warrants".
|
|
8
|
+
|
|
9
|
+
The skill is the higher-leverage half: without it Claude Code sees the
|
|
10
|
+
``spaider.*`` tools as just-another-tool and rarely invokes them. The skill
|
|
11
|
+
file teaches the LLM when to call each tool, the feedback protocol, and the
|
|
12
|
+
failure-mode etiquette.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import typer
|
|
19
|
+
from rich.console import Console
|
|
20
|
+
|
|
21
|
+
from spaider_cli.lib import api as api_client
|
|
22
|
+
from spaider_cli.lib import mcp as mcp_lib
|
|
23
|
+
|
|
24
|
+
app = typer.Typer(no_args_is_help=True)
|
|
25
|
+
console = Console()
|
|
26
|
+
err_console = Console(stderr=True)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
DEFAULT_MCP_URL = "http://localhost:8000/api/v1/mcp/sse"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@app.command("install")
|
|
33
|
+
def install(
|
|
34
|
+
agent: str | None = typer.Option(
|
|
35
|
+
None,
|
|
36
|
+
"--agent",
|
|
37
|
+
help=(
|
|
38
|
+
"Agent name to use for the MCP credential. Looked up via the API; "
|
|
39
|
+
"if not found, the command prompts to create it. "
|
|
40
|
+
"Defaults to dev-$USER."
|
|
41
|
+
),
|
|
42
|
+
),
|
|
43
|
+
api_key: str | None = typer.Option(
|
|
44
|
+
None,
|
|
45
|
+
"--api-key",
|
|
46
|
+
help=(
|
|
47
|
+
"Bearer token to embed in the MCP config. If omitted, the CLI "
|
|
48
|
+
"rotates the agent's key (or creates the agent + new key) so a "
|
|
49
|
+
"valid credential is always written. Pass an existing key to skip rotation."
|
|
50
|
+
),
|
|
51
|
+
),
|
|
52
|
+
url: str = typer.Option(
|
|
53
|
+
DEFAULT_MCP_URL,
|
|
54
|
+
"--url",
|
|
55
|
+
help="MCP server URL. Override if you run the standalone MCP host on :8001.",
|
|
56
|
+
),
|
|
57
|
+
client: str = typer.Option(
|
|
58
|
+
"claude-code",
|
|
59
|
+
"--for",
|
|
60
|
+
help="Which MCP client to install for: claude-code (default) or cursor.",
|
|
61
|
+
),
|
|
62
|
+
scope: str = typer.Option(
|
|
63
|
+
"user",
|
|
64
|
+
"--scope",
|
|
65
|
+
help=(
|
|
66
|
+
"claude-code only. user = global ~/.claude (default; same agent "
|
|
67
|
+
"memory in every repo). project = write ./.mcp.json so THIS repo "
|
|
68
|
+
"uses its own agent memory, overriding the global one."
|
|
69
|
+
),
|
|
70
|
+
),
|
|
71
|
+
) -> None:
|
|
72
|
+
"""Install the SpAIder MCP server + skill into your AI coding tool's config.
|
|
73
|
+
|
|
74
|
+
Idempotent: re-running upgrades the skill, refreshes the credential, and
|
|
75
|
+
backs up any prior config. Non-destructive — other MCP servers in your
|
|
76
|
+
config are preserved.
|
|
77
|
+
"""
|
|
78
|
+
# Resolve the credential we'll embed.
|
|
79
|
+
resolved_key: str
|
|
80
|
+
resolved_agent: str
|
|
81
|
+
if api_key:
|
|
82
|
+
resolved_key = api_key
|
|
83
|
+
resolved_agent = agent or "unspecified"
|
|
84
|
+
else:
|
|
85
|
+
resolved_agent = agent or _default_agent_name()
|
|
86
|
+
try:
|
|
87
|
+
resolved_key = _ensure_agent_key(resolved_agent)
|
|
88
|
+
except api_client.SpaiderApiError as exc:
|
|
89
|
+
err_console.print(
|
|
90
|
+
f"[red]✗[/] could not resolve credentials for agent "
|
|
91
|
+
f"'{resolved_agent}': {exc}"
|
|
92
|
+
)
|
|
93
|
+
err_console.print(
|
|
94
|
+
" Pass [bold]--api-key sk-...[/] to skip the API lookup, "
|
|
95
|
+
"or start the SpAIder backend first (make dev)."
|
|
96
|
+
)
|
|
97
|
+
raise typer.Exit(code=1)
|
|
98
|
+
|
|
99
|
+
# Dispatch to the right client.
|
|
100
|
+
if client == "claude-code":
|
|
101
|
+
if scope not in ("user", "project"):
|
|
102
|
+
err_console.print(
|
|
103
|
+
f"[red]✗[/] unsupported --scope '{scope}'. Supported: user, project."
|
|
104
|
+
)
|
|
105
|
+
raise typer.Exit(code=2)
|
|
106
|
+
report = mcp_lib.install_for_claude_code(
|
|
107
|
+
url=url, api_key=resolved_key, scope=scope, project_root=Path.cwd(),
|
|
108
|
+
)
|
|
109
|
+
_report_claude_code(report=report, agent=resolved_agent, scope=scope)
|
|
110
|
+
elif client == "cursor":
|
|
111
|
+
report = mcp_lib.install_for_cursor(
|
|
112
|
+
project_root=Path.cwd(),
|
|
113
|
+
url=url,
|
|
114
|
+
api_key=resolved_key,
|
|
115
|
+
)
|
|
116
|
+
_report_cursor(report=report, agent=resolved_agent)
|
|
117
|
+
else:
|
|
118
|
+
err_console.print(
|
|
119
|
+
f"[red]✗[/] unsupported --for value '{client}'. "
|
|
120
|
+
"Supported: claude-code, cursor."
|
|
121
|
+
)
|
|
122
|
+
raise typer.Exit(code=2)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# ---------------------------------------------------------------------------
|
|
126
|
+
# Helpers
|
|
127
|
+
# ---------------------------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _default_agent_name() -> str:
|
|
131
|
+
"""Return ``dev-${USER}`` (falling back to ``dev-user`` on no $USER)."""
|
|
132
|
+
import os
|
|
133
|
+
user = os.environ.get("USER") or os.environ.get("USERNAME") or "user"
|
|
134
|
+
return f"dev-{user}"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _ensure_agent_key(name: str) -> str:
|
|
138
|
+
"""Find or create an agent named ``name`` and return a fresh API key.
|
|
139
|
+
|
|
140
|
+
- If the agent exists: rotate its key (matches setup_mcp_dev_agent.sh).
|
|
141
|
+
- If not: create it and return the just-issued key.
|
|
142
|
+
"""
|
|
143
|
+
existing = api_client.find_agent_by_name(name)
|
|
144
|
+
if existing is not None:
|
|
145
|
+
return api_client.rotate_key(existing.id)
|
|
146
|
+
created = api_client.create_agent(name)
|
|
147
|
+
if not created.api_key:
|
|
148
|
+
raise api_client.SpaiderApiError(
|
|
149
|
+
"create_agent returned no api_key — backend may be misconfigured."
|
|
150
|
+
)
|
|
151
|
+
return created.api_key
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _report_claude_code(
|
|
155
|
+
*, report: mcp_lib.InstallReport, agent: str, scope: str = "user",
|
|
156
|
+
) -> None:
|
|
157
|
+
console.print()
|
|
158
|
+
console.print("[bold green]✓[/] SpAIder MCP installed for Claude Code")
|
|
159
|
+
console.print(f" agent : [bold]{agent}[/]")
|
|
160
|
+
console.print(f" scope : [bold]{scope}[/]" + (
|
|
161
|
+
" [dim](this repo only)[/]" if scope == "project" else " [dim](global)[/]"
|
|
162
|
+
))
|
|
163
|
+
console.print(f" config : {report.config_path}")
|
|
164
|
+
if report.config_backup:
|
|
165
|
+
console.print(f" backup of : [dim]{report.config_backup}[/]")
|
|
166
|
+
if report.skill_path:
|
|
167
|
+
console.print(f" skill : {report.skill_path}")
|
|
168
|
+
if report.skill_backup:
|
|
169
|
+
console.print(f" backup of : [dim]{report.skill_backup}[/]")
|
|
170
|
+
if scope == "project":
|
|
171
|
+
console.print()
|
|
172
|
+
console.print(
|
|
173
|
+
"[yellow]![/] [bold].mcp.json[/] holds a secret Bearer token — add it "
|
|
174
|
+
"to this repo's [bold].gitignore[/] so it is never committed."
|
|
175
|
+
)
|
|
176
|
+
console.print()
|
|
177
|
+
console.print(
|
|
178
|
+
"[yellow]Restart Claude Code[/] so it picks up the new MCP server "
|
|
179
|
+
"and skill file."
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _report_cursor(*, report: mcp_lib.InstallReport, agent: str) -> None:
|
|
184
|
+
console.print()
|
|
185
|
+
console.print("[bold green]✓[/] SpAIder rules installed for Cursor")
|
|
186
|
+
console.print(f" agent : [bold]{agent}[/]")
|
|
187
|
+
console.print(f" rules : {report.config_path}")
|
|
188
|
+
if report.config_backup:
|
|
189
|
+
console.print(f" backup of : [dim]{report.config_backup}[/]")
|
|
190
|
+
console.print()
|
|
191
|
+
console.print(
|
|
192
|
+
"[yellow]Reload the Cursor window[/] so it picks up the updated .cursorrules."
|
|
193
|
+
)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Shared utilities for SpAIder CLI subcommands.
|
|
2
|
+
|
|
3
|
+
Will house in the v0.1.0 release:
|
|
4
|
+
|
|
5
|
+
- ``docker``: detect Docker daemon, start stack, wait for healthchecks.
|
|
6
|
+
- ``env``: read / write / merge .env files; generate secrets.
|
|
7
|
+
- ``api``: SpAIder REST client (agents, health).
|
|
8
|
+
- ``llm``: provider key validation via small test calls.
|
|
9
|
+
- ``mcp``: ``~/.claude/.mcp.json`` and skill-file management.
|
|
10
|
+
"""
|