Metadata-Version: 2.4
Name: zainahmed-sdk
Version: 1.0.2
Summary: Official Python SDK for Zain Ahmed's Cloud Architecture, DevSecOps & Agent API
Author-email: Zain Ahmed <hello@zainahmed.net>
License-Expression: MIT
Project-URL: Homepage, https://zainahmed.net
Project-URL: Documentation, https://zainahmed.net/docs
Project-URL: Repository, https://github.com/thezaynahmed/portfolio
Keywords: zainahmed,cloud-architecture,sre,mcp,agentic-ai,sdk
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.24.0
Dynamic: license-file

<div align="center">

# zainahmed-sdk

**Official Python client library and Model Context Protocol (MCP) provider for Zain Ahmed's Cloud Architecture, DevSecOps & Autonomous Agent Gateway.**

[![PyPI version](https://img.shields.io/pypi/v/zainahmed-sdk.svg?style=flat-square&color=2563eb)](https://pypi.org/project/zainahmed-sdk/)
[![Python Versions](https://img.shields.io/pypi/pyversions/zainahmed-sdk.svg?style=flat-square&color=10b981)](https://pypi.org/project/zainahmed-sdk/)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT)
[![OpenAPI 3.1.0](https://img.shields.io/badge/OpenAPI-3.1.0-emerald.svg?style=flat-square)](https://zainahmed.net/openapi.json)
[![Dual MCP Servers](https://img.shields.io/badge/MCP-streamable--http%20%26%20sse-purple.svg?style=flat-square)](https://zainahmed.net/mcp)
[![PEP 561](https://img.shields.io/badge/typing-PEP%20561-blueviolet.svg?style=flat-square)](https://peps.python.org/pep-0561/)
[![HTTPX Powered](https://img.shields.io/badge/HTTPX-async%20%26%20sync-blue.svg?style=flat-square)](https://www.python-httpx.org/)

[Live Platform](https://zainahmed.net) •
[Documentation](https://zainahmed.net/docs) •
[Interactive Console](https://zainahmed.net/developers) •
[Interactive Sandbox](https://zainahmed.net/sandbox) •
[Pricing Tiers](https://zainahmed.net/pricing.md) •
[GitHub Repository](https://github.com/thezaynahmed/portfolio)

</div>

---

## Overview

`zainahmed-sdk` is an open-source Python client for interacting with **Zain Ahmed's verified cloud architecture portfolio, enterprise blueprints, advisory consulting services, and autonomous agent discovery endpoints**.

Built on **HTTPX**, the library provides both synchronous and asynchronous clients with connection pooling, configurable timeouts, RFC 9457 structured error handling, and direct integration with AI agent frameworks (LangChain, LlamaIndex).

### Features

- **Dual Sync & Async Interfaces**: Use `ZainClient` for automation scripts and Jupyter notebooks, or `AsyncZainClient` for asyncio agent swarms and FastAPI services.
- **Strict PEP 561 Types**: Full type annotations across all methods and return values for IDE autocomplete and mypy validation.
- **Typed RFC 9457 Problem Details**: Exceptions raise `ZainAhmedAPIError` with machine-readable `status_code` and `problem_details`.
- **Zero-Mutation Sandbox**: Pass `sandbox=True` to simulate API calls against `/api/v1/sandbox` without mutating live records.
- **Natural Language NLWeb (`ask`)**: Query verified multi-cloud case studies and credentials using natural language with cited source links.
- **Dual MCP Server Export**: Generate Model Context Protocol configurations for both the Operations MCP (`/mcp`) and Documentation MCP (`/mcp/docs`) servers.
- **Context Manager Support**: Clean connection lifecycle management with `with` and `async with` blocks.

---

## Table of Contents

- [Installation](#installation)
- [Quickstart](#quickstart)
  - [Synchronous (`ZainClient`)](#1-synchronous-usage-zainclient)
  - [Asynchronous (`AsyncZainClient`)](#2-asynchronous-usage-asynczainclient)
- [API Reference](#api-reference)
- [Interactive Sandbox Mode](#interactive-sandbox-mode)
- [Error Handling (RFC 9457)](#error-handling-rfc-9457)
- [Model Context Protocol (MCP) Integration](#model-context-protocol-mcp-integration)
- [Agent Framework Integration](#agent-framework-integration)
  - [LangChain Custom Tool](#langchain-custom-tool)
  - [LlamaIndex Tool](#llamaindex-tool)
- [Configuration & Environment](#configuration--environment)
- [Contributing](#contributing)
- [License](#license)

---

## Installation

### Requirements

- Python `>= 3.10`
- `httpx >= 0.24.0`

Install using your preferred package manager:

```bash
# pip
pip install zainahmed-sdk

# uv
uv add zainahmed-sdk

# poetry
poetry add zainahmed-sdk

# pdm
pdm add zainahmed-sdk
```

---

## Quickstart

### 1. Synchronous Usage (`ZainClient`)

For scripts, CLI utilities, and data science workflows:

```python
from zainahmed import ZainClient

with ZainClient() as client:
    # 1. Fetch verified architect credentials & 5x certifications
    profile = client.get_profile()
    print(f"Connected: {profile['name']} — {profile['title']}")

    # 2. Query architectural case studies by category
    projects = client.list_projects(category="cloud-architecture", limit=5)
    for project in projects.get("projects", []):
        print(f"  - [{project['category']}] {project['title']}")

    # 3. Query technical knowledge base via NLWeb
    response = client.ask("What multi-cloud certifications does Zain hold?")
    print("\nAnswer:", response["answer"])
    for source in response.get("sources", []):
        print(f"  Source: {source['title']} ({source['url']})")

    # 4. Fetch plain markdown pricing and SLA terms
    pricing = client.get_pricing()
    print("\nPricing preview:\n", pricing[:120])
```

### 2. Asynchronous Usage (`AsyncZainClient`)

For asyncio agent loops, FastAPI microservices, or concurrent workloads:

```python
import asyncio
from zainahmed import AsyncZainClient

async def main():
    async with AsyncZainClient() as client:
        # Run concurrent requests
        profile_task = client.get_profile()
        projects_task = client.list_projects(category="kubernetes")

        profile, projects = await asyncio.gather(profile_task, projects_task)

        print(f"Architect: {profile['name']}")
        print(f"Found {len(projects.get('projects', []))} Kubernetes case studies")

asyncio.run(main())
```

---

## API Reference

Both `ZainClient` and `AsyncZainClient` expose the same methods:

| Method                                     | HTTP Path              | Return Type | Description                                                                                                                    |
| :----------------------------------------- | :--------------------- | :---------- | :----------------------------------------------------------------------------------------------------------------------------- |
| `get_profile(section=None)`                | `GET /api/v1/profile`  | `dict`      | Retrieve engineer profile, credentials, and social links. `section` can be `"all"`, `"credentials"`, `"bio"`, or `"contacts"`. |
| `list_projects(category=None, limit=None)` | `GET /api/v1/projects` | `dict`      | List enterprise case studies. Filter by category: `"cloud-architecture"`, `"devsecops"`, `"ai-ml"`, `"finops"`.                |
| `list_articles(category=None, limit=None)` | `GET /api/v1/articles` | `dict`      | List published technical deep-dives and SRE blueprints.                                                                        |
| `list_services(tier=None)`                 | `GET /api/v1/services` | `dict`      | List advisory consulting tiers, retainer scopes, and engagement models.                                                        |
| `get_pricing()`                            | `GET /pricing.md`      | `str`       | Retrieve plain Markdown pricing tiers, SLAs (P1-P4), and payment terms.                                                        |
| `submit_contact(...)`                      | `POST /api/v1/contact` | `dict`      | Submit consultation inquiry with optional RFC 7231 `idempotency_key`.                                                          |
| `ask(query)`                               | `POST /ask`            | `dict`      | Query NLWeb reasoning engine. Returns `query`, `answer`, and citation `sources`.                                               |
| `get_mcp_config()`                         | Local generator        | `dict`      | Generate Claude Desktop / Cursor `mcpServers` configuration dictionary.                                                        |

---

## Interactive Sandbox Mode

Test integrations, webhooks, or agent tool calling safely with zero mutation risk against production records:

```python
from zainahmed import ZainClient

# Route all calls to https://zainahmed.net/api/v1/sandbox
with ZainClient(sandbox=True) as client:
    result = client.submit_contact(
        name="Agent Tester",
        email="tester@example.com",
        subject="Sandbox Verification",
        message="Simulating automated agent submission in test mode.",
    )
    print("Status:", result["status"])  # "success" (simulated ID, no email sent)
```

---

## Error Handling (RFC 9457)

Non-2xx HTTP responses raise `ZainAhmedAPIError` containing RFC 9457 **Problem Details**:

```python
from zainahmed import ZainClient, ZainAhmedAPIError

client = ZainClient()

try:
    client.submit_contact(
        name="",  # Validation failure: missing required field
        email="invalid-email",
        message="",
    )
except ZainAhmedAPIError as exc:
    print(f"HTTP Status: {exc.status_code}")
    print(f"Title: {exc.problem_details.get('title')}")
    print(f"Detail: {exc.problem_details.get('detail')}")
    print(f"Code: {exc.problem_details.get('code')}")
```

---

## Model Context Protocol (MCP) Integration

Connect Claude Desktop, Cursor, or Antigravity agents directly to Zain Ahmed's live knowledge base.

### Programmatic Config Export

```python
from zainahmed import ZainClient

client = ZainClient()
print(client.get_mcp_config())
```

### Claude Desktop Configuration

Add the following to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "zainahmed": {
      "url": "https://zainahmed.net/mcp",
      "transport": "streamable-http"
    },
    "zainahmed-docs": {
      "url": "https://zainahmed.net/mcp/docs",
      "transport": "streamable-http"
    }
  }
}
```

---

## Agent Framework Integration

### LangChain Custom Tool

```python
from langchain.tools import tool
from zainahmed import ZainClient

client = ZainClient()

@tool
def ask_zain_architecture(question: str) -> str:
    """Queries Zain Ahmed's verified multi-cloud and SRE architecture knowledge base."""
    result = client.ask(question)
    return result.get("answer", "No answer found.")
```

### LlamaIndex Tool

```python
from llama_index.core.tools import FunctionTool
from zainahmed import ZainClient

client = ZainClient()

def search_case_studies(category: str) -> str:
    """Searches Zain Ahmed's case studies by category."""
    projects = client.list_projects(category=category)
    return str(projects)

case_studies_tool = FunctionTool.from_defaults(fn=search_case_studies)
```

---

## Configuration & Environment

```python
from zainahmed import ZainClient

client = ZainClient(
    # Custom base URL (default: https://zainahmed.net)
    base_url="https://zainahmed.net",

    # Optional Bearer token for authenticated enterprise tiers
    api_key="your_api_key_here",

    # Route requests through the verified Sandbox test environment
    sandbox=False,

    # Request timeout in seconds (default: 15.0)
    timeout=15.0,
)
```

---

## Contributing

1. Clone the repository:
   ```bash
   git clone https://github.com/thezaynahmed/portfolio.git
   cd portfolio/packages/sdk-python
   ```
2. Install editable package with test dependencies:
   ```bash
   pip install -e .
   pip install pytest build twine
   ```
3. Build distribution packages:
   ```bash
   python3 -m build
   ```

---

## License

MIT © [Zain Ahmed](https://zainahmed.net) (<hello@zainahmed.net>)

---

<div align="center">
  <sub>Last reviewed: September 2026 • Maintained for human developers and autonomous AI agents</sub>
</div>
