# GDSFactory+ MCP Server

[![PyPI version](https://img.shields.io/pypi/v/gfp-mcp.svg)](https://pypi.org/project/gfp-mcp/)
[![Python versions](https://img.shields.io/pypi/pyversions/gfp-mcp.svg)](https://pypi.org/project/gfp-mcp/)
[![Tests](https://github.com/doplaydo/gfp-mcp/workflows/Tests/badge.svg)](https://github.com/doplaydo/gfp-mcp/actions)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Model Context Protocol (MCP) server for GDSFactory+ that exposes photonic IC design operations as tools for AI assistants like Claude Code and Claude Desktop.

## Overview

This project implements a standalone MCP server that bridges AI assistants with GDSFactory+ photonic IC design capabilities. The server acts as a lightweight proxy that exposes GDSFactory+ operations through standardized MCP tools while maintaining zero modifications to the existing FastAPI backend.

## Features

### Phase 1: Core Building Tools (Complete)

- **build_cell** - Build a single GDS cell by name
- **build_cells** - Build multiple GDS cells in batch
- **list_cells** - List all available photonic components
- **get_cell_info** - Get detailed component metadata
- **download_gds** - Download built GDS files
- **list_projects** - List all running GDSFactory+ server instances
- **get_project_info** - Get detailed information about a specific project

### Multi-Project Support

The MCP server integrates with the GDSFactory+ server registry to support working with multiple projects simultaneously. The registry is stored at `~/.gdsfactory/server-registry.json` and is automatically managed by GDSFactory+ servers.

#### How It Works

1. When you start a GDSFactory+ server with `gfp serve`, it registers itself in the shared registry
2. The MCP server reads from this registry to discover available projects
3. Tools accept an optional `project` parameter to route requests to specific servers
4. The MCP server automatically resolves project names to the correct port

#### Example Usage

```
User: "List all running GDSFactory+ projects"
Claude: [Uses list_projects tool to show all registered servers]

User: "Build the mzi component in the my_photonics_project"
Claude: [Uses build_cell tool with project="my_photonics_project"]
```

**Note**: The MCP has read-only access to the registry. Only GDSFactory+ servers can register/unregister themselves.

### Architecture

```
AI Assistant (Claude) <-> MCP Server (STDIO) <-> HTTP Client <-> FastAPI Server
```

**Key Benefits:**
- Universal MCP client compatibility via STDIO transport
- Zero modifications to existing FastAPI server
- Clean separation of concerns
- No database conflicts (only FastAPI touches SQLite)
- Scalable architecture ready for 20+ tools

## Installation

### From PyPI (Recommended)

Install the package from PyPI:

```bash
pip install gfp-mcp
```

Or with uv:

```bash
uv pip install gfp-mcp
```

### From Source (Development)

For development or if you want the latest unreleased changes:

```bash
git clone https://github.com/doplaydo/gfp-mcp.git
cd gfp-mcp
pip install -e ".[dev]"
```

### Prerequisites

- Python 3.10 or higher
- GDSFactory+ with FastAPI server running

### Verify Installation

```bash
gfp-mcp-serve --help
```

## Quick Start

### 1. Start the FastAPI Server

In one terminal:

```bash
gfp serve --port 8787
```

### 2. Configure Your AI Assistant

#### Claude Code

Add to `.claude/settings.json`:

```json
{
    "mcpServers": {
        "gdsfactoryplus": {
            "command": "gfp-mcp-serve",
            "args": [],
            "env": {
                "GFP_API_URL": "http://localhost:8787"
            }
        }
    }
}
```

Or use the command line:

```bash
claude mcp add gdsfactoryplus -- gfp-mcp-serve
```

#### Claude Desktop

Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS):

```json
{
    "mcpServers": {
        "gdsfactoryplus": {
            "command": "gfp-mcp-serve",
            "args": []
        }
    }
}
```

For Windows: `%APPDATA%\Claude\claude_desktop_config.json`

For Linux: `~/.config/Claude/claude_desktop_config.json`

### 3. Use the Tools

Ask your AI assistant to:

- "List all available photonic components"
- "Build the mzi component"
- "Show me details about the coupler component"
- "Build multiple components: mzi, coupler, and bend_euler"

## Environment Variables

Configure the MCP server using environment variables:

```bash
# FastAPI server URL (default: http://localhost:8787)
export GFP_API_URL="http://localhost:8787"

# Request timeout in seconds (default: 300)
export GFP_MCP_TIMEOUT=300

# Enable debug logging (default: false)
export GFP_MCP_DEBUG=true
```

## Project Structure

```
gfp-mcp/
├── mcp_standalone/          # MCP server implementation
│   ├── __init__.py         # Package exports
│   ├── config.py           # Configuration management
│   ├── client.py           # HTTP client for FastAPI
│   ├── registry.py         # Server registry (multi-project support)
│   ├── tools.py            # MCP tool definitions
│   ├── mappings.py         # Tool → Endpoint mappings
│   ├── server.py           # MCP server core
│   └── README.md           # Detailed documentation
├── tests/                  # Test suite
│   ├── test_mcp_tools.py
│   ├── test_mcp_mappings.py
│   ├── test_mcp_integration.py
│   └── test_registry.py
├── mcp_serve.py            # CLI entry point
├── MCP_QUICKSTART.md       # Quick start guide
├── MCP_IMPLEMENTATION_STATUS.md  # Implementation details
└── README.md               # This file
```

## Testing

Run the test suite:

```bash
# Run all MCP tests
pytest tests/test_mcp_*.py -v

# Run with coverage
pytest tests/test_mcp_*.py --cov=mcp_standalone --cov-report=term-missing

# Run specific test file
pytest tests/test_mcp_tools.py -v
```

All tests are passing (46/46 tests):
- Tool definitions: 15 tests
- Endpoint mappings: 13 tests
- Integration & client: 9 tests
- Registry integration: 9 tests

## Example Workflows

### Build and Verify a Component

```
User: "List all available photonic components"
Claude: [Uses list_cells tool]

User: "Build the mzi component"
Claude: [Uses build_cell tool with name="mzi"]

User: "Show me the details of the mzi component"
Claude: [Uses get_cell_info tool with name="mzi"]
```

### Batch Build Multiple Components

```
User: "Build the following components: mzi, coupler, and bend_euler"
Claude: [Uses build_cells tool with names=["mzi", "coupler", "bend_euler"]]
```

## Troubleshooting

### Error: "Connection refused to localhost:8787"

**Cause**: FastAPI server is not running

**Solution**: Start the FastAPI server:

```bash
gfp serve --port 8787
```

### Error: "MCP server not responding"

**Cause**: STDIO transport issue or MCP client misconfiguration

**Solution**:
1. Check Claude Code/Desktop logs with `claude --debug`
2. Restart the MCP server
3. Verify the configuration in settings.json

### Error: "Tool execution timeout"

**Cause**: Long-running operation exceeded timeout

**Solution**: Increase the timeout:

```bash
export GFP_MCP_TIMEOUT=600  # 10 minutes
gfp mcp-serve
```

## Roadmap

### Future Phases

- **Phase 2**: Verification tools (DRC, LVS)
- **Phase 3**: SPICE workflow tools
- **Phase 4**: Simulation & advanced tools
- **Phase 5**: Comprehensive testing & documentation

## Documentation

- [Quick Start Guide](MCP_QUICKSTART.md) - Step-by-step setup instructions
- [Implementation Status](MCP_IMPLEMENTATION_STATUS.md) - Detailed implementation notes
- [MCP Standalone README](mcp_standalone/README.md) - Architecture details
- [Contributing Guide](CONTRIBUTING.md) - Development and release guidelines
- [Changelog](CHANGELOG.md) - Version history and release notes

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines on:

- Development setup
- Running tests and code quality checks
- Making changes and submitting PRs
- Release process (for maintainers)

Quick checklist:

1. All tests pass: `pytest tests/test_mcp_*.py -v`
2. Code quality: `ruff check . && ruff format --check .`
3. Documentation is updated
4. Changes are backward compatible

## License

See the main GDSFactory+ project for license information.

## Support

For issues or questions:

1. Check the [Quick Start Guide](MCP_QUICKSTART.md) troubleshooting section
2. Review the [Implementation Status](MCP_IMPLEMENTATION_STATUS.md) document
3. Enable debug mode with `GFP_MCP_DEBUG=true` and check server logs
4. Open an issue on GitHub

## Acknowledgments

Built on the Model Context Protocol by Anthropic, enabling seamless AI assistant integration with photonic IC design workflows.
