# BioSimulagent Python Client

Python MCP client library for reproducible research workflows in computational biology.

## Features

- **Async-first API** - Built on asyncio for high performance
- **Type-safe** - Comprehensive type hints and Pydantic validation
- **25 MCP Tools** - Literature, simulation, design, neural modeling
- **4 Workflows** - Ligand optimization, MD simulation, BBB prediction, drug discovery
- **Session Management** - Automatic subprocess lifecycle handling
- **Jupyter Integration** - Designed for research notebooks (coming in Week 2)

## Installation

```bash
pip install bio-simulagent-client
```

### Development Installation

```bash
cd bio_simulagent_client
pip install -e .
pip install -r requirements-dev.txt
```

## Quick Start

```python
from bio_simulagent_client import BioSimulagent

# Connect to backend
async with BioSimulagent.connect() as client:
    # Search literature
    results = await client.literature.search(
        query="EGFR inhibitor",
        max_results=10
    )

    for article in results.articles:
        print(f"{article.title} ({article.year})")

    # Run workflow
    result = await client.workflow.run(
        name="ligand_optimization",
        objective="Design high-affinity EGFR inhibitor",
        params={"target": "EGFR"}
    )
```

## API Reference

### Client Connection

```python
# Default backend path (backend.main)
client = await BioSimulagent.connect()

# Custom backend
client = await BioSimulagent.connect(
    backend_path="custom.backend",
    python_executable="/path/to/python",
    timeout=30
)

# Context manager (recommended)
async with BioSimulagent.connect() as client:
    # Use client
    pass
```

### Literature Tools

```python
# Search PubMed
results = await client.literature.search(
    query="EGFR inhibitor",
    max_results=10,
    date_from="2020-01-01",
    date_to="2024-12-31"
)

# Get article details
article = await client.literature.get_article(pmid="12345678")

# Get full text
full_text = await client.literature.get_full_text(pmid="12345678")

# Extract biomedical entities
entities = await client.literature.extract_entities(
    text="EGFR mutations in lung cancer"
)
```

### Simulation Tools

```python
# Preprocess structure
config = await client.simulation.preprocess(
    pdb_file="protein.pdb",
    ligand_smiles="CCO"
)

# Run MD simulation
result = await client.simulation.run(
    config=config,
    duration_ns=100,
    temperature=300
)

# Analyze trajectory
analysis = await client.simulation.analyze(
    trajectory_file=result.trajectory_file,
    topology_file=result.topology_file
)
```

### Design Tools

```python
# Predict protein structure
structure = await client.design.predict_structure(
    sequence="MKTAYIAKQRQISFVKSHFSRQ"
)

# Design ligand
ligand = await client.design.design_ligand(
    target_pocket="EGFR_binding_site",
    constraints={"mw_max": 500}
)

# Optimize molecule
optimized = await client.design.optimize(
    smiles="CCO",
    objectives=["binding_affinity", "drug_likeness"]
)
```

### Neural Tools

```python
# Predict BBB permeability
bbb = await client.neural.predict_bbb(smiles="CCO")

# Simulate neural circuit
circuit = await client.neural.simulate_circuit(
    circuit_type="hippocampus",
    stimulation_pattern="theta"
)

# Predict drug effect
effect = await client.neural.drug_effect(
    smiles="CCO",
    target_receptors=["NMDA", "GABA"]
)
```

### Workflows

```python
# Run workflow with progress tracking
def on_progress(step):
    print(f"Step: {step.name} - {step.status}")

result = await client.workflow.run(
    name="ligand_optimization",
    objective="Design EGFR inhibitor",
    params={"target": "EGFR"},
    on_progress=on_progress,
    poll_interval=2.0
)

# Check workflow status
status = await client.workflow.status(workflow_id=result.workflow_id)

# Cancel workflow
await client.workflow.cancel(workflow_id=result.workflow_id)

# List available workflows
workflows = await client.workflow.list_available()
```

## Error Handling

```python
from bio_simulagent_client.exceptions import (
    BioSimulagentError,
    ConnectionError,
    ToolExecutionError,
    ValidationError,
    TimeoutError,
)

try:
    async with BioSimulagent.connect() as client:
        results = await client.literature.search(query="test")
except ConnectionError as e:
    print(f"Failed to connect: {e}")
except ToolExecutionError as e:
    print(f"Tool failed: {e.tool_name} - {e.message}")
except ValidationError as e:
    print(f"Invalid input: {e}")
except TimeoutError as e:
    print(f"Request timeout: {e}")
```

## Testing

```bash
# Run unit tests
pytest tests/

# Run with coverage
pytest --cov=bio_simulagent_client --cov-report=html

# Run integration tests (requires running backend)
RUN_INTEGRATION_TESTS=1 pytest tests/test_integration.py
```

## Development

### Project Structure

```
bio_simulagent_client/
├── __init__.py              # Public API exports
├── client.py                # Main BioSimulagent class
├── exceptions.py            # Custom exceptions
├── types.py                 # Pydantic models
├── workflows.py             # WorkflowRunner
├── _internal/               # Internal modules
│   ├── subprocess_manager.py
│   └── mcp_protocol.py
├── tools/                   # Tool wrappers
│   ├── __init__.py
│   ├── literature.py
│   ├── simulation.py
│   ├── design.py
│   └── neural.py
└── tests/                   # Test suite
    ├── conftest.py
    ├── test_client.py
    ├── test_literature.py
    ├── test_workflows.py
    └── test_integration.py
```

### Code Quality

```bash
# Format code
black bio_simulagent_client/
isort bio_simulagent_client/

# Type checking
mypy bio_simulagent_client/

# Linting
ruff check bio_simulagent_client/
```

## Requirements

- Python 3.11+
- asyncio
- pydantic >=2.0
- mcp >=0.9.0

## Roadmap

### Week 1 (Completed)
- ✅ Core client library
- ✅ 25 MCP tool wrappers
- ✅ Workflow execution
- ✅ Unit tests (80% coverage)

### Week 2 (Completed)
- ✅ Jupyter magic commands
- ✅ Visualization helpers
- ✅ 5 basic example notebooks
- ✅ Documentation structure

### Week 3 (Completed) - v0.3.0
- ✅ 3 advanced example notebooks (drug discovery, trajectory analysis, production tips)
- ✅ Integration test suite (4 complete workflows)
- ✅ Performance benchmarking infrastructure
- ✅ Sphinx documentation with ReadTheDocs
- ✅ CI/CD pipeline (testing, docs, PyPI)
- ✅ Production-ready package structure

## License

MIT License - See LICENSE file for details

## Contributing

Contributions welcome! Please see CONTRIBUTING.md for guidelines.

## Support

- Documentation: https://bio-simulagent.readthedocs.io
- Issues: https://github.com/your-org/bio-simulagent/issues
- Email: support@bio-simulagent.org
