Metadata-Version: 2.4
Name: badana-mcp-sdk
Version: 0.2.0
Summary: Framework-independent Python SDK for secure MCP product integrations
License-Expression: MIT
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

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.

**Status:** alpha (0.2.0), Python 3.11+. Open source under the [MIT License](LICENSE). PyPI publication is managed through the [release procedure](docs/release.md); this is not yet a production-certified integration.

## 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.

## Define the product

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


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)


app = ASGIApplication(sdk, allowed_hosts=["erp.example"])
```

The example above is integration pseudocode (users, permissions and projects are your product services). See [examples/standalone.py](examples/standalone.py) for a runnable read-only example.

```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
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](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](CHANGELOG.md), [security policy](SECURITY.md), and [integration contract](docs/integration.md) for precise SDK interfaces, scope names, provisioning and idempotency requirements, and supported limitations.

## Development

```bash
python -m pip install -e '.[test]'
python -m pytest -q
python -m build
```

No real service credentials are required by the tests. Before production, run a live integration test with your identity provider, gateway and actual product authorization model.
