Metadata-Version: 2.4
Name: synapse-cli
Version: 0.1.3
Summary: MCP Server Generator CLI - Analyze codebases and generate production-ready MCP servers via gRPC backend
Author-email: Synapse Team <contact@synapse.dev>
Maintainer-email: Synapse Team <contact@synapse.dev>
License-Expression: MIT
Project-URL: Homepage, https://github.com/yourusername/synapse-cli
Project-URL: Documentation, https://github.com/yourusername/synapse-cli#readme
Project-URL: Repository, https://github.com/yourusername/synapse-cli
Project-URL: Bug Tracker, https://github.com/yourusername/synapse-cli/issues
Project-URL: Changelog, https://github.com/yourusername/synapse-cli/blob/main/CHANGELOG.md
Keywords: mcp,model-context-protocol,ai,llm,code-generation,cli,automation,grpc
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Code Generators
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Environment :: Console
Classifier: Natural Language :: English
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: click>=8.1.7
Requires-Dist: cryptography>=41.0.7
Requires-Dist: grpcio>=1.60.0
Requires-Dist: grpcio-tools>=1.60.0
Requires-Dist: protobuf>=4.25.0
Requires-Dist: mcp>=1.0.0
Requires-Dist: ast-grep-py>=0.8.0
Requires-Dist: qdrant-client>=1.16.0
Requires-Dist: fastembed>=0.7.0
Requires-Dist: tree-sitter>=0.21.0
Requires-Dist: tree-sitter-python>=0.21.0
Requires-Dist: jedi>=0.19.0
Requires-Dist: questionary>=2.0.0
Requires-Dist: prompt-toolkit>=3.0.0
Requires-Dist: rich>=13.0.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: typing-extensions>=4.9.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4.3; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: black>=23.12.1; extra == "dev"
Requires-Dist: flake8>=6.1.0; extra == "dev"
Requires-Dist: isort>=5.12.0; extra == "dev"
Requires-Dist: mypy>=1.7.1; extra == "dev"
Requires-Dist: pre-commit>=3.5.0; extra == "dev"
Requires-Dist: bandit>=1.7.5; extra == "dev"
Requires-Dist: pip-audit>=2.6.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Provides-Extra: test
Requires-Dist: pytest>=7.4.3; extra == "test"
Requires-Dist: pytest-cov>=4.1.0; extra == "test"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "test"
Requires-Dist: pytest-mock>=3.12.0; extra == "test"
Provides-Extra: docs
Requires-Dist: sphinx>=7.0.0; extra == "docs"
Requires-Dist: sphinx-rtd-theme>=1.3.0; extra == "docs"
Requires-Dist: sphinx-click>=5.0.0; extra == "docs"
Dynamic: license-file

# Synapse - Agentic MCP Server Generator

> **An intelligent CLI tool that analyzes any codebase and automatically generates production-ready MCP (Model Context Protocol) servers**

## Overview

Synapse enables seamless integration between AI assistants and existing codebases by automatically generating MCP servers. Simply point Synapse at your codebase, describe what you need, and it will create a fully functional MCP server with tools, resources, and proper error handling.

## Features

- 🚀 **Quick Setup**: Initialize with a single command
- 🤖 **Multi-Model Support**: Works with Claude, GPT-4, Groq, and Gemini
- 🔍 **Smart Analysis**: Automatically analyzes your codebase structure
- 🏗️ **Agentic Generation**: Uses CrewAI for intelligent MCP server generation
- 🔒 **Secure Configuration**: Encrypted API key storage
- ✅ **MCP Compliant**: Generates servers that follow MCP specifications

## System Architecture

The build process uses a two-agent flow: **Planner Agent** → **Generator Agent**, both powered by an intelligent codebase context search system.

