Metadata-Version: 2.4
Name: devantis-sdk
Version: 0.1.0
Summary: Python SDK and MCP server for the Devantis AI development platform
Author-email: Encode IT <info@encodeit.ro>
License: MIT
Project-URL: Homepage, https://github.com/encode-it-srl/devantis
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.26.0
Requires-Dist: pydantic>=2.0
Requires-Dist: pyyaml>=6.0
Provides-Extra: mcp
Requires-Dist: mcp>=1.0.0; extra == "mcp"
Requires-Dist: websockets>=12.0; extra == "mcp"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: respx>=0.21; extra == "dev"

# Devantis SDK

Python SDK and MCP (Model Context Protocol) server for the **Devantis AI development platform**. Exposes 89 tools to Claude CLI, Claude Desktop, or any MCP-compatible client for managing tickets, requirements, source code, architecture, designs, chat sessions, knowledge graph, and more.

## Quick Start

```bash
# Install with MCP support
pip install devantis-sdk[mcp]

# Login to the platform (opens browser)
devantis login

# Set your default context
devantis config

# Run the MCP server
devantis-mcp
```

## Installation

### From PyPI

```bash
# Core SDK only
pip install devantis-sdk

# With MCP server + WebSocket chat support
pip install devantis-sdk[mcp]

# With development/test dependencies
pip install devantis-sdk[mcp,dev]
```

### From Source

```bash
git clone git@github.com:encode-it-srl/devantis.git
cd devantis/sources/sdk

make install       # Creates .venv + installs SDK with MCP deps
make install-dev   # Same + pytest, respx, etc.
```

## Configuration

### Authentication

The SDK shares authentication with the Devantis CLI. Login once and both tools use the same token:

```bash
devantis login
```

This opens your browser for Keycloak OAuth (PKCE flow) and saves the token to `~/.devantis_token.json`. The SDK auto-refreshes expired tokens using the refresh token.

**Auth modes** (auto-detected):

| Mode | When | Config |
|------|------|--------|
| **User token** | Local development, Claude CLI | `~/.devantis_token.json` (from `devantis login`) |
| **Internal key** | Inside Docker (executor, workers) | `INTERNAL_SERVICE_KEY` env var |
| **Service account** | Server-to-server | Keycloak client credentials |

### Tenant Context

The SDK needs to know which organisation/project/app to operate on:

**Option 1: CLI config** (shared with `devantis` CLI):
```bash
devantis config   # Interactive picker, saves to ~/.devantis.yaml
```

**Option 2: Environment variables:**
```bash
export DEVANTIS_ORG=my-org
export DEVANTIS_PROJECT=my-project
export DEVANTIS_APP=my-app
```

**Option 3: Programmatic:**
```python
client = await DevantisClient.connect(
    org="my-org", project="my-project", app="my-app"
)
```

### Service URLs

The SDK auto-detects how to reach backend services:

| Mode | When | How |
|------|------|-----|
| **Local** (default) | `make up` from `infrastructure/` | Each service on its own localhost port |
| **Docker** | `INTERNAL_SERVICE_KEY` is set | Docker-internal hostnames |
| **Gateway** | `DEVANTIS_API_URL` is set | Single URL with path-based routing |

**Local development** (services running in Docker Compose):
```bash
# No extra config needed. SDK uses correct host-mapped ports:
# ticket-service    → localhost:8076
# chat-service      → localhost:8090
# user-service      → localhost:8086
# etc.
```

**Production** (behind nginx ingress):
```bash
export DEVANTIS_API_URL=https://devantis.dev.encodeit.ro
# All 13 services routed through one domain with path prefixes
```

## Using as MCP Server with Claude CLI

### Register the Server

```bash
# From the SDK directory:
make claude-add

# Or manually:
claude mcp add devantis -- /path/to/sdk/.venv/bin/python -m devantis
```

### Verify

```bash
claude mcp list
# devantis: /path/to/.venv/bin/python -m devantis - Connected

claude mcp get devantis
```

### Use It

Start a new Claude CLI session. All 89 devantis tools are available:

