Metadata-Version: 2.4
Name: servicedock
Version: 0.1.1
Summary: Service Dock: scaffold APIs from OpenAPI, record/replay responses, and enforce runtime contracts & policies.
Author: Andrew Whitehouse
License: MIT
Project-URL: Homepage, https://github.com/WorldTreeInc/servicedock
Project-URL: Repository, https://github.com/WorldTreeInc/servicedock
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Internet :: WWW/HTTP
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: requests
Requires-Dist: python-dotenv
Requires-Dist: pyyaml
Requires-Dist: fastapi
Requires-Dist: uvicorn

# 🛡️ Service Dock

**Scaffold APIs from OpenAPI, record/replay responses, and enforce runtime contracts & policies.**

[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)

---

## 🎯 What is This?

Service Agent Stack validates API responses at runtime, enforces policies (PII protection, field filtering), and enables contract testing through recording/replay - all without code generation.

**Think of it as:** Runtime safety for APIs that OpenAPI CodeGen can't provide.

---

## ⚡ Quick Start

### Option A: Install from PyPI (recommended)

```bash
pip install servicedock

servicedock setup
```

Then follow the prompts: enter your **OpenAPI spec URL** (or path), choose an API name, optionally **record** GET endpoints, and generate a **FastAPI service shell**. Run with `uvicorn services.<name>_service:app --reload`; use `SERVICE_AGENT_MODE=replay` for local playback.

### Option B: From source (this repo)

```bash
pip install -r requirements.txt
python3 agentstack.py setup
```

Manual steps are still available:

1. **Scaffold** — `servicedock init --api dogapi` (or `--api myapi --url https://...`)
2. **Call & record** — `servicedock call breed.breed.images.random.get --breed husky`
3. **Test** — `PYTHONPATH=. python3 tests/test_contract_dog_api.py --mode replay`

---

## 📋 Workflow at a glance

| Step | What you do | Command |
|------|----------------|--------|
| **0** | **Guided flow** (spec → record → service) | `servicedock setup` |
| **1** | Clone/add an API from its OpenAPI spec | `servicedock init --api <name>` or `servicedock init --api <name> --url <spec_url>` |
| **2** | See endpoints | `ls scaffolds/` |
| **3** | Record live responses for replay | `servicedock call <endpoint> --param value ...` |
| **4** | Use in code | `agent.api("ApiName").get("<endpoint>", params)` with `@contract` |
| **5** | Run contract tests (replay = no network) | `PYTHONPATH=. python3 tests/test_contract_*.py --mode replay` |
| **6** | Run your service (live or replay) | `uvicorn ...` — set `SERVICE_AGENT_MODE=replay` to use recordings |

Full walkthrough: **[USER_WORKFLOW.md](USER_WORKFLOW.md)**.

---

## 🌟 Key Features

### ✅ **Runtime Contract Validation**
Ensure APIs actually return what you expect, not just type correctness.

```python
@contract({
    "expects": {
        "message": "must_be_non_empty_string",
        "status": "must_be_non_empty_string"
    }
})
def fetch_dog_image(breed: str):
    return agent.api("DogAPI").get("breed.breed.images.random.get", {"breed": breed})
```

### 🔒 **PII Protection**
Automatically detect and sanitize PII fields (GDPR compliance helper).

```python
@contract({
    "policy": {
        "no_PII": True,
        "sanitize_PII": True  # Redacts email, phone, etc.
    }
})
```

### 🎯 **Field Filtering**
Strip unnecessary fields before sending to clients.

```python
@contract({
    "only_allow": ["id", "name"]  # Filter everything else
})
```

### 📼 **Recording/Replay**
Record live API calls, replay in tests (deterministic, no network).

```bash
# Record
python3 agentstack.py call endpoint.name --param value

# Replay in tests
pytest --mode replay
```

### 🚀 **No Code Generation**
Point at OpenAPI spec and start validating immediately.

---

## 📖 Documentation

- **[User workflow (start here)](USER_WORKFLOW.md)** — Steps 1–n: clone an API, record, use in code, run tests
- **[Contract features & demos](CONTRACT_FEATURES.md)** — What `@contract` can do (expects, only_allow, prohibits, PII, mode) with runnable showcase
- **[Demo Walkthrough](DEMO_WALKTHROUGH.md)** - Full end-to-end example with Dog API
- **[Project Review](PROJECT_REVIEW.md)** - Architecture, capabilities, roadmap
- **[Examples](examples/)** - Sample implementations