```mermaid
flowchart TB
    subgraph Input
        UQ[User Query]
        CB[User's Codebase]
    end

    subgraph "Planner Agent"
        P1[Receive User Query]
        P2{Need More Context?}
        P3[Call Context Search Tool]
        P4[Analyze Search Results]
        P5[Extract Function Signatures]
        P6[Identify Relevant Code]
        P7[Create Markdown To-Do List]
        P8[Write to .synapse/todo_list.md]
    end

    subgraph "Codebase Context Search Tool"
        CS1[Parse Query Keywords]
        CS2[Grep Search Codebase]
        CS3[AST Parse Python Files]
        CS4[Extract Function Signatures]
        CS5[Follow Imports Recursively]
        CS6[Track Visited Files]
        CS7[Score Relevance]
        CS8[Return Structured Context]
    end

    subgraph "Generator Agent"
        G1[Read To-Do List Markdown]
        G2[Get Next Unchecked Task]
        G3{Task Available?}
        G4{Need Context?}
        G5[Call Context Search Tool]
        G6[Check Function Signatures]
        G7[Read Current MCP Server File]
        G8[Write/Update MCP Server Code]
        G9[Use insert_file / replace_file]
        G10[Check Off Task in Markdown]
        G11[MCP Server Complete]
    end

    subgraph "File Editing Tools"
        FE1[read_file_tool]
        FE2[insert_file_tool]
        FE3[replace_file_tool]
        FE4[write_file_tool]
    end

    subgraph Output
        TODO[".synapse/todo_list.md"]
        MCP["mcp_server.py"]
    end

    %% Input flows
    UQ --> P1
    CB --> CS2

    %% Planner flow
    P1 --> P2
    P2 -->|Yes| P3
    P3 --> CS1
    CS1 --> CS2
    CS2 --> CS3
    CS3 --> CS4
    CS4 --> CS5
    CS5 --> CS6
    CS6 --> CS7
    CS7 --> CS8
    CS8 --> P4
    P4 --> P5
    P5 --> P6
    P6 --> P2
    P2 -->|No, Enough Context| P7
    P7 --> P8
    P8 --> TODO

    %% Generator flow
    TODO --> G1
    G1 --> G2
    G2 --> G3
    G3 -->|Yes| G4
    G4 -->|Yes| G5
    G5 --> CS1
    CS8 --> G6
    G6 --> G7
    G4 -->|No| G7
    G7 --> FE1
    FE1 --> G8
    G8 --> G9
    G9 --> FE2
    G9 --> FE3
    FE2 --> G10
    FE3 --> G10
    G10 --> FE3
    G10 --> G2
    G3 -->|No, All Done| G11
    G11 --> MCP

    %% Styling
    style UQ fill:#e1f5fe
    style CB fill:#e1f5fe
    style TODO fill:#fff9c4
    style MCP fill:#c8e6c9
```

### Flow Description

#### Planner Agent (Iterative Context Gathering)
1. **Receives** user query describing MCP server requirements
2. **Iteratively searches** codebase using the context search tool:
   - Calls search multiple times to gather comprehensive context
   - Follows imports and references across files
   - Extracts exact function signatures and parameter patterns
3. **Creates** markdown to-do list with checkboxes at `.synapse/todo_list.md`
4. **Each task** includes: description, required files/functions, dependencies, expected output

#### Codebase Context Search Tool
- **Text-based search**: Uses grep patterns to find relevant code
- **AST parsing**: Extracts function signatures, classes, and methods
- **Import following**: Recursively follows import statements to gather related context
- **Relevance scoring**: Ranks results by relevance to the query
- **Returns**: Structured context with file paths, line numbers, and code snippets

#### Generator Agent (Sequential Task Execution)
1. **Reads** the markdown to-do list from the planner
2. **For each unchecked task** (sequentially):
   - Uses context search to verify function signatures and argument patterns
   - Reads current MCP server file (if exists)
   - Writes/updates MCP server code using file editing tools
   - **Uses only existing code** from user's codebase
   - **Follows exact positional argument patterns** from user's functions
   - Checks off completed task in markdown (`- [ ]` → `- [x]`)
3. **Continues** until all tasks are complete

### To-Do List Format

The planner creates a markdown file with this structure:

