cortexhub 2.0.0__tar.gz → 2.0.1__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.
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: cortexhub
3
+ Version: 2.0.1
4
+ Summary: MCP gateway client for CortexHub programmatic agent access.
5
+ Project-URL: Homepage, https://cortexhub.ai
6
+ Project-URL: Documentation, https://docs.cortexhub.ai
7
+ Author-email: CortexHub <hello@cortexhub.ai>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,ai,governance,mcp,programmatic
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+
23
+ # cortexhub
24
+
25
+ Official Python SDK for CortexHub programmatic MCP access.
26
+
27
+ [Documentation](https://docs.cortexhub.ai/docs/sdks/overview)
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install cortexhub
33
+ ```
34
+
35
+ ## Credentials
36
+
37
+ Create an MCP OAuth client in CortexHub Cloud: **Account** → **MCP API access** → copy `client_id` and `client_secret`.
38
+
39
+ ## Usage
40
+
41
+ ```python
42
+ from cortexhub import Cortexhub
43
+
44
+ session = Cortexhub().session(
45
+ agent="helpdesk-bot",
46
+ mcp_session_id="chat-42", # optional: separate conversations in Cloud
47
+ )
48
+ # session.mcp.url and session.mcp.headers → pass to your MCP transport
49
+ ```
50
+
51
+ ## Configuration
52
+
53
+ | Variable | Default | Purpose |
54
+ |---|---|---|
55
+ | `CORTEXHUB_URL` | `https://mcp.cortexhub.ai` | MCP gateway and OAuth token base URL |
56
+ | `CORTEXHUB_CLIENT_ID` | — | MCP OAuth client id |
57
+ | `CORTEXHUB_CLIENT_SECRET` | — | MCP OAuth client secret |
58
+
59
+ Token exchange: `POST {CORTEXHUB_URL}/v1/mcp/oauth/token` (`client_credentials` or `refresh_token`).
60
+
61
+ ## License
62
+
63
+ MIT.
@@ -0,0 +1,41 @@
1
+ # cortexhub
2
+
3
+ Official Python SDK for CortexHub programmatic MCP access.
4
+
5
+ [Documentation](https://docs.cortexhub.ai/docs/sdks/overview)
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install cortexhub
11
+ ```
12
+
13
+ ## Credentials
14
+
15
+ Create an MCP OAuth client in CortexHub Cloud: **Account** → **MCP API access** → copy `client_id` and `client_secret`.
16
+
17
+ ## Usage
18
+
19
+ ```python
20
+ from cortexhub import Cortexhub
21
+
22
+ session = Cortexhub().session(
23
+ agent="helpdesk-bot",
24
+ mcp_session_id="chat-42", # optional: separate conversations in Cloud
25
+ )
26
+ # session.mcp.url and session.mcp.headers → pass to your MCP transport
27
+ ```
28
+
29
+ ## Configuration
30
+
31
+ | Variable | Default | Purpose |
32
+ |---|---|---|
33
+ | `CORTEXHUB_URL` | `https://mcp.cortexhub.ai` | MCP gateway and OAuth token base URL |
34
+ | `CORTEXHUB_CLIENT_ID` | — | MCP OAuth client id |
35
+ | `CORTEXHUB_CLIENT_SECRET` | — | MCP OAuth client secret |
36
+
37
+ Token exchange: `POST {CORTEXHUB_URL}/v1/mcp/oauth/token` (`client_credentials` or `refresh_token`).
38
+
39
+ ## License
40
+
41
+ MIT.
@@ -1,14 +1,14 @@
1
1
  [project]
2
2
  name = "cortexhub"
3
- version = "2.0.0"
4
- description = "MCP gateway client for CortexHub — simple and verified runtime sessions."
3
+ version = "2.0.1"
4
+ description = "MCP gateway client for CortexHub programmatic agent access."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
7
7
  license = { text = "MIT" }
8
8
  authors = [
9
9
  { name = "CortexHub", email = "hello@cortexhub.ai" }
10
10
  ]
11
- keywords = ["ai", "agents", "mcp", "cxh_gateway", "governance"]
11
+ keywords = ["ai", "agents", "mcp" , "programmatic", "governance"]
12
12
  classifiers = [
13
13
  "Development Status :: 5 - Production/Stable",
14
14
  "Intended Audience :: Developers",
@@ -30,7 +30,6 @@ dependencies = []
30
30
  [project.urls]
31
31
  Homepage = "https://cortexhub.ai"
32
32
  Documentation = "https://docs.cortexhub.ai"
33
- Examples = "https://github.com/CortexHub-AI/examples/"
34
33
 
35
34
  [build-system]
36
35
  requires = ["hatchling"]
@@ -0,0 +1,30 @@
1
+ """cortexhub - programmatic MCP access for CortexHub.
2
+
3
+ ```python
4
+ from cortexhub import Cortexhub
5
+
6
+ session = Cortexhub().session(agent="helpdesk-bot", mcp_session_id="chat-1")
7
+ # session.mcp.url and session.mcp.headers → your MCP transport
8
+ ```
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from .client import Cortexhub
14
+ from .errors import APIError, AuthenticationError, ConfigurationError, CortexhubError
15
+ from .mcp_oauth import CortexhubMcpOAuthClient, McpOAuthSession, McpOAuthToken
16
+ from .session import SessionMcp
17
+
18
+ __version__ = "2.1.0"
19
+ __all__ = [
20
+ "Cortexhub",
21
+ "CortexhubMcpOAuthClient",
22
+ "McpOAuthSession",
23
+ "McpOAuthToken",
24
+ "SessionMcp",
25
+ "CortexhubError",
26
+ "ConfigurationError",
27
+ "AuthenticationError",
28
+ "APIError",
29
+ "__version__",
30
+ ]
@@ -0,0 +1,11 @@
1
+ """SDK base URL configuration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ DEFAULT_URL = "https://mcp.cortexhub.ai"
8
+
9
+
10
+ def base_url() -> str:
11
+ return (os.environ.get("CORTEXHUB_URL") or DEFAULT_URL).rstrip("/")
@@ -0,0 +1,59 @@
1
+ """``Cortexhub`` - programmatic MCP access via member MCP OAuth."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ from .errors import ConfigurationError
8
+ from .mcp_oauth import CortexhubMcpOAuthClient, McpOAuthSession
9
+
10
+
11
+ class Cortexhub(CortexhubMcpOAuthClient):
12
+ """MCP gateway client using a member MCP OAuth client.
13
+
14
+ Environment variables (optional):
15
+
16
+ - ``CORTEXHUB_CLIENT_ID``
17
+ - ``CORTEXHUB_CLIENT_SECRET``
18
+ - ``CORTEXHUB_URL`` (default ``https://mcp.cortexhub.ai``)
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ *,
24
+ client_id: str | None = None,
25
+ client_secret: str | None = None,
26
+ token_url: str | None = None,
27
+ ) -> None:
28
+ resolved_id = (client_id or os.environ.get("CORTEXHUB_CLIENT_ID") or "").strip()
29
+ resolved_secret = (
30
+ client_secret or os.environ.get("CORTEXHUB_CLIENT_SECRET") or ""
31
+ ).strip()
32
+ if not resolved_id or not resolved_secret:
33
+ raise ConfigurationError(
34
+ "Missing OAuth client credentials. Pass client_id= and client_secret= "
35
+ "or set CORTEXHUB_CLIENT_ID and CORTEXHUB_CLIENT_SECRET."
36
+ )
37
+ kwargs: dict[str, str] = {
38
+ "client_id": resolved_id,
39
+ "client_secret": resolved_secret,
40
+ }
41
+ if token_url:
42
+ kwargs["token_url"] = token_url.strip()
43
+ super().__init__(**kwargs)
44
+
45
+ def session(
46
+ self,
47
+ *,
48
+ agent: str,
49
+ mcp_session_id: str | None = None,
50
+ refresh: bool = False,
51
+ ) -> McpOAuthSession:
52
+ """Return MCP headers for ``agent`` (required on every programmatic call)."""
53
+ return super().session(
54
+ agent=agent, mcp_session_id=mcp_session_id, refresh=refresh
55
+ )
56
+
57
+ def __repr__(self) -> str:
58
+ prefix = self.client_id[:12] + "…" if len(self.client_id) > 12 else self.client_id
59
+ return f"Cortexhub(client_id={prefix!r})"
@@ -1,4 +1,4 @@
1
- """Minimal error hierarchy for the cortexhub SDK."""
1
+ """Error types for the MCP gateway Python SDK (``cortexhub`` on PyPI)."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
@@ -8,15 +8,15 @@ class CortexhubError(Exception):
8
8
 
9
9
 
10
10
  class ConfigurationError(CortexhubError):
11
- """The SDK was initialised without a usable API key."""
11
+ """Missing or invalid MCP OAuth client credentials at construction."""
12
12
 
13
13
 
14
14
  class AuthenticationError(CortexhubError):
15
- """Control-plane API rejected the API key."""
15
+ """MCP OAuth token endpoint rejected the client credentials (HTTP 401)."""
16
16
 
17
17
 
18
18
  class APIError(CortexhubError):
19
- """Control-plane API returned a non-success response."""
19
+ """MCP OAuth token endpoint returned a non-success HTTP response."""
20
20
 
21
21
  def __init__(self, message: str, *, status: int | None = None) -> None:
22
22
  super().__init__(message)
@@ -0,0 +1,142 @@
1
+ """Member MCP OAuth programmatic client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+ from ._config import base_url
13
+ from .errors import APIError, AuthenticationError
14
+ from .session import SessionMcp
15
+
16
+ _AGENT_HEADER = "X-CortexHub-Agent"
17
+ _BEARER_HEADER = "Authorization"
18
+
19
+
20
+ @dataclass
21
+ class McpOAuthToken:
22
+ access_token: str
23
+ token_type: str
24
+ expires_in: int
25
+ refresh_token: str | None = None
26
+ scope: str = ""
27
+
28
+
29
+ @dataclass
30
+ class McpOAuthSession:
31
+ """MCP connection using Bearer JWT + optional agent and session headers."""
32
+
33
+ access_token: str
34
+ agent: str | None = None
35
+ mcp_session_id: str | None = None
36
+ mcp: SessionMcp = field(init=False)
37
+
38
+ def __post_init__(self) -> None:
39
+ headers: dict[str, str] = {
40
+ _BEARER_HEADER: f"Bearer {self.access_token}",
41
+ }
42
+ if self.agent:
43
+ headers[_AGENT_HEADER] = self.agent
44
+ if self.mcp_session_id:
45
+ headers["Mcp-Session-Id"] = self.mcp_session_id
46
+ self.mcp = SessionMcp(url=f"{base_url()}/v1/mcp", headers=headers)
47
+
48
+
49
+ class CortexhubMcpOAuthClient:
50
+ """Obtain MCP OAuth tokens via client_credentials / refresh_token."""
51
+
52
+ def __init__(
53
+ self,
54
+ *,
55
+ client_id: str,
56
+ client_secret: str,
57
+ token_url: str | None = None,
58
+ ) -> None:
59
+ if not client_id or not client_secret:
60
+ raise ValueError("client_id and client_secret are required.")
61
+ self.client_id = client_id
62
+ self.client_secret = client_secret
63
+ self.token_url = (token_url or f"{base_url()}/v1/mcp/oauth/token").strip()
64
+ self._refresh_token: str | None = None
65
+
66
+ def fetch_token(self, *, refresh: bool = False) -> McpOAuthToken:
67
+ """Mint or refresh an access token."""
68
+ if refresh:
69
+ if not self._refresh_token:
70
+ raise ValueError("No refresh_token stored; call fetch_token() first.")
71
+ body = {
72
+ "grant_type": "refresh_token",
73
+ "client_id": self.client_id,
74
+ "client_secret": self.client_secret,
75
+ "refresh_token": self._refresh_token,
76
+ }
77
+ else:
78
+ body = {
79
+ "grant_type": "client_credentials",
80
+ "client_id": self.client_id,
81
+ "client_secret": self.client_secret,
82
+ }
83
+ data = _post_form(self.token_url, body)
84
+ token = McpOAuthToken(
85
+ access_token=str(data["access_token"]),
86
+ token_type=str(data.get("token_type") or "Bearer"),
87
+ expires_in=int(data.get("expires_in") or 0),
88
+ refresh_token=data.get("refresh_token"),
89
+ scope=str(data.get("scope") or ""),
90
+ )
91
+ if token.refresh_token:
92
+ self._refresh_token = token.refresh_token
93
+ return token
94
+
95
+ def session(
96
+ self,
97
+ *,
98
+ agent: str,
99
+ mcp_session_id: str | None = None,
100
+ refresh: bool = False,
101
+ ) -> McpOAuthSession:
102
+ """Return MCP headers for ``agent`` (required on every programmatic call).
103
+
104
+ Pass ``mcp_session_id`` (your chat or conversation id) to group tool
105
+ activity into separate rows in CortexHub Cloud.
106
+ """
107
+ if not agent or not agent.strip():
108
+ raise ValueError("agent= is required for programmatic MCP OAuth.")
109
+ token = self.fetch_token(refresh=refresh)
110
+ session_id = (mcp_session_id or "").strip() or None
111
+ return McpOAuthSession(
112
+ access_token=token.access_token,
113
+ agent=agent.strip(),
114
+ mcp_session_id=session_id,
115
+ )
116
+
117
+
118
+ def _post_form(url: str, fields: dict[str, str]) -> dict[str, Any]:
119
+ encoded = urllib.parse.urlencode(fields).encode("utf-8")
120
+ req = urllib.request.Request(
121
+ url,
122
+ data=encoded,
123
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
124
+ method="POST",
125
+ )
126
+ try:
127
+ with urllib.request.urlopen(req, timeout=30) as resp:
128
+ raw = resp.read().decode("utf-8")
129
+ except urllib.error.HTTPError as exc:
130
+ detail = exc.read().decode("utf-8", errors="replace")
131
+ if exc.code == 401:
132
+ raise AuthenticationError(
133
+ f"MCP OAuth token request unauthorized: {detail}"
134
+ ) from exc
135
+ raise APIError(
136
+ f"MCP OAuth token request failed ({exc.code}): {detail}",
137
+ status=exc.code,
138
+ ) from exc
139
+ parsed = json.loads(raw)
140
+ if not isinstance(parsed, dict):
141
+ raise RuntimeError("Token endpoint returned non-object JSON.")
142
+ return parsed
@@ -0,0 +1,13 @@
1
+ """Session types for MCP programmatic OAuth."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class SessionMcp:
10
+ """MCP streamable-HTTP connection details for your framework."""
11
+
12
+ url: str
13
+ headers: dict[str, str] = field(default_factory=dict)
cortexhub-2.0.0/PKG-INFO DELETED
@@ -1,90 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: cortexhub
3
- Version: 2.0.0
4
- Summary: MCP gateway client for CortexHub — simple and verified runtime sessions.
5
- Project-URL: Homepage, https://cortexhub.ai
6
- Project-URL: Documentation, https://docs.cortexhub.ai
7
- Project-URL: Examples, https://github.com/CortexHub-AI/examples/
8
- Author-email: CortexHub <hello@cortexhub.ai>
9
- License: MIT
10
- License-File: LICENSE
11
- Keywords: agents,ai,cxh_gateway,governance,mcp
12
- Classifier: Development Status :: 5 - Production/Stable
13
- Classifier: Intended Audience :: Developers
14
- Classifier: License :: OSI Approved :: MIT License
15
- Classifier: Programming Language :: Python :: 3
16
- Classifier: Programming Language :: Python :: 3.10
17
- Classifier: Programming Language :: Python :: 3.11
18
- Classifier: Programming Language :: Python :: 3.12
19
- Classifier: Programming Language :: Python :: 3.13
20
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
- Requires-Python: >=3.10
22
- Description-Content-Type: text/markdown
23
-
24
- # cortexhub
25
-
26
- Official Python SDK for the CortexHub MCP gateway and runtime-session control plane.
27
-
28
- [Documentation](https://docs.cortexhub.ai)
29
-
30
- ## Install
31
-
32
- ```bash
33
- pip install cortexhub
34
- ```
35
-
36
- ## Simple mode (declared end-user)
37
-
38
- For personal MCP clients or server agents that do not need verified end-user identity:
39
-
40
- ```python
41
- from cortexhub import Cortexhub
42
-
43
- cx = Cortexhub() # reads CORTEXHUB_API_KEY
44
- session = cx.session(user_id="user_123")
45
-
46
- print(session.mcp.url) # https://mcp.cortexhub.ai/v1/mcp
47
- print(session.mcp.headers) # X-API-Key + X-CortexHub-End-User-Subject
48
- ```
49
-
50
- Hand `session.mcp.url` and `session.mcp.headers` to Claude Agent SDK, OpenAI Agents, LangGraph, or any MCP client.
51
-
52
- ## Verified mode (runtime sessions)
53
-
54
- When policies require verified end-user attribution:
55
-
56
- ```python
57
- from cortexhub import Cortexhub, CortexhubPlatform
58
-
59
- # 1. Your trusted backend (tenant API key) binds the end user once.
60
- platform = CortexhubPlatform() # CORTEXHUB_PLATFORM_API_KEY
61
- ctx = platform.create_context(
62
- agent_id="cxh_agent_…",
63
- end_user_subject="user_123",
64
- )
65
-
66
- # 2. Your agent runtime mints a short-lived bearer.
67
- agent = Cortexhub() # agent API key
68
- runtime = agent.open_runtime(ctx.id)
69
-
70
- print(runtime.mcp.headers) # Authorization: Bearer cxh_rs_…
71
- ```
72
-
73
- Resume after reconnect:
74
-
75
- ```python
76
- runtime = agent.resume_runtime(runtime.session_id)
77
- ```
78
-
79
- ## Configuration
80
-
81
- | Variable | Purpose |
82
- |---|---|
83
- | `CORTEXHUB_API_KEY` | Agent API key for `Cortexhub()` |
84
- | `CORTEXHUB_PLATFORM_API_KEY` | Tenant or org key for `CortexhubPlatform()` |
85
-
86
- Gateway URL is fixed at `https://mcp.cortexhub.ai/v1/mcp`. Control plane is `https://api.cortexhub.ai`.
87
-
88
- ## License
89
-
90
- MIT.
cortexhub-2.0.0/README.md DELETED
@@ -1,67 +0,0 @@
1
- # cortexhub
2
-
3
- Official Python SDK for the CortexHub MCP gateway and runtime-session control plane.
4
-
5
- [Documentation](https://docs.cortexhub.ai)
6
-
7
- ## Install
8
-
9
- ```bash
10
- pip install cortexhub
11
- ```
12
-
13
- ## Simple mode (declared end-user)
14
-
15
- For personal MCP clients or server agents that do not need verified end-user identity:
16
-
17
- ```python
18
- from cortexhub import Cortexhub
19
-
20
- cx = Cortexhub() # reads CORTEXHUB_API_KEY
21
- session = cx.session(user_id="user_123")
22
-
23
- print(session.mcp.url) # https://mcp.cortexhub.ai/v1/mcp
24
- print(session.mcp.headers) # X-API-Key + X-CortexHub-End-User-Subject
25
- ```
26
-
27
- Hand `session.mcp.url` and `session.mcp.headers` to Claude Agent SDK, OpenAI Agents, LangGraph, or any MCP client.
28
-
29
- ## Verified mode (runtime sessions)
30
-
31
- When policies require verified end-user attribution:
32
-
33
- ```python
34
- from cortexhub import Cortexhub, CortexhubPlatform
35
-
36
- # 1. Your trusted backend (tenant API key) binds the end user once.
37
- platform = CortexhubPlatform() # CORTEXHUB_PLATFORM_API_KEY
38
- ctx = platform.create_context(
39
- agent_id="cxh_agent_…",
40
- end_user_subject="user_123",
41
- )
42
-
43
- # 2. Your agent runtime mints a short-lived bearer.
44
- agent = Cortexhub() # agent API key
45
- runtime = agent.open_runtime(ctx.id)
46
-
47
- print(runtime.mcp.headers) # Authorization: Bearer cxh_rs_…
48
- ```
49
-
50
- Resume after reconnect:
51
-
52
- ```python
53
- runtime = agent.resume_runtime(runtime.session_id)
54
- ```
55
-
56
- ## Configuration
57
-
58
- | Variable | Purpose |
59
- |---|---|
60
- | `CORTEXHUB_API_KEY` | Agent API key for `Cortexhub()` |
61
- | `CORTEXHUB_PLATFORM_API_KEY` | Tenant or org key for `CortexhubPlatform()` |
62
-
63
- Gateway URL is fixed at `https://mcp.cortexhub.ai/v1/mcp`. Control plane is `https://api.cortexhub.ai`.
64
-
65
- ## License
66
-
67
- MIT.
@@ -1,47 +0,0 @@
1
- """cortexhub - MCP gateway client for CortexHub agents.
2
-
3
- Quickstart (simple mode)::
4
-
5
- from cortexhub import Cortexhub
6
-
7
- cx = Cortexhub() # CORTEXHUB_API_KEY
8
- session = cx.session(user_id="user_123")
9
- mcp_url = session.mcp.url
10
- mcp_headers = session.mcp.headers
11
-
12
- Verified attribution (platform backend + agent runtime)::
13
-
14
- from cortexhub import Cortexhub, CortexhubPlatform
15
-
16
- platform = CortexhubPlatform() # CORTEXHUB_PLATFORM_API_KEY (tenant key)
17
- ctx = platform.create_context(
18
- agent_id="cxh_agent_…",
19
- end_user_subject="user_123",
20
- )
21
-
22
- agent = Cortexhub() # agent key
23
- runtime = agent.open_runtime(ctx.id)
24
- mcp_headers = runtime.mcp.headers # Authorization: Bearer cxh_rs_…
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- from .client import Cortexhub
30
- from .errors import APIError, AuthenticationError, ConfigurationError, CortexhubError
31
- from .platform import CortexhubPlatform, RuntimeContext
32
- from .session import RuntimeSession, Session, SessionMcp
33
-
34
- __version__ = "2.0.0"
35
- __all__ = [
36
- "Cortexhub",
37
- "CortexhubPlatform",
38
- "RuntimeContext",
39
- "RuntimeSession",
40
- "Session",
41
- "SessionMcp",
42
- "CortexhubError",
43
- "ConfigurationError",
44
- "AuthenticationError",
45
- "APIError",
46
- "__version__",
47
- ]
@@ -1,64 +0,0 @@
1
- """Minimal JSON HTTP helpers for the CortexHub control-plane API."""
2
-
3
- from __future__ import annotations
4
-
5
- import json
6
- import urllib.error
7
- import urllib.request
8
- from typing import Any
9
-
10
- from .errors import APIError, AuthenticationError
11
-
12
-
13
- def post_envelope(
14
- url: str,
15
- *,
16
- api_key: str,
17
- body: dict[str, Any],
18
- timeout: float = 30.0,
19
- ) -> dict[str, Any]:
20
- payload = json.dumps(body).encode("utf-8")
21
- request = urllib.request.Request(
22
- url,
23
- data=payload,
24
- method="POST",
25
- headers={
26
- "Content-Type": "application/json",
27
- "Accept": "application/json",
28
- "X-API-Key": api_key,
29
- },
30
- )
31
- try:
32
- with urllib.request.urlopen(request, timeout=timeout) as response:
33
- raw = response.read().decode("utf-8")
34
- except urllib.error.HTTPError as exc:
35
- detail = _read_error_body(exc)
36
- if exc.code in (401, 403):
37
- raise AuthenticationError(detail or f"HTTP {exc.code}") from exc
38
- raise APIError(detail or f"HTTP {exc.code}", status=exc.code) from exc
39
- except urllib.error.URLError as exc:
40
- raise APIError(f"Network error: {exc.reason}") from exc
41
-
42
- parsed = json.loads(raw) if raw else {}
43
- if not isinstance(parsed, dict):
44
- raise APIError("Unexpected response shape from CortexHub API")
45
- data = parsed.get("data")
46
- if not isinstance(data, dict):
47
- raise APIError("Response missing data envelope")
48
- return data
49
-
50
-
51
- def _read_error_body(exc: urllib.error.HTTPError) -> str | None:
52
- try:
53
- raw = exc.read().decode("utf-8")
54
- except OSError:
55
- return None
56
- if not raw:
57
- return None
58
- try:
59
- parsed = json.loads(raw)
60
- except json.JSONDecodeError:
61
- return raw
62
- if isinstance(parsed, dict):
63
- return str(parsed.get("detail") or parsed.get("message") or parsed.get("title") or raw)
64
- return raw
@@ -1,82 +0,0 @@
1
- """``Cortexhub`` — agent-scoped MCP gateway client."""
2
-
3
- from __future__ import annotations
4
-
5
- import os
6
-
7
- from ._http import post_envelope
8
- from .errors import ConfigurationError
9
- from .session import RuntimeSession, Session, runtime_session_from_api
10
-
11
- _API_BASE = "https://api.cortexhub.ai"
12
-
13
-
14
- class Cortexhub:
15
- """Per-agent client (``cxh_live_a_*`` / agent API key).
16
-
17
- * **Simple mode** — ``session(user_id=...)`` returns local headers with a
18
- declared end-user subject (audit metadata only).
19
- * **Verified mode** — ``open_runtime(context_id=...)`` mints a short-lived
20
- ``cxh_rs_*`` bearer against a runtime context your platform created.
21
- """
22
-
23
- def __init__(self, api_key: str | None = None) -> None:
24
- resolved = (api_key or os.environ.get("CORTEXHUB_API_KEY") or "").strip()
25
- if not resolved:
26
- raise ConfigurationError(
27
- "Missing API key. Pass api_key=... to Cortexhub() "
28
- "or set the CORTEXHUB_API_KEY environment variable."
29
- )
30
- self.api_key: str = resolved
31
-
32
- def session(self, user_id: str) -> Session:
33
- """Simple mode — local session with declared end-user attribution."""
34
- return Session(api_key=self.api_key, user_id=user_id)
35
-
36
- create = session
37
-
38
- def open_runtime(self, context_id: str) -> RuntimeSession:
39
- """Verified mode — mint a runtime session from an existing context."""
40
- if not context_id.strip():
41
- raise ValueError("context_id is required.")
42
- data = post_envelope(
43
- f"{_API_BASE}/v1/sessions",
44
- api_key=self.api_key,
45
- body={"context_id": context_id.strip()},
46
- )
47
- return runtime_session_from_api(data)
48
-
49
- def resume_runtime(self, session_id: str) -> RuntimeSession:
50
- """Re-mint the bearer for an active runtime session (token rotation)."""
51
- if not session_id.strip():
52
- raise ValueError("session_id is required.")
53
- data = post_envelope(
54
- f"{_API_BASE}/v1/sessions/{session_id.strip()}/resume",
55
- api_key=self.api_key,
56
- body={},
57
- )
58
- return runtime_session_from_api(data)
59
-
60
- def join_runtime(
61
- self,
62
- *,
63
- context_id: str,
64
- parent_session_id: str,
65
- handoff_reason: str,
66
- session_handle: str = "join",
67
- ) -> RuntimeSession:
68
- """Multi-agent handoff — join an existing runtime context."""
69
- data = post_envelope(
70
- f"{_API_BASE}/v1/sessions/{session_handle.strip()}/join",
71
- api_key=self.api_key,
72
- body={
73
- "context_id": context_id.strip(),
74
- "parent_session_id": parent_session_id.strip(),
75
- "handoff_reason": handoff_reason.strip(),
76
- },
77
- )
78
- return runtime_session_from_api(data)
79
-
80
- def __repr__(self) -> str:
81
- prefix = self.api_key[:15] + "…" if len(self.api_key) > 15 else "…"
82
- return f"Cortexhub(api_key={prefix!r})"
@@ -1,82 +0,0 @@
1
- """Platform client — mint runtime contexts with a tenant or org API key."""
2
-
3
- from __future__ import annotations
4
-
5
- from dataclasses import dataclass
6
- from typing import Any
7
-
8
- from ._http import post_envelope
9
- from .errors import ConfigurationError
10
-
11
- _API_BASE = "https://api.cortexhub.ai"
12
-
13
-
14
- @dataclass(frozen=True)
15
- class RuntimeContext:
16
- """A verified end-user runtime context (``cxh_rtc_*``)."""
17
-
18
- id: str
19
- org_id: str
20
- tenant_id: str
21
- agent_id: str
22
- end_user_subject: str | None
23
- user_id: str | None
24
-
25
-
26
- class CortexhubPlatform:
27
- """Control-plane client for partner backends (tenant or org API key).
28
-
29
- Use this on your trusted server to bind end-user identity before the
30
- agent runtime opens a verified MCP session.
31
- """
32
-
33
- def __init__(self, api_key: str | None = None) -> None:
34
- import os
35
-
36
- resolved = (api_key or os.environ.get("CORTEXHUB_PLATFORM_API_KEY") or "").strip()
37
- if not resolved:
38
- raise ConfigurationError(
39
- "Missing platform API key. Pass api_key=... or set "
40
- "CORTEXHUB_PLATFORM_API_KEY (tenant or org key)."
41
- )
42
- self._api_key = resolved
43
-
44
- def create_context(
45
- self,
46
- *,
47
- agent_id: str,
48
- end_user_subject: str,
49
- user_id: str | None = None,
50
- external_context_id: str | None = None,
51
- metadata: dict[str, Any] | None = None,
52
- ) -> RuntimeContext:
53
- """Create (or idempotently fetch) a runtime context for one end user."""
54
- if not agent_id.strip():
55
- raise ValueError("agent_id is required.")
56
- if not end_user_subject.strip():
57
- raise ValueError("end_user_subject is required.")
58
-
59
- body: dict[str, Any] = {
60
- "agent_id": agent_id.strip(),
61
- "end_user_subject": end_user_subject.strip(),
62
- }
63
- subject_id = (user_id or end_user_subject).strip()
64
- body["user_id"] = subject_id
65
- if external_context_id:
66
- body["external_context_id"] = external_context_id.strip()
67
- if metadata:
68
- body["metadata"] = metadata
69
-
70
- data = post_envelope(
71
- f"{_API_BASE}/v1/contexts",
72
- api_key=self._api_key,
73
- body=body,
74
- )
75
- return RuntimeContext(
76
- id=str(data["id"]),
77
- org_id=str(data["org_id"]),
78
- tenant_id=str(data["tenant_id"]),
79
- agent_id=str(data["agent_id"]),
80
- end_user_subject=data.get("end_user_subject"),
81
- user_id=data.get("user_id"),
82
- )
@@ -1,83 +0,0 @@
1
- """Session objects returned by ``Cortexhub`` — simple and verified modes."""
2
-
3
- from __future__ import annotations
4
-
5
- from dataclasses import dataclass, field
6
- from datetime import datetime
7
- from typing import Any
8
-
9
- _MCP_URL = "https://mcp.cortexhub.ai/v1/mcp"
10
- _API_KEY_HEADER = "X-API-Key"
11
- _END_USER_SUBJECT_HEADER = "X-CortexHub-End-User-Subject"
12
- _BEARER_HEADER = "Authorization"
13
-
14
-
15
- @dataclass(frozen=True)
16
- class SessionMcp:
17
- """MCP streamable-HTTP connection details for your framework."""
18
-
19
- url: str
20
- headers: dict[str, str] = field(default_factory=dict)
21
-
22
-
23
- class Session:
24
- """Simple mode — agent key + declared end-user subject (non-authoritative)."""
25
-
26
- def __init__(self, *, api_key: str, user_id: str) -> None:
27
- if not user_id:
28
- raise ValueError("user_id is required.")
29
- self.user_id: str = user_id
30
- self.mode: str = "simple"
31
- self.mcp: SessionMcp = SessionMcp(
32
- url=_MCP_URL,
33
- headers={
34
- _API_KEY_HEADER: api_key,
35
- _END_USER_SUBJECT_HEADER: user_id,
36
- },
37
- )
38
-
39
- def __repr__(self) -> str:
40
- return f"Session(user_id={self.user_id!r}, mode={self.mode!r})"
41
-
42
-
43
- @dataclass(frozen=True)
44
- class RuntimeSession:
45
- """Verified mode — short-lived ``cxh_rs_*`` bearer from a runtime context."""
46
-
47
- session_id: str
48
- context_id: str
49
- token: str
50
- expires_at: datetime | None
51
- end_user_subject: str | None
52
- mcp: SessionMcp
53
- mode: str = "verified"
54
-
55
- def __repr__(self) -> str:
56
- return (
57
- f"RuntimeSession(session_id={self.session_id!r}, "
58
- f"context_id={self.context_id!r}, mode={self.mode!r})"
59
- )
60
-
61
-
62
- def runtime_session_from_api(data: dict[str, Any]) -> RuntimeSession:
63
- session = data["session"]
64
- token = str(data["token"])
65
- mcp_block = data.get("mcp") or {}
66
- url = str(mcp_block.get("url") or _MCP_URL)
67
- headers = dict(mcp_block.get("headers") or {})
68
- if _BEARER_HEADER not in headers:
69
- headers[_BEARER_HEADER] = f"Bearer {token}"
70
-
71
- expires_raw = session.get("expires_at")
72
- expires_at = None
73
- if expires_raw:
74
- expires_at = datetime.fromisoformat(str(expires_raw).replace("Z", "+00:00"))
75
-
76
- return RuntimeSession(
77
- session_id=str(session["id"]),
78
- context_id=str(session["runtime_context_id"]),
79
- token=token,
80
- expires_at=expires_at,
81
- end_user_subject=session.get("end_user_subject"),
82
- mcp=SessionMcp(url=url, headers=headers),
83
- )
File without changes
File without changes