This repository was archived by the owner on Mar 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy path__init__.py
359 lines (291 loc) · 10.6 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import json
import re
import subprocess
import sys
from pathlib import Path
import click
import toml
from packaging.version import parse
MIN_UV_VERSION = "0.4.10"
class PyProject:
def __init__(self, path: Path):
self.data = toml.load(path)
@property
def name(self) -> str:
return self.data["project"]["name"]
@property
def first_binary(self) -> str | None:
scripts = self.data["project"].get("scripts", {})
return next(iter(scripts.keys()), None)
def check_uv_version(required_version: str) -> str | None:
"""Check if uv is installed and has minimum version"""
try:
result = subprocess.run(
["uv", "--version"], capture_output=True, text=True, check=True
)
version = result.stdout.strip()
match = re.match(r"uv (\d+\.\d+\.\d+)", version)
if match:
version_num = match.group(1)
if parse(version_num) >= parse(required_version):
return version
return None
except subprocess.CalledProcessError:
click.echo("❌ Error: Failed to check uv version.", err=True)
sys.exit(1)
except FileNotFoundError:
return None
def ensure_uv_installed() -> None:
"""Ensure uv is installed at minimum version"""
if check_uv_version(MIN_UV_VERSION) is None:
click.echo(
f"❌ Error: uv >= {MIN_UV_VERSION} is required but not installed.", err=True
)
click.echo("To install, visit: https://github.com/astral-sh/uv", err=True)
sys.exit(1)
def get_claude_config_path() -> Path | None:
"""Get the Claude config directory based on platform"""
if sys.platform == "win32":
path = Path(Path.home(), "AppData", "Roaming", "Claude")
elif sys.platform == "darwin":
path = Path(Path.home(), "Library", "Application Support", "Claude")
else:
return None
if path.exists():
return path
return None
def has_claude_app() -> bool:
return get_claude_config_path() is not None
def update_claude_config(project_name: str, project_path: Path) -> bool:
"""Add the project to the Claude config if possible"""
config_dir = get_claude_config_path()
if not config_dir:
return False
config_file = config_dir / "claude_desktop_config.json"
if not config_file.exists():
return False
try:
config = json.loads(config_file.read_text())
if "mcpServers" not in config:
config["mcpServers"] = {}
if project_name in config["mcpServers"]:
click.echo(
f"⚠️ Warning: {project_name} already exists in Claude.app configuration",
err=True,
)
click.echo(f"Settings file location: {config_file}", err=True)
return False
config["mcpServers"][project_name] = {
"command": "uv",
"args": ["--directory", str(project_path), "run", project_name],
}
config_file.write_text(json.dumps(config, indent=2))
click.echo(f"✅ Added {project_name} to Claude.app configuration")
click.echo(f"Settings file location: {config_file}")
return True
except Exception:
click.echo("❌ Failed to update Claude.app configuration", err=True)
click.echo(f"Settings file location: {config_file}", err=True)
return False
def get_package_directory(path: Path) -> Path:
"""Find the package directory under src/"""
src_dir = next((path / "src").glob("*/__init__.py"), None)
if src_dir is None:
click.echo("❌ Error: Could not find __init__.py in src directory", err=True)
sys.exit(1)
return src_dir.parent
def copy_template(
path: Path, name: str, description: str, version: str = "0.1.0", template_name: str = "blank"
) -> None:
"""Copy template files into src/<project_name>"""
template_dir = Path(__file__).parent / "template"
if template_name == "notes":
template_dir = template_dir / "notes"
target_dir = get_package_directory(path)
import jinja2
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader(str(template_dir)))
files = [
("__init__.py.jinja2", "__init__.py", target_dir),
("server.py.jinja2", "server.py", target_dir),
("README.md.jinja2", "README.md", path),
]
pyproject = PyProject(path / "pyproject.toml")
bin_name = pyproject.first_binary
template_vars = {
"binary_name": bin_name,
"server_name": name,
"server_version": version,
"server_description": description,
"server_directory": str(path.resolve()),
}
try:
for template_file, output_file, output_dir in files:
template: jinja2.Template = env.get_template(template_file)
rendered = template.render(**template_vars)
out_path = output_dir / output_file
out_path.write_text(rendered)
except Exception as e:
click.echo(f"❌ Error: Failed to template and write files: {e}", err=True)
sys.exit(1)
def create_project(
path: Path, name: str, description: str, version: str, use_claude: bool = True
) -> None:
"""Create a new project using uv"""
path.mkdir(parents=True, exist_ok=True)
try:
subprocess.run(
["uv", "init", "--name", name, "--package", "--app", "--quiet"],
cwd=path,
check=True,
)
except subprocess.CalledProcessError:
click.echo("❌ Error: Failed to initialize project.", err=True)
sys.exit(1)
# Add mcp dependency using uv add
try:
subprocess.run(["uv", "add", "mcp"], cwd=path, check=True)
except subprocess.CalledProcessError:
click.echo("❌ Error: Failed to add mcp dependency.", err=True)
sys.exit(1)
copy_template(path, name, description, version)
# Check if Claude.app is available
if (
use_claude
and has_claude_app()
and click.confirm(
"\nClaude.app detected. Would you like to install the server into Claude.app now?",
default=True,
)
):
update_claude_config(name, path)
relpath = path.relative_to(Path.cwd())
click.echo(f"✅ Created project {name} in {relpath}")
click.echo("ℹ️ To install dependencies run:")
click.echo(f" cd {relpath}")
click.echo(" uv sync --dev --all-extras")
def update_pyproject_settings(
project_path: Path, version: str, description: str
) -> None:
"""Update project version and description in pyproject.toml"""
import toml
pyproject_path = project_path / "pyproject.toml"
if not pyproject_path.exists():
click.echo("❌ Error: pyproject.toml not found", err=True)
sys.exit(1)
try:
pyproject = toml.load(pyproject_path)
if version is not None:
pyproject["project"]["version"] = version
if description is not None:
pyproject["project"]["description"] = description
pyproject_path.write_text(toml.dumps(pyproject))
except Exception as e:
click.echo(f"❌ Error updating pyproject.toml: {e}", err=True)
sys.exit(1)
def check_package_name(name: str) -> bool:
"""Check if the package name is valid according to pyproject.toml spec"""
if not name:
click.echo("❌ Project name cannot be empty", err=True)
return False
if " " in name:
click.echo("❌ Project name must not contain spaces", err=True)
return False
if not all(c.isascii() and (c.isalnum() or c in "_-.") for c in name):
click.echo(
"❌ Project name must consist of ASCII letters, digits, underscores, hyphens, and periods",
err=True,
)
return False
if name.startswith(("_", "-", ".")) or name.endswith(("_", "-", ".")):
click.echo(
"❌ Project name must not start or end with an underscore, hyphen, or period",
err=True,
)
return False
return True
@click.command()
@click.option(
"--path",
type=click.Path(path_type=Path),
help="Directory to create project in",
)
@click.option(
"--name",
type=str,
help="Project name",
)
@click.option(
"--version",
type=str,
help="Server version",
)
@click.option(
"--description",
type=str,
help="Project description",
)
@click.option(
"--template",
type=click.Choice(["blank", "notes"]),
default="blank",
help="Project template to use",
)
@click.option(
"--claudeapp/--no-claudeapp",
default=True,
help="Enable/disable Claude.app integration",
)
def main(
path: Path | None,
name: str | None,
version: str | None,
description: str | None,
template: str,
claudeapp: bool,
) -> int:
"""Create a new MCP server project"""
ensure_uv_installed()
click.echo("Creating a new MCP server project using uv.")
click.echo("This will set up a Python project with MCP dependency.")
click.echo("\nLet's begin!\n")
name = click.prompt("Project name (required)", type=str) if name is None else name
if name is None:
click.echo("❌ Error: Project name cannot be empty", err=True)
return 1
if not check_package_name(name):
return 1
description = (
click.prompt("Project description", type=str, default="A MCP server project")
if description is None
else description
)
assert isinstance(description, str)
# Validate version if not supplied on command line
if version is None:
version = click.prompt("Project version", default="0.1.0", type=str)
assert isinstance(version, str)
try:
parse(version) # Validate semver format
except Exception:
click.echo(
"❌ Error: Version must be a valid semantic version (e.g. 1.0.0)",
err=True,
)
return 1
project_path = (Path.cwd() / name) if path is None else path
# Ask the user if the path is correct if not specified on command line
if path is None:
click.echo(f"Project will be created at: {project_path}")
if not click.confirm("Is this correct?", default=True):
project_path = Path(
click.prompt("Enter the correct path", type=click.Path(path_type=Path))
)
if project_path is None:
click.echo("❌ Error: Invalid path. Project creation aborted.", err=True)
return 1
project_path = project_path.resolve()
create_project(project_path, name, description, version, claudeapp)
copy_template(project_path, name, description, version, template)
update_pyproject_settings(project_path, version, description)
return 0