```markdown
# MCP Server Generation Tasks

- [ ] Task 1: Create MCP server boilerplate
  - Description: Initialize FastMCP server with imports and main execution
  - Expected Output: Basic server structure with FastMCP

- [ ] Task 2: Implement tool for function_name
  - Description: Create MCP tool that exposes function_name
  - Required Files: module/file.py
  - Function Signature: def function_name(param1: str, param2: int) -> dict
  - Dependencies: from module.file import function_name

- [x] Task 1: Create MCP server boilerplate  (checked when complete)
```

## Installation

### From PyPI (Recommended - Coming Soon)

```bash
pip install synapse-cli
```

### From Source

```bash
# Clone the repository
cd /path/to/synapse

# Install in development mode
pip install -e .

# Verify installation
synapse --version
```

### For Development

```bash
# Install with development dependencies
pip install -e ".[dev]"

# Or install from requirements.txt
pip install -r requirements.txt
```

## Quick Start

### 1. Initialize Synapse

```bash
# Navigate to your project directory
cd /path/to/your/project

# Initialize Synapse
synapse init
```

This will:
- Create a `.synapse` directory
- Prompt you to select an AI model (Claude, GPT-4, Groq, or Gemini)
- Securely store your API key
- Set up the configuration

### 2. Check Status

```bash
synapse status
```

## Commands

### `synapse init`

Initialize Synapse in the current directory.

```bash
synapse init          # Initialize with interactive prompts
synapse init --force  # Re-initialize if already exists
```

**What it does:**
- Creates `.synapse` configuration directory
- Configures AI model and API key
- Sets up encrypted configuration storage

