Metadata-Version: 2.4
Name: badana-mcp-sdk
Version: 0.5.0
Summary: Framework-independent Python SDK for secure MCP product integrations
License-Expression: MIT
Project-URL: Homepage, https://github.com/hosseinjavadi2001/badana-mcp-sdk
Project-URL: Documentation, https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/README.md
Project-URL: Issues, https://github.com/hosseinjavadi2001/badana-mcp-sdk/issues
Project-URL: Changelog, https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/CHANGELOG.md
Project-URL: Repository, https://github.com/hosseinjavadi2001/badana-mcp-sdk
Keywords: mcp,oauth2,keycloak,multi-tenant,sdk
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: PyJWT[crypto]<3,>=2.15.1
Requires-Dist: httpx<1,>=0.28
Requires-Dist: jsonschema<5,>=4.23
Provides-Extra: serve
Requires-Dist: uvicorn<1,>=0.34; extra == "serve"
Provides-Extra: test
Requires-Dist: pytest<10,>=8; extra == "test"
Requires-Dist: pytest-asyncio<2,>=0.25; extra == "test"
Requires-Dist: mcp<2,>=1.30; extra == "test"
Requires-Dist: uvicorn<1,>=0.34; extra == "test"
Requires-Dist: build<2,>=1.2; extra == "test"
Dynamic: license-file

# Badana MCP SDK