```
> List my open tickets

> Search the codebase for "authentication"

> Create a ticket for implementing OAuth2

> Send a message to the AI assistant: analyze the project structure

> What does the brain know about our auth service?
```

### Chat Sessions

The MCP server auto-persists chat sessions. First `devantis_chat_send` creates a session; subsequent calls reuse it. Use `devantis_chat_session` for explicit control:

```
> Start a new chat session with the AI assistant

> Ask the assistant to create a hello world file

> Answer "Yes" to approve the file write
```

Switching context (`devantis_switch_context`) automatically clears the active chat session.

## Using as Python SDK

```python
import asyncio
from devantis import DevantisClient

async def main():
    client = await DevantisClient.connect()

    # Source code
    files = await client.source.list()
    content = await client.source.read("src/main.py")
    matches = await client.source.grep("def login", glob="*.py")

    # Tickets
    tickets = await client.tickets.list(status="open", priority="high")
    ticket = await client.tickets.create(
        title="Implement OAuth2",
        description="Add OAuth2 login flow...",
        feature="authentication",
    )

    # Chat with AI assistant
    result = await client.chat.send("How does the auth system work?")
    print(result["content"])

    # Knowledge graph
    entities = await client.knowledge_graph.search("auth")
    await client.knowledge_graph.create_entity(
        name="auth-service",
        entity_type="service",
        observations=[{"content": "Uses JWT with 15min expiry", "kind": "fact"}],
    )

    # Cross-entity search
    results = await client.search("authentication")

    await client.close()

asyncio.run(main())
```

## MCP Tools Reference

### Source Code (9 tools)

| Tool | Description |
|------|-------------|
| `devantis_read_file` | Read a source code file |
| `devantis_write_file` | Create or overwrite a file |
| `devantis_edit_file` | Targeted find-and-replace edit (fuzzy matching) |
| `devantis_delete_file` | Delete a file |
| `devantis_move_file` | Move or rename a file |
| `devantis_list_files` | List files, optionally by folder |
| `devantis_glob_files` | Find files by glob pattern |
| `devantis_grep` | Regex search inside file contents |
| `devantis_batch_files` | Write/delete/edit up to 20 files at once |

### Tickets (23 tools)

| Tool | Description |
|------|-------------|
| `devantis_list_tickets` | List with filters (status, priority, sprint, epic) |
| `devantis_get_ticket` | Full ticket details |
| `devantis_create_ticket` | Create a ticket |
| `devantis_update_ticket` | Update ticket fields |
| `devantis_delete_ticket` | Delete a ticket |
| `devantis_transition_ticket` | Move through workflow (start, review, done, block...) |
| `devantis_search_tickets` | Full-text search |
| `devantis_add_ticket_comment` | Add a comment |
| `devantis_list_ticket_comments` | List comments |
| `devantis_manage_labels` | Label CRUD + assign to tickets |
| `devantis_manage_subtasks` | Subtask CRUD |
| `devantis_manage_links` | Link tickets (blocks, duplicates, relates_to...) |
| `devantis_ticket_watch` | Watch/unwatch tickets |
| `devantis_ticket_vote` | Vote on tickets |
| `devantis_ticket_timelog` | Log time on tickets |
| `devantis_manage_milestones` | Milestone CRUD + assign tickets |
| `devantis_manage_components` | Component CRUD + assign tickets |
| `devantis_manage_filters` | Saved filter CRUD + execute |
| `devantis_get_board` | Kanban / by-assignee / by-feature / by-priority |
| `devantis_get_chart` | Burndown, burnup, cumulative flow, velocity |
| `devantis_ticket_stats` | Aggregate statistics |
| `devantis_manage_sprints` | Sprint lifecycle + ticket management |
| `devantis_manage_epics` | Epic CRUD + ticket management |

### Requirements (5 tools)

| Tool | Description |
|------|-------------|
| `devantis_list_requirements` | List with filters |
| `devantis_get_requirement` | Full requirement details |
| `devantis_create_requirement` | Create a requirement |
| `devantis_update_requirement` | Update fields |
| `devantis_delete_requirement` | Delete a requirement |