---

## 🆚 vs OpenAPI CodeGen

| Feature | CodeGen | Service Agent Stack |
|---------|---------|---------------------|
| **Type Safety** | ✅ Static | ✅ Runtime |
| **Contract Testing** | ❌ | ✅ |
| **PII Protection** | ❌ | ✅ |
| **Recording/Replay** | ❌ | ✅ |
| **Policy Enforcement** | ❌ | ✅ |
| **Code Generation** | ✅ | ❌ (by design) |

**They're complementary!** Use CodeGen for development, Service Agent Stack for runtime safety.

---

## 🎬 Demo Example

See the complete Dog CEO API demo:

1. **OpenAPI Spec:** `service_agent/specs/dogapi.json`
2. **Scaffolds:** `scaffolds/breed.*.get.json`
3. **Recordings:** `recordings/breed.*.json`
4. **Contract Tests:** `tests/test_contract_dog_api.py`
5. **Service Example:** `services/dog_service.py`

```bash
# Run the full demo
cd /path/to/service-agent-stack

# Make live calls (records responses)
python3 agentstack.py call breeds.list.all.get
python3 agentstack.py call breed.breed.images.random.get --breed husky

# Run contract tests (no network, uses recordings)
PYTHONPATH=. python3 tests/test_contract_dog_api.py --mode replay

# Run the service
uvicorn services.dog_service:app --reload
curl http://localhost:8000/dogs/husky/random-image
```

---

## 🏗️ Architecture

```
service_agent/
├── agents/
│   ├── schema_agent.py      # OpenAPI spec parsing & scaffolding
│   ├── recording_agent.py   # Record API interactions
│   └── replay_agent.py      # Replay recordings
├── core.py                  # ServiceAgent & APIWrapper
├── decorators.py            # @contract decorator
├── contract_types.py        # Validators (must_be_number, etc.)
├── config.py                # API configurations
└── test_utils.py            # Test utilities

scaffolds/                   # Generated request templates
recordings/                  # Recorded API responses
tests/                       # Contract tests
services/                    # Example services
```

---

## 📋 Current Capabilities

✅ OpenAPI 2.0 & 3.x parsing  
✅ Automatic scaffolding  
✅ Contract validation  
✅ PII detection & sanitization  
✅ Field filtering (`only_allow`, `prohibits`)  
✅ Recording/Replay  
✅ Live/Replay mode switching  
✅ FastAPI integration  
✅ CLI tooling  

---

## 🚀 Roadmap

### Phase 1: Enhanced Validators
- Email, URL, phone validation
- Regex patterns
- Range validation (min/max)
- Enum validation
- Array validation (minItems, unique)

### Phase 2: Mock Server
- Generate mock server from OpenAPI spec
- Stateful mocks (CRUD operations)
- Scenario-based responses

### Phase 3: Advanced Policies
- GDPR compliance checks
- Rate limiting
- Audit logging
- Field-level encryption

### Phase 4: Developer Experience
- Web UI for contract management
- HTML test reports
- Interactive CLI
- Better error messages

---

## 🤝 Contributing

Contributions welcome! This project has huge potential:

- Contract testing
- API safety & compliance
- Policy enforcement
- Mock servers
- Observability

---

## 📄 License

[Your License Here]

---

## 🎓 Learn More

- **Why not just use OpenAPI CodeGen?** See [PROJECT_REVIEW.md](PROJECT_REVIEW.md)
- **Full walkthrough:** See [DEMO_WALKTHROUGH.md](DEMO_WALKTHROUGH.md)
- **Examples:** Check out `examples/` and `services/`

---

## 💡 Use Cases

✅ **Contract Testing** - Verify APIs meet expectations without full integration tests  
✅ **Third-Party APIs** - Validate APIs you don't control  
✅ **Compliance** - GDPR, HIPAA, PII protection  
✅ **Testing** - Deterministic tests with recording/replay  
✅ **Microservices** - Runtime validation between services  
✅ **API Gateways** - Validate before forwarding to clients  

---

**Built with ❤️ for API safety and testing**