[![PyPI](https://img.shields.io/pypi/v/badana-mcp-sdk)](https://pypi.org/project/badana-mcp-sdk/)
[![Python versions](https://img.shields.io/pypi/pyversions/badana-mcp-sdk)](https://pypi.org/project/badana-mcp-sdk/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/LICENSE)
[![SDK CI](https://github.com/hosseinjavadi2001/badana-mcp-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/hosseinjavadi2001/badana-mcp-sdk/actions/workflows/ci.yml)

Framework-independent Python SDK for secure product integration with an MCP gateway, including DanaPol. Use the same core from an existing application, an ASGI server, or a separately deployed Python integration service. No Django, FastAPI, FastMCP, ORM, or product database is required.

**Current release:** [0.5.0](https://pypi.org/project/badana-mcp-sdk/0.5.0/) · Python 3.11+ · [MIT License](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/LICENSE). Published through GitHub Actions using PyPI Trusted Publishing (OIDC). The SDK is in alpha development; it is not yet production-certified.

## Why Badana MCP SDK?

- **Framework-independent:** use the Python core directly, mount the optional ASGI transport, or run a standalone service.
- **Secure delegated access:** RS256 JWT validation, bounded JWKS caching and key rotation, explicit issuer, audience, scope and client checks.
- **Product-owned authorization:** exact identity mapping, organization isolation, tool permissions and record-level authorization via adapters.
- **Tool discovery:** decorators, explicit or inferred JSON Schema, and a versioned service manifest.
- **Optional provisioning and writes:** separate machine-token authentication, product-controlled provisioning, transactional idempotency contracts and a SQLite reference helper.
- **Cross-language integration:** an authenticated HTTPS sidecar with optional mTLS for products implemented in other languages.
- **Developer tooling:** CLI, environment configuration, liveness/readiness endpoints, request limits and audit logging.

## Architecture

```text
Compatible MCP gateway
    |
    +-- Delegated user JWT / MCP --> Badana MCP SDK
    |                                  |
    |                                  +-- Authentication and authorization
    |                                  +-- Tool registry and manifest
    |                                  |
    |                                  +-- Native Python adapter --> Product
    |                                  +-- HTTPS sidecar --> Private product API
    |
    +-- Dedicated machine JWT --> Optional control adapter --> Product
```

Since 0.4.0, the HTTP transport requires a pinned gateway request signature on every protected endpoint, including manifest. The signature binds method, exact target, selected security headers and request body, expires within 30 seconds, and supplements the delegated JWT. Health endpoints remain minimal and public. Local CLI manifest output remains available to operators. See SECURITY.md for migration and replay considerations.

The gateway owns AI access grants and approval; the product owns business authorization and persistence. The SDK connects these boundaries without replacing your application or identity provider.

## Installation

Install the published package from PyPI:

```bash
python -m pip install badana-mcp-sdk
```

For standalone ASGI serving, install the optional extra:

```bash
python -m pip install 'badana-mcp-sdk[serve]'
```

Pin the current release for reproducible integration:

```bash
python -m pip install 'badana-mcp-sdk[serve]==0.5.0'
badana-mcp --version
```

### Install from source

```bash
git clone https://github.com/hosseinjavadi2001/badana-mcp-sdk.git
cd badana-mcp-sdk
python -m pip install -e '.[serve]'
```

The core requires only PyJWT with cryptography, HTTPX and jsonschema (plus their transitive dependencies). Uvicorn is an optional ASGI server. No framework-specific types enter the public API.

## Quick start: define the product

```python
from badana_mcp import (
    BadanaSDK, Capabilities, JWTConfig, JWTVerifier,
    Organization, ProductAdapter, ProductConfig,
)
from badana_mcp.asgi import ASGIApplication
from badana_mcp.gateway import GatewayProofVerifier


class Adapter(ProductAdapter):
    async def resolve_user(self, identity):
        # Replace with an exact issuer+subject lookup of an active local user.
        return await users.find_active(identity.issuer, identity.subject)

    async def capabilities(self, user):
        # Return current memberships and effective product permission names.
        return await permissions.get_capabilities(user)

    async def authorize(self, context, tool, arguments):
        # Product-owned tool AND resource/record authorization.
        return await permissions.can_execute(
            context.user, context.organization, tool, arguments
        )


config = ProductConfig("erp", "Example ERP", "erp-main")
verifier = JWTVerifier(JWTConfig.keycloak(
    issuer="https://identity.example/realms/example",
    audience=config.audience,
    required_scope=config.access_scope,
    allowed_clients=frozenset({"https://gateway.example/mcp"}),
))
sdk = BadanaSDK(config, Adapter(), verifier)


@sdk.tool(permissions=["projects.view"], read_only=True)
async def list_projects(context, limit: int = 20):
    """List projects in the selected organization."""
    return await projects.list_for(context.user, context.organization.id, limit)


# Provision this public key through a trusted operator channel.
# The private signing key must stay exclusively in the gateway.
import os
proof = GatewayProofVerifier(
    issuer="https://gateway.example/mcp",
    audience="https://erp.example",
    public_keys=os.environ["BADANA_GATEWAY_PUBLIC_KEY"],
)
app = ASGIApplication(sdk, allowed_hosts=["erp.example"], gateway_proof=proof)
```

The example above is integration pseudocode (users, permissions and projects are your product services). See [examples/standalone.py](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/examples/standalone.py) for a runnable read-only example. Clone the repository and run the following from its root (the example is in the source repository):

```bash
export EXAMPLE_ISSUER=https://identity.example/realms/example
export EXAMPLE_EXCHANGE_CLIENTS=https://gateway.example/mcp
export EXAMPLE_USER_SUBJECT=replace-with-real-subject
export BADANA_GATEWAY_PROOF_ISSUER=https://gateway.example/mcp
export BADANA_PRODUCT_ORIGIN=https://erp.example
# Set BADANA_GATEWAY_PUBLIC_KEY to the trusted gateway's RSA public PEM.
badana-mcp check --sdk examples.standalone:sdk
uvicorn examples.standalone:app --host 127.0.0.1 --port 8000
```

Deploy behind HTTPS; configure exact Host and optional Origin allowlists. Do not expose a database, trust forwarded identity headers, or run with wildcard hosts. The example uses a fake dataset and does not create users or support writes.

## Endpoints

| Endpoint | Authentication | Purpose |
| --- | --- | --- |
| GET /health/live | Public | Process liveness |
| GET /health/ready | Public | Adapter readiness |
| GET /api/mcp/manifest/ | Public | Non-secret versioned service/tool definitions |
| GET /api/mcp/capabilities/ | Delegated user JWT | Current product permission discovery |
| POST /mcp | Delegated user JWT | Stateless MCP tools |
| GET /api/badana/v1/catalog/ | Dedicated machine JWT | Assignable organizations and roles |
| POST /api/badana/v1/provisioning/ | Dedicated machine JWT | Product user provisioning |

Management endpoints fail closed unless explicitly configured. The SDK supports the 2025 tools-only Streamable HTTP profile used by the current DanaPol gateway (2025-11-25, 2025-06-18, 2025-03-26). It is not a full implementation of MCP resources, prompts, sampling, SSE, session storage, the 2026 protocol revision, or public OAuth authorization-server discovery. Those are not required for this internal delegated-token integration.

## CLI and cross-language integration

```bash
badana-mcp --version
badana-mcp check --sdk examples.standalone:sdk
badana-mcp manifest --sdk examples.standalone:sdk
```

These commands load trusted local Python code, validate its public manifest and do not claim live connectivity. Set the example's environment variables first. For Java, Node.js, .NET or other languages, the optional plain-Python sidecar uses a fixed HTTPS backend API, dedicated machine credentials, reviewed local tool definitions, and optional mutual TLS.

```bash
# Configure the environment using examples/sidecar.env.example as a guide.
badana-mcp check --sidecar examples/sidecar.toml
badana-mcp serve --sidecar examples/sidecar.toml --host 127.0.0.1 --port 8000
```

See [sidecar protocol](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/docs/sidecar.md) for the backend contract and trust boundaries. Write and management operations are opt-in. The product owns authorization and idempotency.

## Security model

- Validate RS256 signatures using trusted configured HTTPS JWKS, issuer, exclusive audience, access-token type, client allowlist, subject, scope and token lifetime.
- Resolve local user identity and organization membership for each invocation. Never infer identity from username or email.
- Business authorization remains the product's responsibility. The SDK requires an explicit authorization adapter and checks declared permission names before execution.
- Control and user tokens have different audience, scope, client allowlists and explicitly pinned machine subjects. A product machine token must never authorize user tools.
- Writes are disabled by default; implement the product's transactional idempotency adapter before enabling them.
- Gateway browser approval and AI access policy are enforced by the gateway. The SDK receives the delegated JWT and idempotency key, not independent proof of human approval. Restrict ingress to the trusted gateway; use mTLS or sender-constrained credentials at infrastructure level where required.
- Do not place secrets, private data or privileged tool descriptions in the public Manifest. Tool handlers must return only authorized data and never return credentials.
- Configure TLS, egress policy, service-account privileges, timeouts, rate limits and log retention at deployment. Bearer JWT can be replayed until expiry; local permission checks help revocation but do not replace sender authentication.
- Audit logger emits identity, operation, request ID, result status and organization, not tokens, arguments or exception details.

See [CHANGELOG](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/CHANGELOG.md), [security policy](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/SECURITY.md), and [integration contract](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/docs/integration.md) for precise SDK interfaces, scope names, provisioning and idempotency requirements, and supported limitations.

## Documentation

| Guide | Description |
| --- | --- |
| [Integration contract](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/docs/integration.md) | Adapter interfaces, identity mapping, authorization and provisioning |
| [Sidecar protocol](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/docs/sidecar.md) | Integrate non-Python products over a private HTTPS API |
| [Standalone example](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/examples/standalone.py) | Runnable read-only integration |
| [Sidecar example configuration](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/examples/sidecar.toml) | Declarative tool registration |
| [Environment example](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/examples/sidecar.env.example) | Deployment configuration reference |
| [Security policy](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/SECURITY.md) | Trust boundaries and responsible disclosure |
| [Release procedure](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/docs/release.md) | Maintainer-only publishing workflow |
| [Changelog](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/CHANGELOG.md) | Release history |
| [Contributing](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/CONTRIBUTING.md) | Development and contribution guidelines |

## Development

Clone the repository and run:

```bash
git clone https://github.com/hosseinjavadi2001/badana-mcp-sdk.git
cd badana-mcp-sdk
python -m pip install -e '.[test]'
python -m pytest -q
python -m build
```

No real service credentials are required by the tests. CI tests Python 3.11, 3.12 and 3.13, validates package builds and checks wheel installation. Before production, run a live integration test with your identity provider, gateway and actual product authorization model.

## Release and compatibility status

- Published package: [badana-mcp-sdk on PyPI](https://pypi.org/project/badana-mcp-sdk/).
- Release 0.5.0: alpha; supports the documented tools-only MCP profile and DanaPol v1 integration contract.
- PyPI publishing uses a separate, manually dispatched workflow and OIDC Trusted Publishing, without a long-lived PyPI API token. See the [release procedure](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/docs/release.md).
- Live end-to-end product integration and independent security review remain outstanding. The SDK is not a complete implementation of every MCP feature.

## License

Released under the [MIT License](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/LICENSE). Commercial and non-commercial use, modification, and redistribution are permitted subject to the license terms.

## Product-initiated connection (DanaPol)

Use the new `ProductLinkClient` on your backend after authenticating the user in your own application. It triggers trusted manifest discovery, returns a one-time browser handoff and verifies the federated identity after your OAuth callback. See the [integration contract](https://github.com/hosseinjavadi2001/badana-mcp-sdk/blob/main/docs/integration.md). No user password is sent to DanaPol. Requires a DanaPol deployment with the product broker enabled.


Version 0.5.0 requires `mobile` in ProductLinkClient.start. Supply the authenticated user's phone from backend account data; DanaPol does not perform OTP or other product authentication. Mobile is never sent in OAuth or MCP tokens. Use bind_existing_mobile to migrate previously completed product links before registering another product.
