nia-mcp-server 1.0.5__py3-none-any.whl → 1.0.7__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.

Potentially problematic release.


This version of nia-mcp-server might be problematic. Click here for more details.

@@ -0,0 +1,193 @@
1
+ """
2
+ Nia Project Initialization Module
3
+ Handles creation of Nia-enabled project structures and configurations
4
+ """
5
+ import os
6
+ import json
7
+ import shutil
8
+ import logging
9
+ import subprocess
10
+ from pathlib import Path
11
+ from datetime import datetime
12
+ from typing import List, Dict, Optional, Any
13
+ from .profiles import PROFILE_CONFIGS, get_profile_config
14
+ from .rule_transformer import transform_rules_for_profile
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ class NIAProjectInitializer:
19
+ """Handles Nia project initialization with support for multiple IDE profiles"""
20
+
21
+ def __init__(self, project_root: str):
22
+ self.project_root = Path(project_root).resolve()
23
+ self.assets_dir = Path(__file__).parent / "assets"
24
+ self.templates_dir = self.assets_dir / "templates"
25
+ self.rules_dir = self.assets_dir / "rules"
26
+
27
+ # Validate that required directories exist
28
+ if not self.assets_dir.exists():
29
+ raise RuntimeError(f"Assets directory not found at {self.assets_dir}. Nia MCP server may not be installed correctly.")
30
+ if not self.rules_dir.exists():
31
+ raise RuntimeError(f"Rules directory not found at {self.rules_dir}. Nia MCP server may not be installed correctly.")
32
+
33
+ def initialize_project(
34
+ self,
35
+ profiles: List[str] = ["cursor"]
36
+ ) -> Dict[str, Any]:
37
+ """
38
+ Initialize a Nia project with specified profiles
39
+
40
+ Args:
41
+ profiles: List of IDE profiles to set up (cursor, vscode, claude, etc.)
42
+
43
+ Returns:
44
+ Dictionary with initialization results and status
45
+ """
46
+ try:
47
+ results = {
48
+ "success": True,
49
+ "project_root": str(self.project_root),
50
+ "profiles_initialized": [],
51
+ "files_created": [],
52
+ "warnings": [],
53
+ "next_steps": []
54
+ }
55
+
56
+ # Validate project root
57
+ if not self.project_root.exists():
58
+ os.makedirs(self.project_root, exist_ok=True)
59
+
60
+ # No longer creating .nia directory or config files
61
+
62
+ # Process each profile
63
+ for profile in profiles:
64
+ if profile not in PROFILE_CONFIGS:
65
+ results["warnings"].append(f"Unknown profile: {profile}")
66
+ continue
67
+
68
+ profile_results = self._initialize_profile(profile)
69
+ if profile_results["success"]:
70
+ results["profiles_initialized"].append(profile)
71
+ results["files_created"].extend(profile_results["files_created"])
72
+ else:
73
+ results["warnings"].append(f"Failed to initialize {profile}: {profile_results.get('error')}")
74
+
75
+ # Generate next steps
76
+ results["next_steps"].extend(self._generate_next_steps(profiles))
77
+
78
+ logger.info(f"Successfully initialized Nia project at {self.project_root}")
79
+ return results
80
+
81
+ except Exception as e:
82
+ logger.error(f"Failed to initialize project: {e}")
83
+ return {
84
+ "success": False,
85
+ "error": str(e),
86
+ "project_root": str(self.project_root)
87
+ }
88
+
89
+ def _create_nia_directories(self):
90
+ """Create the .nia directory structure"""
91
+ # Simplified - no unnecessary directories or files
92
+ pass
93
+
94
+
95
+
96
+
97
+ def _initialize_profile(self, profile: str) -> Dict[str, Any]:
98
+ """Initialize a specific IDE profile"""
99
+ try:
100
+ profile_config = get_profile_config(profile)
101
+ if not profile_config:
102
+ return {"success": False, "error": "Profile configuration not found"}
103
+
104
+ files_created = []
105
+
106
+ # Create profile directory
107
+ profile_dir = self.project_root / profile_config["target_dir"]
108
+ os.makedirs(profile_dir, exist_ok=True)
109
+
110
+ # Transform and copy rules
111
+ rule_files = transform_rules_for_profile(
112
+ profile,
113
+ self.rules_dir,
114
+ profile_dir,
115
+ self.project_root
116
+ )
117
+
118
+ for rule_file in rule_files:
119
+ files_created.append(str(Path(rule_file).relative_to(self.project_root)))
120
+
121
+ # Handle profile-specific setup
122
+ if profile == "vscode" and profile_config.get("additional_files"):
123
+ # VSCode gets tasks.json and snippets from additional_files
124
+ pass # Handled by transform_rules_for_profile
125
+ # No need to setup MCP config - user is already running through MCP!
126
+
127
+ return {
128
+ "success": True,
129
+ "files_created": files_created
130
+ }
131
+
132
+ except Exception as e:
133
+ logger.error(f"Failed to initialize profile {profile}: {e}")
134
+ return {"success": False, "error": str(e)}
135
+
136
+
137
+
138
+ def _generate_next_steps(self, profiles: List[str]) -> List[str]:
139
+ """Generate helpful next steps for the user"""
140
+ steps = []
141
+
142
+ # Check for current git repository
143
+ if (self.project_root / ".git").exists():
144
+ try:
145
+ # Use subprocess for safer command execution
146
+ result = subprocess.run(
147
+ ["git", "remote", "get-url", "origin"],
148
+ cwd=self.project_root,
149
+ capture_output=True,
150
+ text=True,
151
+ check=False # Don't raise exception if git command fails
152
+ )
153
+ git_remote = result.stdout.strip()
154
+ if git_remote and "github.com" in git_remote:
155
+ steps.append(f"Index this repository: index_repository {git_remote}")
156
+ except (subprocess.SubprocessError, FileNotFoundError):
157
+ # Git might not be installed or available
158
+ logger.debug("Could not get git remote URL")
159
+
160
+ # Profile-specific steps
161
+ if "cursor" in profiles:
162
+ steps.append("Restart Cursor to load Nia MCP server")
163
+ if "vscode" in profiles:
164
+ steps.append("Reload VSCode window to apply settings")
165
+
166
+ # General steps
167
+ steps.extend([
168
+ "Explore available commands with list_repositories",
169
+ "Search for code patterns with search_codebase",
170
+ "Find new libraries with nia_web_search"
171
+ ])
172
+
173
+ return steps
174
+
175
+
176
+ def initialize_nia_project(
177
+ project_root: str,
178
+ profiles: List[str] = ["cursor"]
179
+ ) -> Dict[str, Any]:
180
+ """
181
+ Convenience function to initialize a Nia project
182
+
183
+ Args:
184
+ project_root: Root directory of the project
185
+ profiles: List of IDE profiles to set up
186
+
187
+ Returns:
188
+ Dictionary with initialization results
189
+ """
190
+ initializer = NIAProjectInitializer(project_root)
191
+ return initializer.initialize_project(
192
+ profiles=profiles
193
+ )
@@ -0,0 +1,363 @@
1
+ """
2
+ Nia Rule Transformer
3
+ Handles transformation of rule files for different IDE profiles
4
+ """
5
+ import os
6
+ import re
7
+ import logging
8
+ from pathlib import Path
9
+ from typing import List, Dict, Any, Optional
10
+ from .profiles import get_profile_config, TEMPLATE_CONFIGS
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def transform_rules_for_profile(
16
+ profile: str,
17
+ source_dir: Path,
18
+ target_dir: Path,
19
+ project_root: Path
20
+ ) -> List[str]:
21
+ """
22
+ Transform rule files for a specific profile
23
+
24
+ Args:
25
+ profile: Profile name (cursor, vscode, etc.)
26
+ source_dir: Directory containing source rule files
27
+ target_dir: Directory to write transformed rules
28
+ project_root: Project root directory for context
29
+
30
+ Returns:
31
+ List of created file paths
32
+ """
33
+ profile_config = get_profile_config(profile)
34
+ if not profile_config:
35
+ raise ValueError(f"Unknown profile: {profile}")
36
+
37
+ created_files = []
38
+ file_map = profile_config.get("file_map", {})
39
+
40
+ # Process each file in the file map
41
+ for source_file, target_file in file_map.items():
42
+ source_path = source_dir / source_file
43
+
44
+ if not source_path.exists():
45
+ logger.warning(f"Source file not found: {source_path}")
46
+ continue
47
+
48
+ # Read source content
49
+ content = source_path.read_text()
50
+
51
+ # Apply transformations
52
+ transformed_content = apply_transformations(
53
+ content,
54
+ profile_config,
55
+ project_root
56
+ )
57
+
58
+ # Write to target
59
+ target_path = target_dir / target_file
60
+ os.makedirs(target_path.parent, exist_ok=True)
61
+ target_path.write_text(transformed_content)
62
+ created_files.append(str(target_path))
63
+
64
+ logger.info(f"Created rule file: {target_path}")
65
+
66
+ # Handle additional files (like VSCode tasks.json)
67
+ additional_files = profile_config.get("additional_files", {})
68
+ for filename, template_key in additional_files.items():
69
+ if template_key in TEMPLATE_CONFIGS:
70
+ template_config = TEMPLATE_CONFIGS[template_key]
71
+ target_path = target_dir / filename
72
+
73
+ # Apply any necessary transformations to template
74
+ content = template_config["content"]
75
+ content = apply_template_variables(content, project_root)
76
+
77
+ target_path.write_text(content)
78
+ created_files.append(str(target_path))
79
+ logger.info(f"Created additional file: {target_path}")
80
+
81
+ return created_files
82
+
83
+
84
+ def apply_transformations(
85
+ content: str,
86
+ profile_config: Dict[str, Any],
87
+ project_root: Path
88
+ ) -> str:
89
+ """
90
+ Apply profile-specific transformations to content
91
+
92
+ Args:
93
+ content: Original content
94
+ profile_config: Profile configuration
95
+ project_root: Project root for context
96
+
97
+ Returns:
98
+ Transformed content
99
+ """
100
+ # Apply global replacements
101
+ global_replacements = profile_config.get("global_replacements", {})
102
+ for pattern, replacement in global_replacements.items():
103
+ content = content.replace(pattern, replacement)
104
+
105
+ # Apply project-specific variables
106
+ content = apply_template_variables(content, project_root)
107
+
108
+ # Apply format-specific transformations
109
+ if profile_config.get("format") == "markdown":
110
+ content = transform_markdown_format(content, profile_config)
111
+ elif profile_config.get("format") == "mdc":
112
+ content = transform_to_mdc_format(content, profile_config)
113
+
114
+ # Apply feature-specific enhancements
115
+ features = profile_config.get("features", [])
116
+ content = enhance_for_features(content, features, profile_config)
117
+
118
+ return content
119
+
120
+
121
+ def apply_template_variables(content: str, project_root: Path) -> str:
122
+ """
123
+ Replace template variables with actual values
124
+
125
+ Args:
126
+ content: Content with template variables
127
+ project_root: Project root directory
128
+
129
+ Returns:
130
+ Content with variables replaced
131
+ """
132
+ variables = {
133
+ "{{PROJECT_ROOT}}": str(project_root),
134
+ "{{PROJECT_NAME}}": project_root.name,
135
+ "{{WORKSPACE_FOLDER}}": "${workspaceFolder}",
136
+ "{{USER_HOME}}": str(Path.home()),
137
+ }
138
+
139
+ for var, value in variables.items():
140
+ content = content.replace(var, value)
141
+
142
+ return content
143
+
144
+
145
+ def transform_markdown_format(content: str, profile_config: Dict[str, Any]) -> str:
146
+ """
147
+ Apply markdown-specific transformations
148
+
149
+ Args:
150
+ content: Markdown content
151
+ profile_config: Profile configuration
152
+
153
+ Returns:
154
+ Transformed markdown
155
+ """
156
+ # Add profile-specific header if not present
157
+ profile_name = profile_config.get("name", "Unknown")
158
+ if not content.startswith(f"# Nia Integration for {profile_name}"):
159
+ # Check if it starts with a generic Nia header
160
+ if content.startswith("# Nia"):
161
+ # Replace the first line
162
+ lines = content.split('\n')
163
+ lines[0] = f"# Nia Integration for {profile_name}"
164
+ content = '\n'.join(lines)
165
+
166
+ # Enhance code blocks with profile-specific annotations
167
+ if "mcp" in profile_config.get("features", []):
168
+ content = enhance_mcp_code_blocks(content)
169
+
170
+ return content
171
+
172
+
173
+ def transform_to_mdc_format(content: str, profile_config: Dict[str, Any]) -> str:
174
+ """
175
+ Transform markdown content to MDC format for Cursor
176
+
177
+ Args:
178
+ content: Original markdown content
179
+ profile_config: Profile configuration
180
+
181
+ Returns:
182
+ MDC formatted content
183
+ """
184
+ # Extract the first line as description
185
+ lines = content.split('\n')
186
+ description = ""
187
+ content_start = 0
188
+
189
+ if lines and lines[0].startswith('#'):
190
+ # Use the first header as description
191
+ description = lines[0].replace('#', '').strip()
192
+ content_start = 1
193
+ else:
194
+ description = "Nia Knowledge Agent Integration Rules"
195
+
196
+ # Build MDC header
197
+ # For Nia rules, we want them always applied since they guide AI assistant behavior
198
+ mdc_header = f"""---
199
+ description: {description}
200
+ alwaysApply: true
201
+ ---
202
+ """
203
+
204
+ # Get the rest of the content
205
+ remaining_content = '\n'.join(lines[content_start:]).strip()
206
+
207
+ # Apply markdown transformations first
208
+ remaining_content = transform_markdown_format(remaining_content, profile_config)
209
+
210
+ return mdc_header + '\n' + remaining_content
211
+
212
+
213
+ def enhance_for_features(
214
+ content: str,
215
+ features: List[str],
216
+ profile_config: Dict[str, Any]
217
+ ) -> str:
218
+ """
219
+ Enhance content based on profile features
220
+
221
+ Args:
222
+ content: Original content
223
+ features: List of features supported by profile
224
+ profile_config: Profile configuration
225
+
226
+ Returns:
227
+ Enhanced content
228
+ """
229
+ # Add feature-specific sections if not present
230
+ enhancements = []
231
+
232
+ if "mcp" in features and "## MCP Integration" not in content:
233
+ enhancements.append(generate_mcp_section(profile_config))
234
+
235
+ if "composer" in features and "## Composer Usage" not in content:
236
+ enhancements.append(generate_composer_section())
237
+
238
+ if "tasks" in features and "## Task Automation" not in content:
239
+ enhancements.append(generate_tasks_section())
240
+
241
+ if "terminal_integration" in features and "## Terminal Commands" not in content:
242
+ enhancements.append(generate_terminal_section())
243
+
244
+ # Append enhancements to content
245
+ if enhancements:
246
+ content += "\n\n" + "\n\n".join(enhancements)
247
+
248
+ return content
249
+
250
+
251
+ def enhance_mcp_code_blocks(content: str) -> str:
252
+ """
253
+ Enhance code blocks for MCP-enabled profiles
254
+
255
+ Args:
256
+ content: Markdown content
257
+
258
+ Returns:
259
+ Enhanced content
260
+ """
261
+ # Pattern to find code blocks with Nia commands
262
+ pattern = r'```(\w*)\n(.*?nia.*?)\n```'
263
+
264
+ def replacer(match):
265
+ lang = match.group(1) or "bash"
266
+ code = match.group(2)
267
+
268
+ # If it's a NIA command, add annotation
269
+ if any(cmd in code for cmd in ["index_repository", "search_codebase", "list_repositories"]):
270
+ return f'```{lang}\n# MCP Command - Run this in your AI assistant\n{code}\n```'
271
+ return match.group(0)
272
+
273
+ return re.sub(pattern, replacer, content, flags=re.DOTALL)
274
+
275
+
276
+ def generate_mcp_section(profile_config: Dict[str, Any]) -> str:
277
+ """Generate MCP integration section"""
278
+ profile_name = profile_config.get("name", "IDE")
279
+ return f"""## MCP Integration
280
+
281
+ {profile_name} supports Nia through the Model Context Protocol (MCP). After initialization:
282
+
283
+ 1. **Restart {profile_name}** to load the Nia MCP server
284
+ 2. **Verify connection** by running: `list_repositories`
285
+ 3. **Set API key** in your environment or {profile_name} settings
286
+
287
+ The MCP server provides direct access to all Nia commands within your AI assistant."""
288
+
289
+
290
+ def generate_composer_section() -> str:
291
+ """Generate Composer-specific section"""
292
+ return """## Composer Usage
293
+
294
+ When using Cursor's Composer:
295
+
296
+ 1. **Start with context**: Always check indexed repositories first
297
+ 2. **Natural language**: Use complete questions, not keywords
298
+ 3. **Inline results**: Nia results appear directly in your code
299
+ 4. **Multi-file**: Reference multiple files from search results
300
+
301
+ Example:
302
+ ```
303
+ Composer: "How does authentication work in this Next.js app?"
304
+ [Nia searches indexed codebase and shows relevant files]
305
+ ```"""
306
+
307
+
308
+ def generate_tasks_section() -> str:
309
+ """Generate tasks automation section"""
310
+ return """## Task Automation
311
+
312
+ Quick tasks are configured in `.vscode/tasks.json`:
313
+
314
+ - **Ctrl+Shift+P** → "Tasks: Run Task"
315
+ - Select "Nia: Index Repository" or other Nia tasks
316
+ - Follow prompts for input
317
+
318
+ Custom keyboard shortcuts can be added in keybindings.json."""
319
+
320
+
321
+ def generate_terminal_section() -> str:
322
+ """Generate terminal integration section"""
323
+ return """## Terminal Commands
324
+
325
+ Quick aliases for your terminal:
326
+
327
+ ```bash
328
+ # Add to your shell profile (.bashrc, .zshrc, etc.)
329
+ alias nia-index='echo "index_repository"'
330
+ alias nia-search='echo "search_codebase"'
331
+ alias nia-list='echo "list_repositories"'
332
+ ```
333
+
334
+ Use these in the integrated terminal for quick access."""
335
+
336
+
337
+ def create_profile_specific_file(
338
+ profile: str,
339
+ filename: str,
340
+ content: str,
341
+ target_dir: Path
342
+ ) -> Optional[str]:
343
+ """
344
+ Create a profile-specific file
345
+
346
+ Args:
347
+ profile: Profile name
348
+ filename: Target filename
349
+ content: File content
350
+ target_dir: Target directory
351
+
352
+ Returns:
353
+ Created file path or None
354
+ """
355
+ try:
356
+ file_path = target_dir / filename
357
+ os.makedirs(file_path.parent, exist_ok=True)
358
+ file_path.write_text(content)
359
+ logger.info(f"Created {profile} file: {file_path}")
360
+ return str(file_path)
361
+ except Exception as e:
362
+ logger.error(f"Failed to create {filename} for {profile}: {e}")
363
+ return None