### Architecture (6 tools)

| Tool | Description |
|------|-------------|
| `devantis_list_architecture` | List documents and diagrams |
| `devantis_read_architecture` | Read document content |
| `devantis_create_architecture` | Create document or diagram |
| `devantis_update_architecture` | Update content |
| `devantis_delete_architecture` | Delete a document |
| `devantis_search_architecture` | Search by name |

### Designs (6 tools)

| Tool | Description |
|------|-------------|
| `devantis_list_designs` | List design files (HTML, CSS, tokens) |
| `devantis_read_design` | Read file content |
| `devantis_create_design` | Create a design file |
| `devantis_update_design` | Update content |
| `devantis_delete_design` | Delete a file |
| `devantis_search_designs` | Search designs |

### Chat / AI Assistant (8 tools)

| Tool | Description |
|------|-------------|
| `devantis_chat_session` | Manage active session (set, start, clear, get) |
| `devantis_chat_send` | Send message, collect response |
| `devantis_chat_answer` | Answer a paused workflow's question |
| `devantis_chat_confirm` | Approve/reject a workflow proposal |
| `devantis_chat_history` | Get conversation history |
| `devantis_chat_sessions` | List recent sessions |
| `devantis_chat_stop` | Cancel running workflow |
| `devantis_chat_delete` | Delete a session |

### Knowledge Graph / Brain (12 tools)

| Tool | Description |
|------|-------------|
| `devantis_kg_search` | Search entities and observations |
| `devantis_kg_get_entity` | Get entity with all observations |
| `devantis_kg_add` | Create entity with observations |
| `devantis_kg_add_observation` | Add observation to existing entity |
| `devantis_kg_remove` | Delete entity, observation, or relation |
| `devantis_kg_relations` | Manage entity relations |
| `devantis_kg_reason` | LLM reasoning over brain knowledge |
| `devantis_kg_stats` | Graph statistics |
| `devantis_kg_vitals` | Brain health and intelligence score |
| `devantis_kg_impact` | Impact analysis (what depends on this?) |
| `devantis_kg_confirm_observation` | Mark observation as still valid |
| `devantis_kg_dependencies` | Recursive dependency traversal |

### Executors (3 tools)

| Tool | Description |
|------|-------------|
| `devantis_executor_shell` | Run shell commands on remote agents |
| `devantis_deploy_k8s` | Kubernetes operations via MCP |
| `devantis_list_executors` | List executor agents and status |

### Analytics (2 tools)

| Tool | Description |
|------|-------------|
| `devantis_token_usage` | Token usage and cost analytics |
| `devantis_cost_forecast` | Cost predictions and spending alerts |

### Users & Team (4 tools)

| Tool | Description |
|------|-------------|
| `devantis_users_search` | Find users by name/email |
| `devantis_users_me` | Current user profile |
| `devantis_list_members` | List members at org/project/app level |
| `devantis_manage_members` | Add/update/remove members |

### Platform (8 tools)

| Tool | Description |
|------|-------------|
| `devantis_search` | Cross-entity parallel search |
| `devantis_memory` | Persistent project memory (key-value) |
| `devantis_switch_context` | Switch org/project/app |
| `devantis_list_projects` | List orgs, projects, or apps |
| `devantis_get_config` | Get app configuration |
| `devantis_update_config` | Update configuration |
| `devantis_manage_notifications` | Notification channels and subscriptions |
| `devantis_bulk_tickets` | Batch ticket operations |

### Documentation (3 tools)

| Tool | Description |
|------|-------------|
| `devantis_list_docs` | List documentation pages |
| `devantis_read_doc` | Read a documentation page |
| `devantis_search_docs` | Search documentation |

## Publishing to PyPI

### Prerequisites

1. **PyPI account**: Register at https://pypi.org/account/register/
2. **API token**: Create at https://pypi.org/manage/account/token/

### Configure Credentials

Create `~/.pypirc` (one-time setup):

```ini
[pypi]
username = __token__
password = pypi-AgEIcH...your-token-here...
```

