badana-mcp-sdk 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. badana_mcp_sdk-0.2.0/LICENSE +21 -0
  2. badana_mcp_sdk-0.2.0/PKG-INFO +156 -0
  3. badana_mcp_sdk-0.2.0/README.md +127 -0
  4. badana_mcp_sdk-0.2.0/pyproject.toml +46 -0
  5. badana_mcp_sdk-0.2.0/setup.cfg +4 -0
  6. badana_mcp_sdk-0.2.0/src/badana_mcp/__init__.py +13 -0
  7. badana_mcp_sdk-0.2.0/src/badana_mcp/__main__.py +3 -0
  8. badana_mcp_sdk-0.2.0/src/badana_mcp/adapters.py +96 -0
  9. badana_mcp_sdk-0.2.0/src/badana_mcp/asgi.py +252 -0
  10. badana_mcp_sdk-0.2.0/src/badana_mcp/auth.py +140 -0
  11. badana_mcp_sdk-0.2.0/src/badana_mcp/cli.py +118 -0
  12. badana_mcp_sdk-0.2.0/src/badana_mcp/config.py +109 -0
  13. badana_mcp_sdk-0.2.0/src/badana_mcp/core.py +297 -0
  14. badana_mcp_sdk-0.2.0/src/badana_mcp/errors.py +37 -0
  15. badana_mcp_sdk-0.2.0/src/badana_mcp/idempotency.py +63 -0
  16. badana_mcp_sdk-0.2.0/src/badana_mcp/jsonutil.py +68 -0
  17. badana_mcp_sdk-0.2.0/src/badana_mcp/py.typed +0 -0
  18. badana_mcp_sdk-0.2.0/src/badana_mcp/settings.py +60 -0
  19. badana_mcp_sdk-0.2.0/src/badana_mcp/sidecar.py +229 -0
  20. badana_mcp_sdk-0.2.0/src/badana_mcp/tools.py +136 -0
  21. badana_mcp_sdk-0.2.0/src/badana_mcp_sdk.egg-info/PKG-INFO +156 -0
  22. badana_mcp_sdk-0.2.0/src/badana_mcp_sdk.egg-info/SOURCES.txt +32 -0
  23. badana_mcp_sdk-0.2.0/src/badana_mcp_sdk.egg-info/dependency_links.txt +1 -0
  24. badana_mcp_sdk-0.2.0/src/badana_mcp_sdk.egg-info/entry_points.txt +2 -0
  25. badana_mcp_sdk-0.2.0/src/badana_mcp_sdk.egg-info/requires.txt +13 -0
  26. badana_mcp_sdk-0.2.0/src/badana_mcp_sdk.egg-info/top_level.txt +1 -0
  27. badana_mcp_sdk-0.2.0/tests/test_asgi.py +59 -0
  28. badana_mcp_sdk-0.2.0/tests/test_auth.py +75 -0
  29. badana_mcp_sdk-0.2.0/tests/test_cli.py +32 -0
  30. badana_mcp_sdk-0.2.0/tests/test_core.py +76 -0
  31. badana_mcp_sdk-0.2.0/tests/test_hardening.py +54 -0
  32. badana_mcp_sdk-0.2.0/tests/test_idempotency.py +34 -0
  33. badana_mcp_sdk-0.2.0/tests/test_sidecar.py +115 -0
  34. badana_mcp_sdk-0.2.0/tests/test_tools.py +32 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Badana MCP SDK contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.4
