demo_kiro_file_editing.py•10.6 kB
#!/usr/bin/env python3
"""Demonstration of file editing through Kiro MCP interface."""
import asyncio
import json
import sys
import os
from pathlib import Path
# Add src to Python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from file_system_mcp_server.config import Config
from file_system_mcp_server.safety import SafetyManager
from file_system_mcp_server.file_operations import FileOperationsManager
class KiroFileEditingDemo:
"""Demonstrate file editing capabilities for Kiro integration."""
def __init__(self):
"""Initialize the demo."""
current_dir = Path.cwd()
self.config = Config(
backup_directory=str(current_dir / ".kiro_file_backups"),
max_file_size=50 * 1024 * 1024, # 50MB
max_recursion_depth=8,
protected_paths=["/etc", "/usr", "/bin", "/System"],
enable_backups=True,
log_level="INFO"
)
self.safety_manager = SafetyManager(self.config)
self.file_ops = FileOperationsManager(self.config, self.safety_manager)
self.demo_dir = current_dir / "kiro_demo_files"
self.demo_dir.mkdir(exist_ok=True)
async def simulate_kiro_conversation(self):
"""Simulate a conversation with Kiro about file editing."""
print("🤖 Kiro File Editing Demonstration")
print("=" * 50)
print("This shows how you'll interact with files through Kiro chat\n")
# Scenario 1: Creating a new file
print("👤 User: 'Create a new file called my_notes.txt with some initial content'")
print("🤖 Kiro: I'll create that file for you...")
notes_file = self.demo_dir / "my_notes.txt"
initial_content = """# My Notes
## Ideas
- Build an AI assistant
- Learn about MCP servers
- Create automation scripts
## Tasks for Today
- [ ] Test file editing through Kiro
- [ ] Create project documentation
- [ ] Organize code files
## Random Thoughts
This file was created through Kiro's MCP interface!
"""
result = await self.file_ops.write_file(str(notes_file), initial_content)
if result.success:
print(f"✅ Created file: {notes_file.name} ({result.metadata.size} bytes)")
else:
print(f"❌ Failed: {result.error.message}")
# Scenario 2: Reading the file
print(f"\n👤 User: 'Read my_notes.txt and tell me what's in it'")
print("🤖 Kiro: Let me read that file for you...")
read_result = await self.file_ops.read_file(str(notes_file))
if read_result.success:
print(f"✅ File contents ({read_result.metadata.size} bytes):")
print("📄 " + "─" * 40)
print(read_result.content[:300] + "..." if len(read_result.content) > 300 else read_result.content)
print("📄 " + "─" * 40)
else:
print(f"❌ Failed: {read_result.error.message}")
# Scenario 3: Updating the file
print(f"\n👤 User: 'Add a new section about coding projects to my notes'")
print("🤖 Kiro: I'll add that section to your notes...")
updated_content = read_result.content + """
## Coding Projects
- File System MCP Server ✅
- Personal Task Manager
- Code Documentation Generator
- Automated Backup System
## Learning Goals
- Master MCP protocol
- Build useful AI tools
- Improve Python skills
"""
update_result = await self.file_ops.update_file(str(notes_file), updated_content)
if update_result.success:
print(f"✅ Updated file: {notes_file.name}")
print(f"💾 Backup created: {Path(update_result.backup_created).name}")
print(f"📊 New size: {update_result.metadata.size} bytes")
else:
print(f"❌ Failed: {update_result.error.message}")
# Scenario 4: Creating a code file
print(f"\n👤 User: 'Create a Python script called hello.py with a simple function'")
print("🤖 Kiro: I'll create a Python script for you...")
python_file = self.demo_dir / "hello.py"
python_content = '''#!/usr/bin/env python3
"""Simple hello world script created by Kiro."""
def greet(name="World"):
"""Greet someone with a friendly message."""
return f"Hello, {name}! This was created through Kiro's MCP interface."
def main():
"""Main function."""
print(greet())
print(greet("Kiro User"))
# Add more functionality here
print("\\nFile operations available:")
print("- Read files")
print("- Write files")
print("- Update files")
print("- List directories")
print("- Get file info")
if __name__ == "__main__":
main()
'''
py_result = await self.file_ops.write_file(str(python_file), python_content)
if py_result.success:
print(f"✅ Created Python script: {python_file.name}")
print(f"📊 Size: {py_result.metadata.size} bytes")
else:
print(f"❌ Failed: {py_result.error.message}")
# Scenario 5: Listing files
print(f"\n👤 User: 'List all files in the demo directory'")
print("🤖 Kiro: Here are the files in your demo directory...")
list_result = await self.file_ops.list_directory(str(self.demo_dir))
if list_result.success:
print(f"✅ Found {len(list_result.entries)} files:")
for entry in list_result.entries:
icon = "📁" if entry.metadata.is_directory else "📄"
size = f"({entry.metadata.size} bytes)" if not entry.metadata.is_directory else ""
print(f" {icon} {entry.name} {size}")
else:
print(f"❌ Failed: {list_result.error.message}")
# Scenario 6: Getting file info
print(f"\n👤 User: 'Tell me details about the Python script'")
print("🤖 Kiro: Here's detailed information about your Python script...")
info_result = await self.file_ops.get_file_info(str(python_file))
if info_result.success and info_result.exists:
m = info_result.metadata
print(f"✅ File information for {python_file.name}:")
print(f" 📊 Size: {m.size:,} bytes")
print(f" 🏷️ Type: {m.mime_type}")
print(f" 🔐 Permissions: {m.permissions}")
print(f" 🕒 Modified: {m.modified_time}")
print(f" 📁 Is directory: {m.is_directory}")
else:
print(f"❌ Failed: {info_result.error.message if info_result.error else 'File not found'}")
# Scenario 7: Pattern matching
print(f"\n👤 User: 'Show me all Python files in this project'")
print("🤖 Kiro: I'll search for Python files...")
pattern_result = await self.file_ops.list_directory(str(Path.cwd()), pattern="*.py", recursive=True)
if pattern_result.success:
py_files = [entry for entry in pattern_result.entries if entry.name.endswith('.py')]
print(f"✅ Found {len(py_files)} Python files:")
for entry in py_files[:10]: # Show first 10
rel_path = Path(entry.path).relative_to(Path.cwd())
print(f" 🐍 {rel_path} ({entry.metadata.size} bytes)")
if len(py_files) > 10:
print(f" ... and {len(py_files) - 10} more Python files")
else:
print(f"❌ Failed: {pattern_result.error.message}")
async def show_mcp_tool_responses(self):
"""Show what MCP tool responses look like."""
print(f"\n🛠️ MCP Tool Response Examples")
print("=" * 40)
print("This is what Kiro receives from the MCP server:\n")
# Example tool call
notes_file = self.demo_dir / "my_notes.txt"
if notes_file.exists():
result = await self.file_ops.read_file(str(notes_file))
response_dict = result.to_dict()
print("📥 Tool Call: read_file")
print(f"📤 Response (JSON):")
print(json.dumps(response_dict, indent=2, default=str)[:500] + "...")
def show_kiro_setup_instructions(self):
"""Show step-by-step Kiro setup instructions."""
print(f"\n⚙️ Kiro Setup Instructions")
print("=" * 40)
print("1. **Install MCP dependencies:**")
print(" pip install mcp python-magic")
print(f"\n2. **Run the setup script:**")
print(" python3 setup_kiro_integration.py")
print(f"\n3. **Restart Kiro** to load the MCP server")
print(f"\n4. **Verify in Kiro:**")
print(" - Open Kiro's MCP panel")
print(" - Look for 'file-system-operations' server")
print(" - Should show as 'Connected' and 'Enabled'")
print(f"\n5. **Test with chat commands:**")
commands = [
"List files in the current directory",
"Read the README.md file",
"Create a file called test.txt with hello world",
"Show me all Python files in this project"
]
for cmd in commands:
print(f" • '{cmd}'")
print(f"\n6. **Advanced usage:**")
advanced = [
"Add error handling to the Python script in src/",
"Update my todo list with a new task about MCP servers",
"Create a markdown file documenting this project",
"Find all configuration files and show their contents"
]
for cmd in advanced:
print(f" • '{cmd}'")
async def main():
"""Run the demonstration."""
demo = KiroFileEditingDemo()
try:
# Run the conversation simulation
await demo.simulate_kiro_conversation()
# Show MCP responses
await demo.show_mcp_tool_responses()
# Show setup instructions
demo.show_kiro_setup_instructions()
print(f"\n" + "=" * 50)
print("🎉 Demo Complete!")
print(f"\n📁 Demo files created in: {demo.demo_dir}")
print(f"💾 Backups stored in: {demo.config.backup_directory}")
print(f"\n🚀 Ready for Kiro Integration!")
print("Run 'python3 setup_kiro_integration.py' to set up Kiro")
except Exception as e:
print(f"\n❌ Demo failed: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
asyncio.run(main())