cortexhub 1.1.0__tar.gz → 2.0.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.
@@ -0,0 +1,90 @@
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.
@@ -0,0 +1,67 @@
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,14 +1,14 @@
1
1
  [project]
2
2
  name = "cortexhub"
3
- version = "1.1.0"
4
- description = "MCP gateway client for cortexhub agents — authenticate, hand the MCP URL to your framework of choice, done."
3
+ version = "2.0.0"
4
+ description = "MCP gateway client for CortexHub — simple and verified runtime sessions."
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", "gateway", "governance"]
11
+ keywords = ["ai", "agents", "mcp", "cxh_gateway", "governance"]
12
12
  classifiers = [
13
13
  "Development Status :: 5 - Production/Stable",
14
14
  "Intended Audience :: Developers",
@@ -21,7 +21,7 @@ classifiers = [
21
21
  "Topic :: Software Development :: Libraries :: Python Modules",
22
22
  ]
23
23
 
24
- # v1 has no runtime dependencies. Construction is fully local — the SDK only
24
+ # v1 has no runtime dependencies. Construction is fully local - the SDK only
25
25
  # computes a URL and a header dict. We deliberately do NOT pull in httpx /
26
26
  # pydantic / opentelemetry / policy engine / presidio / spacy here: those used to
27
27
  # do client-side governance and that work now lives on the cortexhub gateway.
@@ -0,0 +1,47 @@
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
+ ]
@@ -0,0 +1,64 @@
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
@@ -0,0 +1,82 @@
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})"
@@ -0,0 +1,23 @@
1
+ """Minimal error hierarchy for the cortexhub SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class CortexhubError(Exception):
7
+ """Base for every error this SDK raises."""
8
+
9
+
10
+ class ConfigurationError(CortexhubError):
11
+ """The SDK was initialised without a usable API key."""
12
+
13
+
14
+ class AuthenticationError(CortexhubError):
15
+ """Control-plane API rejected the API key."""
16
+
17
+
18
+ class APIError(CortexhubError):
19
+ """Control-plane API returned a non-success response."""
20
+
21
+ def __init__(self, message: str, *, status: int | None = None) -> None:
22
+ super().__init__(message)
23
+ self.status = status
@@ -0,0 +1,82 @@
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
+ )
@@ -0,0 +1,83 @@
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
+ )
cortexhub-1.1.0/PKG-INFO DELETED
@@ -1,213 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: cortexhub
3
- Version: 1.1.0
4
- Summary: MCP gateway client for cortexhub agents — authenticate, hand the MCP URL to your framework of choice, done.
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,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
- MCP gateway client for cortexhub agents. Authenticate, hand the MCP URL to your framework of choice, done.
27
-
28
- [Documentation](https://docs.cortexhub.ai)
29
- ## Install
30
-
31
- ```bash
32
- pip install cortexhub
33
- ```
34
-
35
- ## Quickstart
36
-
37
- ```python
38
- from cortexhub import Cortexhub
39
-
40
- cortexhub = Cortexhub() # reads CORTEXHUB_API_KEY
41
- session = cortexhub.create(user_id="user_123")
42
-
43
- print(session.mcp.url) # https://mcp.cortexhub.ai/v1/mcp
44
- print(session.mcp.headers) # {"X-API-Key": "ch_live_…", "X-Cortexhub-End-User-Subject": "user_123"}
45
- ```
46
-
47
- Get an API key by registering an agent at [app.cortexhub.ai](https://app.cortexhub.ai).
48
-
49
- ## Use it with your framework
50
-
51
- The SDK only hands you an MCP URL + headers. Plug them into whichever framework you use.
52
-
53
- ### Claude Agent SDK
54
-
55
- ```python
56
- from cortexhub import Cortexhub
57
- from claude_agent_sdk import ClaudeAgentOptions
58
-
59
- cortexhub = Cortexhub()
60
- session = cortexhub.create(user_id="user_123")
61
-
62
- options = ClaudeAgentOptions(
63
- mcp_servers={
64
- "cortexhub": {
65
- "type": "http",
66
- "url": session.mcp.url,
67
- "headers": session.mcp.headers,
68
- },
69
- },
70
- )
71
- ```
72
-
73
- ### OpenAI Agents SDK
74
-
75
- ```python
76
- from cortexhub import Cortexhub
77
- from agents import Agent, HostedMCPTool
78
-
79
- cortexhub = Cortexhub()
80
- session = cortexhub.create(user_id="user_123")
81
-
82
- agent = Agent(
83
- name="Assistant",
84
- tools=[
85
- HostedMCPTool(
86
- tool_config={
87
- "type": "mcp",
88
- "server_label": "cortexhub",
89
- "server_url": session.mcp.url,
90
- "headers": session.mcp.headers,
91
- "require_approval": "never",
92
- }
93
- )
94
- ],
95
- )
96
- ```
97
-
98
- ### Vercel AI SDK (TypeScript)
99
-
100
- ```typescript
101
- import { Cortexhub } from "@cortexhub/core"; // see @cortexhub/core (TS)
102
- import { createMCPClient } from "@ai-sdk/mcp";
103
-
104
- const cortexhub = new Cortexhub();
105
- const session = await cortexhub.create("user_123");
106
-
107
- const client = await createMCPClient({
108
- transport: {
109
- type: "http",
110
- url: session.mcp.url,
111
- headers: session.mcp.headers,
112
- },
113
- });
114
- const tools = await client.tools();
115
- ```
116
-
117
- ### LangGraph (raw MCP)
118
-
119
- Use the standard MCP client; pass the URL + headers from the session.
120
-
121
- ```python
122
- from cortexhub import Cortexhub
123
- from mcp.client.streamable_http import streamablehttp_client
124
- from mcp import ClientSession
125
-
126
- cortexhub = Cortexhub()
127
- session = cortexhub.create(user_id="user_123")
128
-
129
- async with streamablehttp_client(session.mcp.url, headers=session.mcp.headers) as (read, write, _):
130
- async with ClientSession(read, write) as mcp:
131
- await mcp.initialize()
132
- tools = await mcp.list_tools()
133
- ```
134
-
135
- ### Claude Desktop / Cursor / ChatGPT (no SDK)
136
-
137
- Add just the gateway URL — these clients bootstrap OAuth automatically. See [docs.cortexhub.ai/frameworks/desktop-cursor](https://docs.cortexhub.ai/frameworks/desktop-cursor).
138
-
139
- ## Configuration
140
-
141
- The SDK reads exactly one environment variable:
142
-
143
- | Variable | Purpose |
144
- |---|---|
145
- | `CORTEXHUB_API_KEY` | Per-agent API key (`ch_live_…`) |
146
-
147
- Or pass it explicitly:
148
-
149
- ```python
150
- cortexhub = Cortexhub(api_key="ch_live_…")
151
- ```
152
-
153
- The MCP gateway URL is fixed — `https://mcp.cortexhub.ai/v1/mcp`. There is no self-hosted mode and no base-URL override.
154
-
155
- ## Attributing tool calls to a user
156
-
157
- Every MCP request the gateway sees is attributed to **one** end-user — the person on whose behalf the agent is acting. Two ways to do this:
158
-
159
- ### From this SDK
160
-
161
- `cortexhub.create(user_id="…")` puts the value into the `X-Cortexhub-End-User-Subject` header automatically. That's it — every tool call from the resulting session is now attributed to that user in the audit log and uses their per-end-user OAuth tokens for any toolkit that needs them.
162
-
163
- ```python
164
- session = cortexhub.create(user_id="user_123")
165
- # session.mcp.headers ==
166
- # {"X-API-Key": "ch_live_…", "X-Cortexhub-End-User-Subject": "user_123"}
167
- ```
168
-
169
- ### From any other MCP client (no SDK)
170
-
171
- Add the header directly on every MCP request:
172
-
173
- ```
174
- X-Cortexhub-End-User-Subject: user_123
175
- ```
176
-
177
- E.g. with curl:
178
-
179
- ```bash
180
- curl -N "https://mcp.cortexhub.ai/v1/mcp" \
181
- -H "x-api-key: $CORTEXHUB_API_KEY" \
182
- -H "X-Cortexhub-End-User-Subject: user_123" \
183
- -H "Content-Type: application/json" \
184
- -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
185
- ```
186
-
187
- When you omit the header, the gateway falls back to `mcp_session:<session_id>` — every distinct MCP connection becomes its own anonymous "user". Fine for personal Claude Desktop / Cursor use; not what you want for a multi-tenant app.
188
-
189
- ### What `user_id` is for
190
-
191
- `user_id` is opaque to cortexhub — pass whatever stable identifier your application uses for the human (DB id, email hash, Auth0 sub, …). Cortexhub uses it to:
192
-
193
- - Route per-end-user OAuth tokens (when the toolkit needs them)
194
- - Attribute every tool call to that user in the audit log
195
- - Scope per-end-user rate limits
196
-
197
- Calling `create()` with the same `user_id` twice is a no-op — the session is fully local and cheap to construct.
198
-
199
- ## What runs where
200
-
201
- | Concern | Where it runs |
202
- |---|---|
203
- | Authentication, session construction | This SDK (local, fully offline) |
204
- | Tool discovery, tool execution | cortexhub MCP gateway → toolkits you've attached |
205
- | Per-end-user OAuth resolution | cortexhub MCP gateway |
206
- | Per-tool policies + HITL approvals | cortexhub MCP gateway |
207
- | Audit log of every tool call | cortexhub MCP gateway |
208
-
209
- The SDK itself is a thin wrapper around two strings (URL + headers). Everything else is server-side.
210
-
211
- ## License
212
-
213
- MIT.
cortexhub-1.1.0/README.md DELETED
@@ -1,190 +0,0 @@
1
- # cortexhub
2
-
3
- MCP gateway client for cortexhub agents. Authenticate, hand the MCP URL to your framework of choice, done.
4
-
5
- [Documentation](https://docs.cortexhub.ai)
6
- ## Install
7
-
8
- ```bash
9
- pip install cortexhub
10
- ```
11
-
12
- ## Quickstart
13
-
14
- ```python
15
- from cortexhub import Cortexhub
16
-
17
- cortexhub = Cortexhub() # reads CORTEXHUB_API_KEY
18
- session = cortexhub.create(user_id="user_123")
19
-
20
- print(session.mcp.url) # https://mcp.cortexhub.ai/v1/mcp
21
- print(session.mcp.headers) # {"X-API-Key": "ch_live_…", "X-Cortexhub-End-User-Subject": "user_123"}
22
- ```
23
-
24
- Get an API key by registering an agent at [app.cortexhub.ai](https://app.cortexhub.ai).
25
-
26
- ## Use it with your framework
27
-
28
- The SDK only hands you an MCP URL + headers. Plug them into whichever framework you use.
29
-
30
- ### Claude Agent SDK
31
-
32
- ```python
33
- from cortexhub import Cortexhub
34
- from claude_agent_sdk import ClaudeAgentOptions
35
-
36
- cortexhub = Cortexhub()
37
- session = cortexhub.create(user_id="user_123")
38
-
39
- options = ClaudeAgentOptions(
40
- mcp_servers={
41
- "cortexhub": {
42
- "type": "http",
43
- "url": session.mcp.url,
44
- "headers": session.mcp.headers,
45
- },
46
- },
47
- )
48
- ```
49
-
50
- ### OpenAI Agents SDK
51
-
52
- ```python
53
- from cortexhub import Cortexhub
54
- from agents import Agent, HostedMCPTool
55
-
56
- cortexhub = Cortexhub()
57
- session = cortexhub.create(user_id="user_123")
58
-
59
- agent = Agent(
60
- name="Assistant",
61
- tools=[
62
- HostedMCPTool(
63
- tool_config={
64
- "type": "mcp",
65
- "server_label": "cortexhub",
66
- "server_url": session.mcp.url,
67
- "headers": session.mcp.headers,
68
- "require_approval": "never",
69
- }
70
- )
71
- ],
72
- )
73
- ```
74
-
75
- ### Vercel AI SDK (TypeScript)
76
-
77
- ```typescript
78
- import { Cortexhub } from "@cortexhub/core"; // see @cortexhub/core (TS)
79
- import { createMCPClient } from "@ai-sdk/mcp";
80
-
81
- const cortexhub = new Cortexhub();
82
- const session = await cortexhub.create("user_123");
83
-
84
- const client = await createMCPClient({
85
- transport: {
86
- type: "http",
87
- url: session.mcp.url,
88
- headers: session.mcp.headers,
89
- },
90
- });
91
- const tools = await client.tools();
92
- ```
93
-
94
- ### LangGraph (raw MCP)
95
-
96
- Use the standard MCP client; pass the URL + headers from the session.
97
-
98
- ```python
99
- from cortexhub import Cortexhub
100
- from mcp.client.streamable_http import streamablehttp_client
101
- from mcp import ClientSession
102
-
103
- cortexhub = Cortexhub()
104
- session = cortexhub.create(user_id="user_123")
105
-
106
- async with streamablehttp_client(session.mcp.url, headers=session.mcp.headers) as (read, write, _):
107
- async with ClientSession(read, write) as mcp:
108
- await mcp.initialize()
109
- tools = await mcp.list_tools()
110
- ```
111
-
112
- ### Claude Desktop / Cursor / ChatGPT (no SDK)
113
-
114
- Add just the gateway URL — these clients bootstrap OAuth automatically. See [docs.cortexhub.ai/frameworks/desktop-cursor](https://docs.cortexhub.ai/frameworks/desktop-cursor).
115
-
116
- ## Configuration
117
-
118
- The SDK reads exactly one environment variable:
119
-
120
- | Variable | Purpose |
121
- |---|---|
122
- | `CORTEXHUB_API_KEY` | Per-agent API key (`ch_live_…`) |
123
-
124
- Or pass it explicitly:
125
-
126
- ```python
127
- cortexhub = Cortexhub(api_key="ch_live_…")
128
- ```
129
-
130
- The MCP gateway URL is fixed — `https://mcp.cortexhub.ai/v1/mcp`. There is no self-hosted mode and no base-URL override.
131
-
132
- ## Attributing tool calls to a user
133
-
134
- Every MCP request the gateway sees is attributed to **one** end-user — the person on whose behalf the agent is acting. Two ways to do this:
135
-
136
- ### From this SDK
137
-
138
- `cortexhub.create(user_id="…")` puts the value into the `X-Cortexhub-End-User-Subject` header automatically. That's it — every tool call from the resulting session is now attributed to that user in the audit log and uses their per-end-user OAuth tokens for any toolkit that needs them.
139
-
140
- ```python
141
- session = cortexhub.create(user_id="user_123")
142
- # session.mcp.headers ==
143
- # {"X-API-Key": "ch_live_…", "X-Cortexhub-End-User-Subject": "user_123"}
144
- ```
145
-
146
- ### From any other MCP client (no SDK)
147
-
148
- Add the header directly on every MCP request:
149
-
150
- ```
151
- X-Cortexhub-End-User-Subject: user_123
152
- ```
153
-
154
- E.g. with curl:
155
-
156
- ```bash
157
- curl -N "https://mcp.cortexhub.ai/v1/mcp" \
158
- -H "x-api-key: $CORTEXHUB_API_KEY" \
159
- -H "X-Cortexhub-End-User-Subject: user_123" \
160
- -H "Content-Type: application/json" \
161
- -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
162
- ```
163
-
164
- When you omit the header, the gateway falls back to `mcp_session:<session_id>` — every distinct MCP connection becomes its own anonymous "user". Fine for personal Claude Desktop / Cursor use; not what you want for a multi-tenant app.
165
-
166
- ### What `user_id` is for
167
-
168
- `user_id` is opaque to cortexhub — pass whatever stable identifier your application uses for the human (DB id, email hash, Auth0 sub, …). Cortexhub uses it to:
169
-
170
- - Route per-end-user OAuth tokens (when the toolkit needs them)
171
- - Attribute every tool call to that user in the audit log
172
- - Scope per-end-user rate limits
173
-
174
- Calling `create()` with the same `user_id` twice is a no-op — the session is fully local and cheap to construct.
175
-
176
- ## What runs where
177
-
178
- | Concern | Where it runs |
179
- |---|---|
180
- | Authentication, session construction | This SDK (local, fully offline) |
181
- | Tool discovery, tool execution | cortexhub MCP gateway → toolkits you've attached |
182
- | Per-end-user OAuth resolution | cortexhub MCP gateway |
183
- | Per-tool policies + HITL approvals | cortexhub MCP gateway |
184
- | Audit log of every tool call | cortexhub MCP gateway |
185
-
186
- The SDK itself is a thin wrapper around two strings (URL + headers). Everything else is server-side.
187
-
188
- ## License
189
-
190
- MIT.
@@ -1,42 +0,0 @@
1
- """cortexhub — MCP gateway client for cortexhub agents.
2
-
3
- Authenticate with your agent's API key, hand the MCP URL + headers to your
4
- framework of choice (Claude Agent SDK, OpenAI Agents, Vercel AI SDK,
5
- LangGraph, raw MCP — anything that speaks MCP streamable HTTP), and you're
6
- done. Policies, approvals, scope checks, budget caps, and audit live on the
7
- cortexhub MCP gateway; the SDK doesn't run anything client-side.
8
-
9
- Quickstart::
10
-
11
- from cortexhub import Cortexhub
12
-
13
- cortexhub = Cortexhub() # reads CORTEXHUB_API_KEY
14
- session = cortexhub.create(user_id="user_123")
15
-
16
- # Hand to your framework
17
- mcp_url = session.mcp.url
18
- mcp_headers = session.mcp.headers
19
-
20
- See README.md for end-to-end snippets per framework.
21
- """
22
-
23
- from __future__ import annotations
24
-
25
- from .client import Cortexhub
26
- from .errors import (
27
- AuthenticationError,
28
- ConfigurationError,
29
- CortexhubError,
30
- )
31
- from .session import Session, SessionMcp
32
-
33
- __version__ = "1.1.0"
34
- __all__ = [
35
- "Cortexhub",
36
- "Session",
37
- "SessionMcp",
38
- "CortexhubError",
39
- "ConfigurationError",
40
- "AuthenticationError",
41
- "__version__",
42
- ]
@@ -1,65 +0,0 @@
1
- """``Cortexhub`` — entry point for the v1 SDK.
2
-
3
- Usage:
4
-
5
- from cortexhub import Cortexhub
6
-
7
- cortexhub = Cortexhub() # reads CORTEXHUB_API_KEY
8
- session = cortexhub.create(user_id="user_123")
9
- print(session.mcp.url, session.mcp.headers)
10
-
11
- The class has exactly one method (``create``). The constructor reads
12
- ``CORTEXHUB_API_KEY`` from the environment unless the caller passes one in.
13
-
14
- There is **no base-URL override**: the cortexhub MCP gateway is hosted at
15
- ``https://mcp.cortexhub.ai`` (dedicated public ALB, separate from the REST
16
- control-plane at ``https://api.cortexhub.ai``). We don't support self-hosted
17
- deployments.
18
- """
19
-
20
- from __future__ import annotations
21
-
22
- import os
23
-
24
- from .errors import ConfigurationError
25
- from .session import Session
26
-
27
- class Cortexhub:
28
- """Per-agent cortexhub client.
29
-
30
- One ``Cortexhub`` corresponds to one registered agent — its API key is
31
- the agent's. Different agents (or different environments — staging vs
32
- prod, separate agent keys) use different ``Cortexhub`` instances.
33
- """
34
-
35
- def __init__(self, api_key: str | None = None) -> None:
36
- resolved_key = api_key or os.environ.get("CORTEXHUB_API_KEY")
37
- if not resolved_key or not resolved_key.strip():
38
- raise ConfigurationError(
39
- "Missing API key. Pass api_key=... to Cortexhub() "
40
- "or set the CORTEXHUB_API_KEY environment variable. "
41
- "Get a key by registering an agent at https://app.cortexhub.ai."
42
- )
43
- self.api_key: str = resolved_key.strip()
44
-
45
- def create(self, user_id: str) -> Session:
46
- """Create a session bound to one end-user.
47
-
48
- ``user_id`` is opaque to cortexhub — it's whatever stable identifier
49
- your application uses for the human (DB id, email hash, Auth0 sub,
50
- etc.). The cortexhub MCP gateway will use it to:
51
-
52
- * Route per-end-user OAuth tokens (when the toolkit needs them)
53
- * Attribute every tool call to that user in the audit log
54
- * Evaluate per-user budget caps and rate limits
55
-
56
- The same ``user_id`` always produces the same per-user session state
57
- on the gateway side; calling ``create`` twice for the same user is a
58
- no-op (and cheap — fully local).
59
- """
60
- return Session(api_key=self.api_key, user_id=user_id)
61
-
62
- def __repr__(self) -> str:
63
- # Echo only the key prefix so logs are useful but leak nothing.
64
- prefix = self.api_key[:10] + "…" if len(self.api_key) > 10 else "…"
65
- return f"Cortexhub(api_key={prefix!r})"
@@ -1,22 +0,0 @@
1
- """Minimal error hierarchy for the cortexhub SDK.
2
-
3
- Everything in v1.0 is a thin client around the cortexhub MCP gateway, so the SDK
4
- itself raises only on **local** problems (missing API key, malformed URL).
5
- Server-side errors — policy violations, budget caps, approvals — surface as
6
- MCP tool-call responses; the framework you wrap them in is responsible for
7
- displaying them.
8
- """
9
-
10
- from __future__ import annotations
11
-
12
-
13
- class CortexhubError(Exception):
14
- """Base for every error this SDK raises."""
15
-
16
-
17
- class ConfigurationError(CortexhubError):
18
- """The SDK was initialised without a usable API key or base URL."""
19
-
20
-
21
- class AuthenticationError(CortexhubError):
22
- """Reserved for future use — when SDK methods do call the cortexhub API."""
@@ -1,81 +0,0 @@
1
- """Session — what ``Cortexhub.create(user_id=...)`` returns.
2
-
3
- A ``Session`` is a tiny value object: it holds the (api_key, user_id) pair
4
- and exposes ``session.mcp.url`` + ``session.mcp.headers`` which the caller
5
- hands to their framework's MCP client.
6
-
7
- Construction is fully local — no network call. The cortexhub MCP gateway
8
- authenticates each tool call by reading two headers:
9
-
10
- * ``X-API-Key`` — the agent's raw API key (``ch_live_…`` /``ch_test_…``).
11
- * ``X-Cortexhub-End-User-Subject`` — the end-user the session is bound to.
12
-
13
- Per-end-user OAuth state, Policy decisions, and HITL approvals are all
14
- resolved server-side at the gateway — the SDK has no governance code.
15
-
16
- We deliberately do NOT use ``Authorization: Bearer …`` for the raw agent
17
- key, even though MCP convention favours Bearer. The Bearer slot at the
18
- gateway is reserved for short-lived MCP OAuth JWTs (issued via
19
- ``/v1/oauth/mcp/token``) used by browser-based MCP clients like Claude.ai
20
- and Cursor — mixing raw keys into Bearer would muddle that contract.
21
- """
22
-
23
- from __future__ import annotations
24
-
25
- from dataclasses import dataclass, field
26
-
27
- # Hosted MCP gateway URL. Points to the dedicated public ALB (mcp.cortexhub.ai),
28
- # NOT to api.cortexhub.ai (API Gateway). The MCP ALB has a 3600 s idle timeout
29
- # and AWS WAF — API Gateway has a hard 29 s timeout that kills SSE connections.
30
- # Hard-coded — the SDK does not support self-hosted deployments.
31
- _MCP_URL = "https://mcp.cortexhub.ai/v1/mcp"
32
-
33
- # Headers the gateway reads. Both are namespaced ``X-Cortexhub-…`` /
34
- # ``X-API-Key`` so they don't clash with framework-injected Bearer tokens
35
- # (e.g. when the user's framework also speaks OAuth to other backends).
36
- _API_KEY_HEADER = "X-API-Key"
37
- _END_USER_SUBJECT_HEADER = "X-Cortexhub-End-User-Subject"
38
-
39
-
40
- @dataclass(frozen=True)
41
- class SessionMcp:
42
- """The MCP connection details — pass straight to your framework.
43
-
44
- ``url`` is the streamable-HTTP MCP endpoint; ``headers`` carry the agent
45
- API key plus the end-user subject. Frozen so callers can't accidentally
46
- mutate the dict and lose auth on subsequent calls.
47
- """
48
-
49
- url: str
50
- headers: dict[str, str] = field(default_factory=dict)
51
-
52
-
53
- class Session:
54
- """A per-end-user session bound to one cortexhub agent.
55
-
56
- Created via :meth:`Cortexhub.create`. Carries ``user_id`` for caller
57
- introspection and ``mcp`` for the framework hand-off. The constructor is
58
- keyword-only so accidental positional drift on a future signature change
59
- fails loudly.
60
- """
61
-
62
- def __init__(self, *, api_key: str, user_id: str) -> None:
63
- if not user_id:
64
- raise ValueError("user_id is required.")
65
- # Public — callers may want to log it / pass it back into their
66
- # downstream context (e.g. structured log fields).
67
- self.user_id: str = user_id
68
- # Private — exposed only via ``mcp.headers`` so callers don't get
69
- # tempted to do ad-hoc HTTP with these credentials.
70
- self._api_key = api_key
71
- self.mcp: SessionMcp = SessionMcp(
72
- url=_MCP_URL,
73
- headers={
74
- _API_KEY_HEADER: api_key,
75
- _END_USER_SUBJECT_HEADER: user_id,
76
- },
77
- )
78
-
79
- def __repr__(self) -> str:
80
- # Don't echo the key.
81
- return f"Session(user_id={self.user_id!r}, mcp={self.mcp.url!r})"
File without changes
File without changes