2
+ Name: badana-mcp-sdk
3
+ Version: 0.2.0
4
+ Summary: Framework-independent Python SDK for secure MCP product integrations
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/hosseinjavadi2001/badana-mcp-sdk
7
+ Keywords: mcp,oauth2,keycloak,multi-tenant,sdk
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: PyJWT[crypto]<3,>=2.15.1
18
+ Requires-Dist: httpx<1,>=0.28
19
+ Requires-Dist: jsonschema<5,>=4.23
20
+ Provides-Extra: serve
21
+ Requires-Dist: uvicorn<1,>=0.34; extra == "serve"
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest<10,>=8; extra == "test"
24
+ Requires-Dist: pytest-asyncio<2,>=0.25; extra == "test"
25
+ Requires-Dist: mcp<2,>=1.30; extra == "test"
26
+ Requires-Dist: uvicorn<1,>=0.34; extra == "test"
27
+ Requires-Dist: build<2,>=1.2; extra == "test"
28
+ Dynamic: license-file
29
+
30
+ # Badana MCP SDK
31
+
32
+ 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.
33
+
34
+ **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.
35
+
36
+ ## Install from source
37
+
38
+ ```bash
39
+ git clone https://github.com/hosseinjavadi2001/badana-mcp-sdk.git
40
+ cd badana-mcp-sdk
41
+ python -m pip install -e '.[serve]'
42
+ ```
43
+
44
+ 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.
45
+
46
+ ## Define the product
47
+
48
+ ```python
49
+ from badana_mcp import (
50
+ BadanaSDK, Capabilities, JWTConfig, JWTVerifier,
51
+ Organization, ProductAdapter, ProductConfig,
52
+ )
53
+ from badana_mcp.asgi import ASGIApplication
54
+
55
+
56
+ class Adapter(ProductAdapter):
57
+ async def resolve_user(self, identity):
58
+ # Replace with an exact issuer+subject lookup of an active local user.
59
+ return await users.find_active(identity.issuer, identity.subject)
60
+
61
+ async def capabilities(self, user):
62
+ # Return current memberships and effective product permission names.
63
+ return await permissions.get_capabilities(user)
64
+
65
+ async def authorize(self, context, tool, arguments):
66
+ # Product-owned tool AND resource/record authorization.
67
+ return await permissions.can_execute(
68
+ context.user, context.organization, tool, arguments
69
+ )
70
+
71
+
72
+ config = ProductConfig("erp", "Example ERP", "erp-main")
73
+ verifier = JWTVerifier(JWTConfig.keycloak(
74
+ issuer="https://identity.example/realms/example",
75
+ audience=config.audience,
76
+ required_scope=config.access_scope,
77
+ allowed_clients=frozenset({"https://gateway.example/mcp"}),
78
+ ))
79
+ sdk = BadanaSDK(config, Adapter(), verifier)
80
+
81
+
82
+ @sdk.tool(permissions=["projects.view"], read_only=True)
83
+ async def list_projects(context, limit: int = 20):
84
+ """List projects in the selected organization."""
85
+ return await projects.list_for(context.user, context.organization.id, limit)
86
+
87
+
88
+ app = ASGIApplication(sdk, allowed_hosts=["erp.example"])
89
+ ```
90
+
91
+ 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.
92
+
93
+ ```bash
94
+ export EXAMPLE_ISSUER=https://identity.example/realms/example
95
+ export EXAMPLE_EXCHANGE_CLIENTS=https://gateway.example/mcp
96
+ export EXAMPLE_USER_SUBJECT=replace-with-real-subject
97
+ uvicorn examples.standalone:app --host 127.0.0.1 --port 8000
98
+ ```
99
+
100
+ 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.
101
+
102
+ ## Endpoints
103
+
104
+ | Endpoint | Authentication | Purpose |
105
+ | --- | --- | --- |
106
+ | GET /health/live | Public | Process liveness |
107
+ | GET /health/ready | Public | Adapter readiness |
108
+ | GET /api/mcp/manifest/ | Public | Non-secret versioned service/tool definitions |
109
+ | GET /api/mcp/capabilities/ | Delegated user JWT | Current product permission discovery |
110
+ | POST /mcp | Delegated user JWT | Stateless MCP tools |
111
+ | GET /api/badana/v1/catalog/ | Dedicated machine JWT | Assignable organizations and roles |
112
+ | POST /api/badana/v1/provisioning/ | Dedicated machine JWT | Product user provisioning |
113
+
114
+ 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.
115
+
116
+ ## CLI and cross-language integration
117
+
118
+ ```bash
119
+ badana-mcp --version
120
+ badana-mcp check --sdk examples.standalone:sdk
121
+ badana-mcp manifest --sdk examples.standalone:sdk
122
+ ```
123
+
124
+ 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.
125
+
126
+ ```bash
127
+ # Configure the environment using examples/sidecar.env.example as a guide.
128
+ badana-mcp check --sidecar examples/sidecar.toml
129
+ badana-mcp serve --sidecar examples/sidecar.toml --host 127.0.0.1 --port 8000
130
+ ```
131
+
132
+ 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.
133
+
134
+ ## Security model
135
+
136
+ - Validate RS256 signatures using trusted configured HTTPS JWKS, issuer, exclusive audience, access-token type, client allowlist, subject, scope and token lifetime.
137
+ - Resolve local user identity and organization membership for each invocation. Never infer identity from username or email.
138
+ - Business authorization remains the product's responsibility. The SDK requires an explicit authorization adapter and checks declared permission names before execution.
139
+ - Control and user tokens have different audience, scope, client allowlists and explicitly pinned machine subjects. A product machine token must never authorize user tools.
140
+ - Writes are disabled by default; implement the product's transactional idempotency adapter before enabling them.
141
+ - 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.
142
+ - 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.
143
+ - 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.
144
+ - Audit logger emits identity, operation, request ID, result status and organization, not tokens, arguments or exception details.
145
+
146
+ 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.
147
+
148
+ ## Development
149
+
150
+ ```bash
151
+ python -m pip install -e '.[test]'
152
+ python -m pytest -q
153
+ python -m build
154
+ ```
155
+
156
+ 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.
@@ -0,0 +1,127 @@
1
+ # Badana MCP SDK
2
+
3
+ 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.
4
+
5
+ **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.
6
+
7
+ ## Install from source
8
+
9
+ ```bash
10
+ git clone https://github.com/hosseinjavadi2001/badana-mcp-sdk.git
11
+ cd badana-mcp-sdk
12
+ python -m pip install -e '.[serve]'
13
+ ```
14
+
15
+ 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.
16
+
17
+ ## Define the product
18
+
19
+ ```python
20
+ from badana_mcp import (
21
+ BadanaSDK, Capabilities, JWTConfig, JWTVerifier,
22
+ Organization, ProductAdapter, ProductConfig,
23
+ )
24
+ from badana_mcp.asgi import ASGIApplication
25
+
26
+
27
+ class Adapter(ProductAdapter):
28
+ async def resolve_user(self, identity):
29
+ # Replace with an exact issuer+subject lookup of an active local user.
30
+ return await users.find_active(identity.issuer, identity.subject)
31
+
32
+ async def capabilities(self, user):
33
+ # Return current memberships and effective product permission names.
34
+ return await permissions.get_capabilities(user)
35
+
36
+ async def authorize(self, context, tool, arguments):
37
+ # Product-owned tool AND resource/record authorization.
38
+ return await permissions.can_execute(
39
+ context.user, context.organization, tool, arguments
40
+ )
41
+
42
+
43
+ config = ProductConfig("erp", "Example ERP", "erp-main")
44
+ verifier = JWTVerifier(JWTConfig.keycloak(
45
+ issuer="https://identity.example/realms/example",
46
+ audience=config.audience,
47
+ required_scope=config.access_scope,
48
+ allowed_clients=frozenset({"https://gateway.example/mcp"}),
49
+ ))
50
+ sdk = BadanaSDK(config, Adapter(), verifier)
51
+
52
+
53
+ @sdk.tool(permissions=["projects.view"], read_only=True)
54
+ async def list_projects(context, limit: int = 20):
55
+ """List projects in the selected organization."""
56
+ return await projects.list_for(context.user, context.organization.id, limit)
57
+
58
+
59
+ app = ASGIApplication(sdk, allowed_hosts=["erp.example"])
60
+ ```
61
+
62
+ 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.
63
+
64
+ ```bash
65
+ export EXAMPLE_ISSUER=https://identity.example/realms/example
66
+ export EXAMPLE_EXCHANGE_CLIENTS=https://gateway.example/mcp
67
+ export EXAMPLE_USER_SUBJECT=replace-with-real-subject
68
+ uvicorn examples.standalone:app --host 127.0.0.1 --port 8000
69
+ ```
70
+
71
+ 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.
72
+
73
+ ## Endpoints
74
+
75
+ | Endpoint | Authentication | Purpose |
76
+ | --- | --- | --- |
77
+ | GET /health/live | Public | Process liveness |
78
+ | GET /health/ready | Public | Adapter readiness |
79
+ | GET /api/mcp/manifest/ | Public | Non-secret versioned service/tool definitions |
80
+ | GET /api/mcp/capabilities/ | Delegated user JWT | Current product permission discovery |
81
+ | POST /mcp | Delegated user JWT | Stateless MCP tools |
82
+ | GET /api/badana/v1/catalog/ | Dedicated machine JWT | Assignable organizations and roles |
83
+ | POST /api/badana/v1/provisioning/ | Dedicated machine JWT | Product user provisioning |
84
+
85
+ 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.
86
+
87
+ ## CLI and cross-language integration
88
+
89
+ ```bash
90
+ badana-mcp --version
91
+ badana-mcp check --sdk examples.standalone:sdk
92
+ badana-mcp manifest --sdk examples.standalone:sdk
93
+ ```
94
+
95
+ 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.
96
+
97
+ ```bash
98
+ # Configure the environment using examples/sidecar.env.example as a guide.
99
+ badana-mcp check --sidecar examples/sidecar.toml
100
+ badana-mcp serve --sidecar examples/sidecar.toml --host 127.0.0.1 --port 8000
101
+ ```
102
+
103
+ 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.
104
+
105
+ ## Security model
106
+
107
+ - Validate RS256 signatures using trusted configured HTTPS JWKS, issuer, exclusive audience, access-token type, client allowlist, subject, scope and token lifetime.
108
+ - Resolve local user identity and organization membership for each invocation. Never infer identity from username or email.
109
+ - Business authorization remains the product's responsibility. The SDK requires an explicit authorization adapter and checks declared permission names before execution.
110
+ - Control and user tokens have different audience, scope, client allowlists and explicitly pinned machine subjects. A product machine token must never authorize user tools.
111
+ - Writes are disabled by default; implement the product's transactional idempotency adapter before enabling them.
112
+ - 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.
113
+ - 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.
114
+ - 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.
115
+ - Audit logger emits identity, operation, request ID, result status and organization, not tokens, arguments or exception details.
116
+
117
+ 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.
118
+
119
+ ## Development
120
+
121
+ ```bash
122
+ python -m pip install -e '.[test]'
123
+ python -m pytest -q
124
+ python -m build
125
+ ```
126
+
127
+ 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.
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "badana-mcp-sdk"
7
+ version = "0.2.0"
8
+ description = "Framework-independent Python SDK for secure MCP product integrations"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ keywords = ["mcp", "oauth2", "keycloak", "multi-tenant", "sdk"]
13
+ requires-python = ">=3.11"
14
+ dependencies = [
15
+ "PyJWT[crypto]>=2.15.1,<3",
16
+ "httpx>=0.28,<1",
17
+ "jsonschema>=4.23,<5",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 3 - Alpha",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Typing :: Typed",
26
+ ]
27
+
28
+ [project.optional-dependencies]
29
+ serve = ["uvicorn>=0.34,<1"]
30
+ test = ["pytest>=8,<10", "pytest-asyncio>=0.25,<2", "mcp>=1.30,<2", "uvicorn>=0.34,<1", "build>=1.2,<2"]
31
+
32
+ [project.scripts]
33
+ badana-mcp = "badana_mcp.cli:main"
34
+
35
+ [project.urls]
36
+ Repository = "https://github.com/hosseinjavadi2001/badana-mcp-sdk"
37
+
38
+ [tool.setuptools.packages.find]
39
+ where = ["src"]
40
+
41
+ [tool.setuptools.package-data]
42
+ badana_mcp = ["py.typed"]
43
+
44
+ [tool.pytest.ini_options]
45
+ asyncio_mode = "auto"
46
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,13 @@
1
+ """Public API of the framework-independent Badana MCP SDK."""
2
+ from .adapters import Capabilities, ControlAdapter, ControlRequest, Mutation, Organization, ProductAdapter, ToolContext
3
+ from .auth import Identity, JWTVerifier, Principal
4
+ from .config import JWTConfig, ProductConfig
5
+ from .core import BadanaSDK, VERSION
6
+ from .settings import SDKSettings
7
+ from .errors import AuthenticationError, Conflict, Forbidden, InvalidInput, SDKError, Unavailable
8
+
9
+ __version__ = VERSION
10
+ __all__ = ["BadanaSDK","JWTConfig","JWTVerifier","ProductConfig","Identity","Principal",
11
+ "Capabilities","Organization","ProductAdapter","ControlAdapter","ControlRequest",
12
+ "Mutation","ToolContext","SDKError","AuthenticationError","Conflict","Forbidden",
13
+ "InvalidInput","Unavailable","SDKSettings"]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,96 @@
1
+ """Product-owned identity, business permissions, and transactional mutation interfaces."""
2
+ from abc import ABC, abstractmethod
3
+ from collections.abc import Awaitable, Callable
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ from .auth import Identity, Principal
8
+ from .errors import Forbidden
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Organization:
13
+ id: str
14
+ name: str
15
+ permissions: frozenset[str]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Capabilities:
20
+ permissions: frozenset[str] = frozenset()
21
+ organizations: tuple[Organization, ...] = ()
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class ToolContext:
26
+ principal: Principal
27
+ user: Any
28
+ organization: Organization | None
29
+ request_id: str
30
+ idempotency_key: str | None = None
31
+ # Product transaction/execution context; not serialized to the client.
32
+ transaction: Any = None
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Mutation:
37
+ namespace: str
38
+ key: str
39
+ fingerprint: str
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class ControlRequest:
44
+ principal: Principal
45
+ operation: str
46
+ identity: Identity
47
+ payload: dict
48
+ actor_id: str
49
+ request_id: str
50
+ mutation: Mutation
51
+
52
+
53
+ class ProductAdapter(ABC):
54
+ @abstractmethod
55
+ async def resolve_user(self, identity: Identity) -> Any | None:
56
+ """Return an active local user mapped to the exact (issuer, subject), else None."""
57
+
58
+ @abstractmethod
59
+ async def capabilities(self, user: Any) -> Capabilities:
60
+ """Return only active memberships and effective product permissions."""
61
+
62
+ @abstractmethod
63
+ async def authorize(self, context: ToolContext, tool: str, arguments: dict) -> bool:
64
+ """Check tool and record-specific business access. Must return literal True."""
65
+
66
+ async def ready(self) -> bool:
67
+ return True
68
+
69
+ async def write_once(self, context: ToolContext, mutation: Mutation,
70
+ execute: Callable[[ToolContext], Awaitable[Any]]) -> Any:
71
+ """Implement persistent atomic idempotency in the product's business transaction.
72
+
73
+ Same key+fingerprint -> same result; same key+different fingerprint -> Conflict.
74
+ Call execute with a transaction-bound context. Revalidate authorization inside
75
+ the transaction before mutation. Store the result in that transaction.
76
+ The default deliberately disables writes.
77
+ """
78
+ raise Forbidden()
79
+
80
+
81
+ class ControlAdapter(ABC):
82
+ @abstractmethod
83
+ async def catalog(self, principal: Principal) -> dict:
84
+ """Return only organizations and roles assignable by this machine principal."""
85
+
86
+ @abstractmethod
87
+ async def authorize(self, request: ControlRequest) -> bool:
88
+ """Explicit delegated product administrative policy. No email-based linking."""
89
+
90
+ @abstractmethod
91
+ async def provision_once(self, request: ControlRequest) -> str:
92
+ """Perform authorized provisioning atomically with persistent idempotency.
93
+
94
+ Recheck admin policy, identity collisions, tenant and role bounds in the same
95
+ transaction as the mutation; store key/fingerprint/result. Return local user ID.
96
+ """