Lock down permissions:
```bash
chmod 600 ~/.pypirc
```

### Files Involved in Publishing

```
sources/sdk/
├── pyproject.toml          # Package metadata, version, dependencies
├── README.md               # This file (shown on PyPI page)
├── src/devantis/           # Source code (packaged into the wheel)
│   ├── __init__.py         # Exports DevantisClient, __version__
│   ├── __main__.py         # Entry point for python -m devantis
│   ├── mcp_server.py       # MCP server with 89 tool definitions
│   ├── main.py             # DevantisClient class
│   ├── client.py           # HTTP client (auth, retries, gateway mode)
│   ├── auth.py             # Keycloak auth providers
│   ├── tenant.py           # Tenant resolution (org/project/app)
│   ├── errors.py           # Typed exceptions
│   └── services/           # Service classes (one per backend)
├── Makefile                # Build/publish/test commands
└── dist/                   # Built artifacts (created by make build)
    ├── devantis_sdk-X.Y.Z.tar.gz          # Source distribution
    └── devantis_sdk-X.Y.Z-py3-none-any.whl  # Wheel (binary)
```

### Release Process

**1. Bump the version** in `pyproject.toml`:
```toml
version = "0.2.0"
```

**2. Build and verify:**
```bash
make build      # Creates dist/*.whl and dist/*.tar.gz
make verify     # Syntax + imports + tool audit
make check      # MCP server handshake test
```

**3. Test on TestPyPI** (optional but recommended for first release):
```bash
make publish-test

# Then test the install:
pip install -i https://test.pypi.org/simple/ devantis-sdk[mcp]
```

**4. Publish to PyPI:**
```bash
make publish
```

**5. Verify the release:**
```bash
pip install devantis-sdk[mcp]
python -c "from devantis import DevantisClient; print('OK')"
```

### Makefile Reference

```bash
make install       # Create venv + install with MCP deps
make install-dev   # Same + dev/test deps
make build         # Build wheel + sdist into dist/
make publish       # Build + upload to PyPI
make publish-test  # Build + upload to TestPyPI
make verify        # Syntax + imports + tool audit (0 weak descriptions)
make check         # MCP server initialize handshake test
make tools         # List all MCP tool names
make tool-count    # Print tool count
make run           # Run MCP server (stdio)
make claude-add    # Register in Claude CLI
make claude-remove # Unregister from Claude CLI
make claude-status # Check MCP server status
make test          # Run pytest
make clean         # Remove dist/ and build artifacts
make clean-all     # Remove venv + all artifacts
```

## Project Structure

```
src/devantis/
├── __init__.py                # Public API: DevantisClient
├── __main__.py                # python -m devantis entry point
├── main.py                    # DevantisClient — connects and exposes all services
├── client.py                  # BaseClient — HTTP with auth, retries, gateway mode
├── auth.py                    # UserTokenAuth, InternalAuth, ServiceAccountAuth
├── tenant.py                  # TenantContext resolution (slugs -> UUIDs)
├── errors.py                  # DevantisError, AuthError, NotFound, Forbidden, etc.
├── mcp_server.py              # MCP server — 89 tool definitions + dispatch
└── services/
    ├── source.py              # File ops, grep, glob, batch
    ├── tickets.py             # Full ticket lifecycle + sub-resources
    ├── requirements.py        # Requirement CRUD + search
    ├── architecture.py        # Architecture documents
    ├── designs.py             # Design files (HTML, CSS, tokens)
    ├── chat.py                # WebSocket chat with pause/resume
    ├── knowledge_graph.py     # AI brain — entities, relations, reasoning
    ├── executors.py           # Remote shell, K8s deploy, MCP tools
    ├── projects.py            # Org/project/app management + members
    ├── analytics.py           # Token usage, cost forecast, alerts
    ├── users.py               # User search and profiles
    ├── notifications.py       # Channels, subscriptions, logs
    ├── search.py              # Cross-entity parallel search
    ├── memory.py              # Persistent key-value storage
    └── docs.py                # Platform documentation
```

## License

MIT