**Example output:**
```
🚀 Synapse Initialization
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Select your AI model:
  1. Anthropic Claude
  2. Groq
  3. OpenAI
  4. Gemini

Your choice: 1

✓ Selected: Anthropic Claude
Enter your API key: ********************************
✓ Validating API key...
✓ Connection successful!
✓ Configuration saved securely

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎉 Welcome to Synapse!

Available Commands:
  synapse config       View or update configuration
  synapse analyze      Analyze your codebase structure
  synapse build        Generate MCP server from requirements

Get started: synapse analyze
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

### `synapse status`

Show current Synapse status and project information.

```bash
synapse status
```

**What it shows:**
- Initialization status
- Configuration status
- Analysis status
- Next steps

### `synapse config`

View or update configuration. API keys are shown as first 5 characters + `****`.

```bash
synapse config                    # View current config (project + global API key display)
synapse config --key <API_KEY>    # Set project API key (and global if not set)
synapse config --global --key <API_KEY>  # Set global API key only
```

### `synapse analyze`

Analyze codebase structure (Coming in Phase 2).

```bash
synapse analyze
synapse analyze --verbose
synapse analyze --output ./custom_output
```

### `synapse build`

Generate MCP server from requirements (Coming in Phase 2).

```bash
synapse build
synapse build --query "Create tools for database operations"
synapse build --output custom_server.py
```

## Project Structure

```
synapse/
├── cli.py                  # Main CLI entry point
├── pyproject.toml          # Modern Python package configuration (PEP 621)
├── setup.py                # Minimal setup for backward compatibility
├── MANIFEST.in             # Package file inclusion rules
├── commands/               # Command implementations
│   ├── init_command.py    # synapse init
│   ├── config_command.py  # synapse config (Phase 2)
│   ├── analyze_command.py # synapse analyze (Phase 2)
│   └── build_command.py   # synapse build (Phase 2)
├── utils/                  # Utility functions
│   ├── cli_utils.py       # CLI interaction helpers
│   ├── config_manager.py  # Configuration management
│   ├── call_llm.py        # LLM API integration
│   └── ...                # Other utilities
├── crews/                  # CrewAI crews (Phase 2+)
├── agents/                 # Agent definitions (Phase 2+)
├── tools/                  # Tool wrappers (Phase 2+)
├── nodes/                  # Node implementations (Phase 2+)
├── templates/              # MCP server templates (Phase 2+)
└── tests/                  # Test files
```

## Packaging

Synapse uses modern Python packaging standards:
- **`pyproject.toml`**: Main configuration file (PEP 621 compliant)
- **`setup.py`**: Minimal compatibility shim
- Ready for PyPI publishing

See [PUBLISHING.md](PUBLISHING.md) for detailed instructions on building and publishing to PyPI.

## Configuration

Synapse uses two config locations:

- **Global**: `~/.synapse/config.json` — shared across projects (API key stored encrypted).
- **Project**: `PROJECT_ROOT/.synapse/config.json` — per-project config and API key override.

**API key precedence** (for backend gRPC auth): `SYNAPSE_API_KEY` env > project API key > global API key.

**Set API key:**

```bash
synapse init                    # Prompts for API key if no global key; sets both project and global
synapse config --key <API_KEY>  # Set project key (and global if global not set)
synapse config --global --key <API_KEY>  # Set global key only
```

View config (API key shown as first 5 chars + `****`): `synapse config`.

Project directory layout:

```
.synapse/
├── config.json            # Encrypted API key + project config
├── project_schema.txt     # Generated by analyze
└── statistics.json        # Generated by analyze
```

### Testing API key ("Invalid or expired API key")

The backend validates keys against the **database** (and Redis cache). The key you set in the CLI must be a key that exists in the backend's `api_keys` table.

- **Production / UI flow:** Create an API key in the Synapse web app (Settings or API Keys). Copy the key (shown only once) and set it in the CLI: `synapse config --key <that_exact_key>`.
- **Local / dev testing:** Seed a test key into the same DB the gRPC backend uses, then use that key in the CLI:

  ```bash
  # From repo root; set DB_PASSWORD (and CLOUD_SQL_CONNECTION_NAME if using Cloud SQL)
  python infrastructure/seed_test_api_key.py
  # Copy the printed key, then:
  synapse config --key <printed_key>
  synapse build
  ```

- **Verify what the CLI is using:** Run `synapse config` and check the "API Key" line (first 5 chars + `****`). Ensure it matches the key you created (e.g. `syn-api-...` from the UI or seed script). If you set `SYNAPSE_API_KEY` in the environment, that overrides project/global config.

### Supported AI Models

| Model | Provider | API Key Format |
|-------|----------|----------------|
| Claude 3.5 Sonnet | Anthropic | `sk-ant-...` |
| Llama 3.3 70B | Groq | `gsk_...` |
| GPT-4 | OpenAI | `sk-...` |
| Gemini 1.5 Pro | Google | `AIza...` |

## Security

- API keys are encrypted using Fernet symmetric encryption
- Encryption keys are machine-specific
- Configuration files are stored locally in `.synapse/`
- Never commit `.synapse/` to version control

## Development Status

### ✅ Phase 1: CLI Tool & Init (Current)
- [x] Project structure
- [x] CLI framework with Click
- [x] Configuration management with encryption
- [x] `synapse init` command
- [x] `synapse status` command
- [x] Documentation

### 🚧 Phase 2: Config & Analysis (Next)
- [ ] `synapse config` command
- [ ] Codebase analyzer
- [ ] `synapse analyze` command
- [ ] Project schema generation

### 📋 Phase 3: MCP Generation
- [ ] CrewAI integration
- [ ] Agent definitions
- [ ] `synapse build` command
- [ ] MCP server templates
- [ ] Validation

## Requirements

- Python 3.9+
- API key for at least one supported AI model
- Internet connection for API calls

## Troubleshooting

### "Synapse not initialized"

Run `synapse init` in your project directory first.

### "Invalid API key"

Ensure your API key:
- Starts with the correct prefix for your chosen model
- Has no extra spaces or characters
- Is valid and active

### Re-initialization

Use `synapse init --force` to re-initialize if needed.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

MIT License - see LICENSE file for details

## Support

For issues, questions, or contributions, please visit:
- GitHub Issues: [https://github.com/yourusername/synapse-cli/issues](https://github.com/yourusername/synapse-cli/issues)
- Documentation: [https://github.com/yourusername/synapse-cli#readme](https://github.com/yourusername/synapse-cli#readme)

---

Built with ❤️ using CrewAI and the Model Context Protocol

