cortexhub 2.0.5__tar.gz → 3.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,11 @@
1
+ dist/
2
+ build/
3
+ *.egg-info/
4
+ .venv/
5
+ __pycache__/
6
+ .pytest_cache/
7
+ .ruff_cache/
8
+ .pypirc
9
+
10
+ # uv lock (library — resolved by consumers, not shipped)
11
+ uv.lock
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.5
2
+ Name: cortexhub
3
+ Version: 3.0.0
4
+ Summary: CortexHub platform SDK: point your agent at the governed LLM router + MCP gateway.
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
+ Provides-Extra: ai
22
+ Requires-Dist: openai>=1.40; extra == 'ai'
23
+ Provides-Extra: all
24
+ Requires-Dist: mcp>=1.0; extra == 'all'
25
+ Requires-Dist: openai>=1.40; extra == 'all'
26
+ Provides-Extra: mcp
27
+ Requires-Dist: mcp>=1.0; extra == 'mcp'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # cortexhub
31
+
32
+ The **CortexHub platform SDK**. One API key points your existing agent at two
33
+ governed planes:
34
+
35
+ - the **LLM router** (inference) - OpenAI-compatible, so any framework works,
36
+ with routing, caching, compression, governance, and per-agent metering; and
37
+ - the **MCP gateway** (tools + brain + files) - governed, consent-gated,
38
+ injection-defended.
39
+
40
+ You don't rewrite your agent. You change a base URL and drop in one key.
41
+
42
+ [Documentation](https://docs.cortexhub.ai/docs/sdks/overview)
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install cortexhub # zero-dependency core (URLs + headers)
48
+ pip install 'cortexhub[ai]' # + a ready OpenAI-compatible client via cx.llm
49
+ pip install 'cortexhub[mcp]' # + the official MCP client for cx.mcp() sessions
50
+ ```
51
+
52
+ ## The key
53
+
54
+ Onboard an external AI employee in the CortexHub dashboard, grant it
55
+ capabilities, and mint an API key **bound to that agent** (Settings ->
56
+ API keys, or the agent's page). The `cxh_key_...` *is* that agent's identity -
57
+ every call is attributed, governed, and metered to it. No agent argument needed.
58
+
59
+ ```python
60
+ from cortexhub import Cortexhub
61
+ cx = Cortexhub(api_key="cxh_key_...") # or set CORTEXHUB_API_KEY
62
+ ```
63
+
64
+ ## Inference
65
+
66
+ `cx.ai` gives you everything any OpenAI-compatible client needs; `cx.llm` is a
67
+ ready client (extra: `cortexhub[ai]`). Pick the model with the `model` argument:
68
+ `cortexhub/auto` to let CortexHub route per turn, or any model enabled on the
69
+ platform.
70
+
71
+ ```python
72
+ cx.llm.chat.completions.create(model="cortexhub/auto", messages=[{"role": "user", "content": "hi"}])
73
+ cx.llm.responses.create(model="cortexhub/auto", input="hi")
74
+ cx.llm.models.list()
75
+
76
+ cx.ai.base_url # e.g. https://api.cortexhub.ai/v1 (override with CORTEXHUB_ROUTER_URL)
77
+ cx.ai.api_key # your cxh_key_...
78
+ ```
79
+
80
+ ## Use your existing framework
81
+
82
+ The router speaks the OpenAI wire protocol, so every framework integrates the
83
+ same way: point its OpenAI-compatible provider at `cx.ai.base_url`, pass
84
+ `cx.ai.api_key`, and choose a `model`.
85
+
86
+ ```python
87
+ base, key = cx.ai.base_url, cx.ai.api_key
88
+
89
+ # OpenAI SDK / plain
90
+ from openai import OpenAI
91
+ OpenAI(base_url=base, api_key=key).chat.completions.create(model="cortexhub/auto", messages=[...])
92
+
93
+ # LangChain / LangGraph
94
+ from langchain_openai import ChatOpenAI
95
+ ChatOpenAI(base_url=base, api_key=key, model="cortexhub/auto")
96
+
97
+ # CrewAI (LiteLLM under the hood)
98
+ from crewai import LLM
99
+ LLM(model="openai/cortexhub/auto", base_url=base, api_key=key)
100
+
101
+ # AutoGen
102
+ from autogen_ext.models.openai import OpenAIChatCompletionClient
103
+ OpenAIChatCompletionClient(model="cortexhub/auto", base_url=base, api_key=key)
104
+
105
+ # Pydantic AI
106
+ from pydantic_ai.models.openai import OpenAIModel
107
+ from pydantic_ai.providers.openai import OpenAIProvider
108
+ OpenAIModel("cortexhub/auto", provider=OpenAIProvider(base_url=base, api_key=key))
109
+ ```
110
+
111
+ **Anthropic SDK:** the router is OpenAI-compatible, not Anthropic-Messages, so
112
+ point the *OpenAI* client at CortexHub with a `claude-*` model (we route to
113
+ Claude) rather than the Anthropic SDK.
114
+
115
+ ## Tools, brain, and files (MCP gateway)
116
+
117
+ `cx.mcp(agent=...)` returns the MCP connection your agent's loop drives. Any
118
+ MCP-capable framework can register it as a server; the `cortexhub_*` tools
119
+ (governed toolkit calls, brain recall/learn, files search) then appear
120
+ automatically.
121
+
122
+ ```python
123
+ conn = cx.mcp(agent="invoice-bot", end_user_subject="user_42")
124
+ conn.url # https://mcp.cortexhub.ai/v1/mcp
125
+ conn.headers # ready to wire into your MCP transport
126
+ ```
127
+
128
+ ## Authentication modes
129
+
130
+ - **API key** (`api_key=cxh_key_...`, or `CORTEXHUB_API_KEY`) - backends whose
131
+ end users do not have CortexHub accounts. Attest the end user per call with
132
+ `end_user_subject`. Required for `cx.ai` / `cx.llm`.
133
+ - **MCP OAuth client** (`client_id=` / `client_secret=`) - for interactive
134
+ CortexHub users, MCP gateway only.
135
+
136
+ The MCP gateway also accepts MCP OAuth from third-party clients (Claude, Cursor)
137
+ independently of this SDK.
@@ -0,0 +1,108 @@
1
+ # cortexhub
2
+
3
+ The **CortexHub platform SDK**. One API key points your existing agent at two
4
+ governed planes:
5
+
6
+ - the **LLM router** (inference) - OpenAI-compatible, so any framework works,
7
+ with routing, caching, compression, governance, and per-agent metering; and
8
+ - the **MCP gateway** (tools + brain + files) - governed, consent-gated,
9
+ injection-defended.
10
+
11
+ You don't rewrite your agent. You change a base URL and drop in one key.
12
+
13
+ [Documentation](https://docs.cortexhub.ai/docs/sdks/overview)
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pip install cortexhub # zero-dependency core (URLs + headers)
19
+ pip install 'cortexhub[ai]' # + a ready OpenAI-compatible client via cx.llm
20
+ pip install 'cortexhub[mcp]' # + the official MCP client for cx.mcp() sessions
21
+ ```
22
+
23
+ ## The key
24
+
25
+ Onboard an external AI employee in the CortexHub dashboard, grant it
26
+ capabilities, and mint an API key **bound to that agent** (Settings ->
27
+ API keys, or the agent's page). The `cxh_key_...` *is* that agent's identity -
28
+ every call is attributed, governed, and metered to it. No agent argument needed.
29
+
30
+ ```python
31
+ from cortexhub import Cortexhub
32
+ cx = Cortexhub(api_key="cxh_key_...") # or set CORTEXHUB_API_KEY
33
+ ```
34
+
35
+ ## Inference
36
+
37
+ `cx.ai` gives you everything any OpenAI-compatible client needs; `cx.llm` is a
38
+ ready client (extra: `cortexhub[ai]`). Pick the model with the `model` argument:
39
+ `cortexhub/auto` to let CortexHub route per turn, or any model enabled on the
40
+ platform.
41
+
42
+ ```python
43
+ cx.llm.chat.completions.create(model="cortexhub/auto", messages=[{"role": "user", "content": "hi"}])
44
+ cx.llm.responses.create(model="cortexhub/auto", input="hi")
45
+ cx.llm.models.list()
46
+
47
+ cx.ai.base_url # e.g. https://api.cortexhub.ai/v1 (override with CORTEXHUB_ROUTER_URL)
48
+ cx.ai.api_key # your cxh_key_...
49
+ ```
50
+
51
+ ## Use your existing framework
52
+
53
+ The router speaks the OpenAI wire protocol, so every framework integrates the
54
+ same way: point its OpenAI-compatible provider at `cx.ai.base_url`, pass
55
+ `cx.ai.api_key`, and choose a `model`.
56
+
57
+ ```python
58
+ base, key = cx.ai.base_url, cx.ai.api_key
59
+
60
+ # OpenAI SDK / plain
61
+ from openai import OpenAI
62
+ OpenAI(base_url=base, api_key=key).chat.completions.create(model="cortexhub/auto", messages=[...])
63
+
64
+ # LangChain / LangGraph
65
+ from langchain_openai import ChatOpenAI
66
+ ChatOpenAI(base_url=base, api_key=key, model="cortexhub/auto")
67
+
68
+ # CrewAI (LiteLLM under the hood)
69
+ from crewai import LLM
70
+ LLM(model="openai/cortexhub/auto", base_url=base, api_key=key)
71
+
72
+ # AutoGen
73
+ from autogen_ext.models.openai import OpenAIChatCompletionClient
74
+ OpenAIChatCompletionClient(model="cortexhub/auto", base_url=base, api_key=key)
75
+
76
+ # Pydantic AI
77
+ from pydantic_ai.models.openai import OpenAIModel
78
+ from pydantic_ai.providers.openai import OpenAIProvider
79
+ OpenAIModel("cortexhub/auto", provider=OpenAIProvider(base_url=base, api_key=key))
80
+ ```
81
+
82
+ **Anthropic SDK:** the router is OpenAI-compatible, not Anthropic-Messages, so
83
+ point the *OpenAI* client at CortexHub with a `claude-*` model (we route to
84
+ Claude) rather than the Anthropic SDK.
85
+
86
+ ## Tools, brain, and files (MCP gateway)
87
+
88
+ `cx.mcp(agent=...)` returns the MCP connection your agent's loop drives. Any
89
+ MCP-capable framework can register it as a server; the `cortexhub_*` tools
90
+ (governed toolkit calls, brain recall/learn, files search) then appear
91
+ automatically.
92
+
93
+ ```python
94
+ conn = cx.mcp(agent="invoice-bot", end_user_subject="user_42")
95
+ conn.url # https://mcp.cortexhub.ai/v1/mcp
96
+ conn.headers # ready to wire into your MCP transport
97
+ ```
98
+
99
+ ## Authentication modes
100
+
101
+ - **API key** (`api_key=cxh_key_...`, or `CORTEXHUB_API_KEY`) - backends whose
102
+ end users do not have CortexHub accounts. Attest the end user per call with
103
+ `end_user_subject`. Required for `cx.ai` / `cx.llm`.
104
+ - **MCP OAuth client** (`client_id=` / `client_secret=`) - for interactive
105
+ CortexHub users, MCP gateway only.
106
+
107
+ The MCP gateway also accepts MCP OAuth from third-party clients (Claude, Cursor)
108
+ independently of this SDK.
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "cortexhub"
3
- version = "2.0.5"
4
- description = "MCP gateway client for CortexHub programmatic agent access."
3
+ version = "3.0.0"
4
+ description = "CortexHub platform SDK: point your agent at the governed LLM router + MCP gateway."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
7
7
  license = { text = "MIT" }
@@ -27,6 +27,15 @@ classifiers = [
27
27
  # do client-side governance and that work now lives on the cortexhub gateway.
28
28
  dependencies = []
29
29
 
30
+ # The core is zero-dependency (it computes URLs + headers). The client sugar
31
+ # pulls the standard clients only when you ask for it:
32
+ # pip install 'cortexhub[ai]' -> cx.llm returns a ready openai client
33
+ # pip install 'cortexhub[mcp]' -> the official MCP client for cx.mcp() sessions
34
+ [project.optional-dependencies]
35
+ ai = ["openai>=1.40"]
36
+ mcp = ["mcp>=1.0"]
37
+ all = ["openai>=1.40", "mcp>=1.0"]
38
+
30
39
  [project.urls]
31
40
  Homepage = "https://cortexhub.ai"
32
41
  Documentation = "https://docs.cortexhub.ai"
@@ -64,14 +73,20 @@ ignore = ["E501"]
64
73
  python_version = "3.10"
65
74
  strict = true
66
75
  warn_return_any = true
67
- warn_unused_ignores = true
76
+ # ``openai`` is an optional extra (cortexhub[ai]); the core is zero-dep and
77
+ # imports it lazily inside cx.llm, so a missing stub for it is not an error.
78
+ warn_unused_ignores = false
79
+
80
+ [[tool.mypy.overrides]]
81
+ module = ["openai", "openai.*"]
82
+ ignore_missing_imports = true
68
83
 
69
84
  [tool.uv]
70
85
  python-preference = "only-managed"
71
86
 
72
87
  [dependency-groups]
73
88
  dev = [
74
- "pytest>=9.0.2",
75
- "ruff>=0.4.0",
76
- "mypy>=1.10.0",
89
+ "pytest==9.0.3",
90
+ "ruff==0.14.11",
91
+ "mypy==1.19.1",
77
92
  ]
@@ -2,16 +2,16 @@
2
2
 
3
3
  This package builds the URL and headers your MCP transport needs to
4
4
  call ``https://mcp.cortexhub.ai/v1/mcp``. It does not call the
5
- CortexHub Platform API; for organisation and workspace management, use
6
- the Platform API directly.
5
+ CortexHub Platform API; for organisation, agent, and member management,
6
+ use the Platform API directly.
7
7
 
8
8
  Two gateway authentication paths through one entry point:
9
9
 
10
10
  .. code-block:: python
11
11
 
12
- # Workspace MCP API key (recommended for backends):
12
+ # Org API key (recommended for backends):
13
13
  from cortexhub import Cortexhub
14
- cx = Cortexhub(api_key="cxh_mcpk_<id>_<secret>")
14
+ cx = Cortexhub(api_key="cxh_key_<id>_<secret>")
15
15
  session = cx.session(agent="invoice-bot", end_user_subject="user_42")
16
16
 
17
17
  # MCP OAuth client (interactive CortexHub users):
@@ -24,24 +24,26 @@ to wire into your MCP transport.
24
24
 
25
25
  from __future__ import annotations
26
26
 
27
+ from .ai import AiGateway
27
28
  from .client import Cortexhub
28
29
  from .errors import APIError, AuthenticationError, ConfigurationError, CortexhubError
29
30
  from .mcp_key import CortexhubKeyClient, McpKeySession
30
31
  from .mcp_oauth import CortexhubMcpOAuthClient, McpOAuthSession, McpOAuthToken
31
32
  from .session import SessionMcp
32
33
 
33
- __version__ = "2.0.4"
34
+ __version__ = "3.0.0"
34
35
  __all__ = [
36
+ "APIError",
37
+ "AiGateway",
38
+ "AuthenticationError",
39
+ "ConfigurationError",
35
40
  "Cortexhub",
41
+ "CortexhubError",
36
42
  "CortexhubKeyClient",
37
43
  "CortexhubMcpOAuthClient",
38
44
  "McpKeySession",
39
45
  "McpOAuthSession",
40
46
  "McpOAuthToken",
41
47
  "SessionMcp",
42
- "CortexhubError",
43
- "ConfigurationError",
44
- "AuthenticationError",
45
- "APIError",
46
48
  "__version__",
47
49
  ]
@@ -0,0 +1,22 @@
1
+ """SDK base URL configuration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ # MCP gateway (tools + brain + files).
8
+ DEFAULT_URL = "https://mcp.cortexhub.ai"
9
+
10
+ # AI gateway (LLM router). OpenAI-compatible; the client appends
11
+ # ``/chat/completions`` etc. The keyed router is served on the platform API
12
+ # host today; ``router.cortexhub.ai`` is the future canonical host. Override
13
+ # with ``CORTEXHUB_ROUTER_URL``.
14
+ DEFAULT_ROUTER_URL = "https://api.cortexhub.ai/v1"
15
+
16
+
17
+ def base_url() -> str:
18
+ return (os.environ.get("CORTEXHUB_URL") or DEFAULT_URL).rstrip("/")
19
+
20
+
21
+ def router_base_url() -> str:
22
+ return (os.environ.get("CORTEXHUB_ROUTER_URL") or DEFAULT_ROUTER_URL).rstrip("/")
@@ -0,0 +1,63 @@
1
+ """AI gateway (LLM router) configuration + optional client.
2
+
3
+ The router is OpenAI-compatible, so you point any framework's OpenAI-compatible
4
+ provider at :attr:`AiGateway.base_url` with your ``cxh_key_...`` as the API key
5
+ and pass a ``model`` (``cortexhub/auto`` to let CortexHub route, or a specific
6
+ model enabled on the platform). The key is bound to one agent, so there is no
7
+ agent argument - every call is that agent, governed and metered.
8
+
9
+ ``base_url`` + ``api_key`` are all any client needs; :meth:`AiGateway.client`
10
+ (and ``Cortexhub.llm``) is optional sugar that returns a ready ``openai``
11
+ client, and requires the ``cortexhub[ai]`` extra.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass
17
+ from typing import Any
18
+
19
+ from ._config import router_base_url
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class AiGateway:
24
+ """Everything needed to call the CortexHub LLM router.
25
+
26
+ Point your framework's OpenAI-compatible client here::
27
+
28
+ cx = Cortexhub(api_key="cxh_key_...")
29
+ # base_url + api_key are all you need:
30
+ base = cx.ai.base_url # e.g. https://api.cortexhub.ai/v1
31
+ key = cx.ai.api_key # your cxh_key_...
32
+ """
33
+
34
+ api_key: str
35
+ base_url: str
36
+
37
+ @property
38
+ def headers(self) -> dict[str, str]:
39
+ """Auth header for a raw HTTP client (the OpenAI wire uses Bearer)."""
40
+ return {"Authorization": f"Bearer {self.api_key}"}
41
+
42
+ def client(self, **kwargs: Any) -> Any:
43
+ """Return an ``openai`` client pointed at the router (extra: ``ai``).
44
+
45
+ Extra keyword arguments are passed through to ``openai.OpenAI`` (e.g.
46
+ ``timeout``, ``max_retries``). Raises a clear error if ``openai`` is not
47
+ installed.
48
+ """
49
+ try:
50
+ from openai import OpenAI # type: ignore[import-not-found]
51
+ except ModuleNotFoundError as exc: # pragma: no cover - exercised in tests
52
+ raise ImportError(
53
+ "cx.llm / AiGateway.client() needs the 'openai' package. "
54
+ "Install it with: pip install 'cortexhub[ai]'"
55
+ ) from exc
56
+ return OpenAI(base_url=self.base_url, api_key=self.api_key, **kwargs)
57
+
58
+
59
+ def build_ai_gateway(api_key: str) -> AiGateway:
60
+ return AiGateway(api_key=api_key, base_url=router_base_url())
61
+
62
+
63
+ __all__ = ["AiGateway", "build_ai_gateway"]
@@ -2,12 +2,12 @@
2
2
 
3
3
  Two authentication paths are supported through one entry point:
4
4
 
5
- * **Workspace MCP API key** (recommended for backends whose end users do
5
+ * **Org API key** (recommended for backends whose end users do
6
6
  not have CortexHub accounts):
7
7
 
8
8
  .. code-block:: python
9
9
 
10
- cx = Cortexhub(api_key="cxh_mcpk_<id>_<secret>")
10
+ cx = Cortexhub(api_key="cxh_key_<id>_<secret>")
11
11
  session = cx.session(agent="invoice-bot", end_user_subject="user_42")
12
12
 
13
13
  * **MCP OAuth client** (when your application signs in CortexHub users):
@@ -24,21 +24,32 @@ to wire into the MCP transport of your choice.
24
24
  from __future__ import annotations
25
25
 
26
26
  import os
27
- from typing import Literal
27
+ from typing import Any, Literal
28
28
 
29
+ from .ai import AiGateway, build_ai_gateway
29
30
  from .errors import ConfigurationError
30
31
  from .mcp_key import CortexhubKeyClient, McpKeySession
31
32
  from .mcp_oauth import CortexhubMcpOAuthClient, McpOAuthSession, McpOAuthToken
33
+ from .session import SessionMcp
32
34
 
33
35
 
34
36
  class Cortexhub:
35
- """MCP gateway client. Pass either a workspace API key OR OAuth credentials.
37
+ """CortexHub platform client. Pass either an org API key OR OAuth credentials.
38
+
39
+ One key spans both runtime planes:
40
+
41
+ - ``cx.ai`` / ``cx.llm`` -- the LLM router (inference). Point any
42
+ OpenAI-compatible framework at ``cx.ai.base_url`` with your ``cxh_key_``,
43
+ or use ``cx.llm`` for a ready client (extra: ``cortexhub[ai]``).
44
+ - ``cx.mcp(agent=...)`` / ``cx.session(...)`` -- the MCP gateway (tools,
45
+ brain, files) as an MCP connection for your agent.
36
46
 
37
47
  Environment variables (optional fallbacks):
38
48
 
39
- - ``CORTEXHUB_API_KEY`` -- workspace MCP API key (``cxh_mcpk_*``)
49
+ - ``CORTEXHUB_API_KEY`` -- org API key (``cxh_key_*``)
40
50
  - ``CORTEXHUB_CLIENT_ID`` and ``CORTEXHUB_CLIENT_SECRET`` -- MCP OAuth credentials
41
- - ``CORTEXHUB_URL`` -- gateway base URL (default ``https://mcp.cortexhub.ai``)
51
+ - ``CORTEXHUB_URL`` -- MCP gateway base URL (default ``https://mcp.cortexhub.ai``)
52
+ - ``CORTEXHUB_ROUTER_URL`` -- LLM router base URL (OpenAI-compatible)
42
53
 
43
54
  Exactly one credential path must be present. If both an API key and
44
55
  OAuth credentials are configured, the API key takes precedence.
@@ -79,7 +90,7 @@ class Cortexhub:
79
90
  return
80
91
 
81
92
  raise ConfigurationError(
82
- "Missing credentials. Pass api_key= (workspace MCP API key) OR "
93
+ "Missing credentials. Pass api_key= (org API key) OR "
83
94
  "client_id= and client_secret= (MCP OAuth client). You can also "
84
95
  "set CORTEXHUB_API_KEY, or CORTEXHUB_CLIENT_ID and "
85
96
  "CORTEXHUB_CLIENT_SECRET."
@@ -99,14 +110,13 @@ class Cortexhub:
99
110
  end_user_display_hint: str | None = None,
100
111
  conversation_title: str | None = None,
101
112
  last_user_message: str | None = None,
102
- invocation_mode: Literal["interactive", "autonomous"] | None = None,
103
113
  refresh: bool = False,
104
114
  ) -> McpKeySession | McpOAuthSession:
105
115
  """Return MCP transport details (``.mcp.url`` and ``.mcp.headers``).
106
116
 
107
117
  ``agent`` is required on every call.
108
118
 
109
- **Workspace API key mode**: pass ``end_user_subject`` to attest
119
+ **Org API key mode**: pass ``end_user_subject`` to attest
110
120
  the end user the call is acting on behalf of. The gateway
111
121
  requires it for any policy with end-user accountability; missing
112
122
  it on such a call returns HTTP 400. ``end_user_display_hint`` is
@@ -118,13 +128,6 @@ class Cortexhub:
118
128
  attached so operators can see session context when reviewing
119
129
  spans for this session in CortexHub.
120
130
 
121
- ``invocation_mode``:
122
-
123
- * ``"interactive"`` -- a human is present and can answer
124
- in-client consent prompts. Default for OAuth callers.
125
- * ``"autonomous"`` -- cron jobs, queue workers, webhook handlers,
126
- and other unattended runs. Default for workspace-key callers.
127
-
128
131
  ``refresh`` only applies to OAuth mode -- force a refresh-token
129
132
  exchange instead of reusing the cached token.
130
133
  """
@@ -135,7 +138,6 @@ class Cortexhub:
135
138
  mcp_session_id=mcp_session_id,
136
139
  end_user_subject=end_user_subject,
137
140
  end_user_display_hint=end_user_display_hint,
138
- invocation_mode=invocation_mode,
139
141
  )
140
142
  assert self._oauth_backend is not None
141
143
  return self._oauth_backend.session(
@@ -143,7 +145,6 @@ class Cortexhub:
143
145
  mcp_session_id=mcp_session_id,
144
146
  conversation_title=conversation_title,
145
147
  last_user_message=last_user_message,
146
- invocation_mode=invocation_mode,
147
148
  refresh=refresh,
148
149
  )
149
150
 
@@ -162,16 +163,76 @@ class Cortexhub:
162
163
  """OAuth token URL when in OAuth mode. Empty string in key mode."""
163
164
  return self._oauth_backend.token_url if self._oauth_backend else ""
164
165
 
166
+ @property
167
+ def ai(self) -> AiGateway:
168
+ """LLM router config (``base_url`` + ``api_key``). Key mode only.
169
+
170
+ Point any OpenAI-compatible framework at ``cx.ai.base_url`` with
171
+ ``cx.ai.api_key``; pass a ``model`` (``cortexhub/auto`` or a specific
172
+ enabled model). The key is bound to one agent, so no agent argument.
173
+ """
174
+ if self._key_backend is None:
175
+ raise ConfigurationError(
176
+ "cx.ai / cx.llm require an org API key (api_key=cxh_key_...). "
177
+ "The LLM router authenticates with the API key as a Bearer "
178
+ "token; OAuth client credentials are for the MCP gateway."
179
+ )
180
+ return build_ai_gateway(self._key_backend.api_key)
181
+
182
+ @property
183
+ def llm(self) -> Any:
184
+ """A ready OpenAI-compatible client at the router (extra: ``cortexhub[ai]``).
185
+
186
+ .. code-block:: python
187
+
188
+ cx.llm.chat.completions.create(model="cortexhub/auto", messages=[...])
189
+ cx.llm.responses.create(model="cortexhub/auto", input="...")
190
+
191
+ Cached per client. Requires the ``openai`` package.
192
+ """
193
+ cached = getattr(self, "_llm_client", None)
194
+ if cached is None:
195
+ cached = self.ai.client()
196
+ self._llm_client = cached
197
+ return cached
198
+
199
+ def mcp(
200
+ self,
201
+ *,
202
+ agent: str,
203
+ mcp_session_id: str | None = None,
204
+ end_user_subject: str | None = None,
205
+ end_user_display_hint: str | None = None,
206
+ conversation_title: str | None = None,
207
+ last_user_message: str | None = None,
208
+ refresh: bool = False,
209
+ ) -> SessionMcp:
210
+ """MCP gateway connection (``.url`` + ``.headers``) for your agent.
211
+
212
+ A shortcut for ``cx.session(...).mcp``. Wire ``.url`` and ``.headers``
213
+ into your MCP transport; tools, brain, and files appear as governed
214
+ tools. Works in both key and OAuth mode.
215
+ """
216
+ return self.session(
217
+ agent=agent,
218
+ mcp_session_id=mcp_session_id,
219
+ end_user_subject=end_user_subject,
220
+ end_user_display_hint=end_user_display_hint,
221
+ conversation_title=conversation_title,
222
+ last_user_message=last_user_message,
223
+ refresh=refresh,
224
+ ).mcp
225
+
165
226
  def fetch_token(self, *, refresh: bool = False) -> McpOAuthToken:
166
227
  """OAuth-mode only. Mint or refresh an access token directly.
167
228
 
168
- Raises ``RuntimeError`` if the client was built with a workspace
229
+ Raises ``RuntimeError`` if the client was built with an org
169
230
  API key -- those do not require a token exchange.
170
231
  """
171
232
  if self._oauth_backend is None:
172
233
  raise RuntimeError(
173
234
  "fetch_token() is only available when the client was built "
174
- "with client_id and client_secret. Workspace API keys do not "
235
+ "with client_id and client_secret. Org API keys do not "
175
236
  "require a token exchange."
176
237
  )
177
238
  return self._oauth_backend.fetch_token(refresh=refresh)
@@ -181,5 +242,5 @@ class Cortexhub:
181
242
  return f"Cortexhub(api_key={self._key_backend.masked_key!r})"
182
243
  assert self._oauth_backend is not None
183
244
  cid = self._oauth_backend.client_id
184
- prefix = cid[:12] + "…" if len(cid) > 12 else cid
245
+ prefix = cid[:12] + "..." if len(cid) > 12 else cid
185
246
  return f"Cortexhub(client_id={prefix!r})"
@@ -0,0 +1,100 @@
1
+ """Org API key client.
2
+
3
+ Use this when your backend acts on behalf of users who do not have
4
+ CortexHub identities. The org API key authenticates the
5
+ gateway; the end-user identity is attested per call via
6
+ ``X-CortexHub-End-User-Subject``. No CortexHub user row is created
7
+ for the end user, no email is required, no PII is stored.
8
+
9
+ For applications that sign in CortexHub users interactively, see
10
+ :mod:`cortexhub.mcp_oauth` instead.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ from ._config import base_url
18
+ from .session import SessionMcp
19
+
20
+ _KEY_HEADER = "X-CortexHub-Key"
21
+ _AGENT_HEADER = "X-CortexHub-Agent"
22
+ _END_USER_SUBJECT_HEADER = "X-CortexHub-End-User-Subject"
23
+ _END_USER_DISPLAY_HINT_HEADER = "X-CortexHub-End-User-Display-Hint"
24
+
25
+ _KEY_PREFIX = "cxh_key_"
26
+
27
+
28
+ @dataclass
29
+ class McpKeySession:
30
+ """MCP connection using an org API key + per-call end-user attestation.
31
+
32
+ Wire into your MCP transport via ``session.mcp.url`` and
33
+ ``session.mcp.headers``.
34
+ """
35
+
36
+ api_key: str
37
+ agent: str
38
+ mcp_session_id: str | None = None
39
+ end_user_subject: str | None = None
40
+ end_user_display_hint: str | None = None
41
+ mcp: SessionMcp = field(init=False)
42
+
43
+ def __post_init__(self) -> None:
44
+ headers: dict[str, str] = {
45
+ _KEY_HEADER: self.api_key,
46
+ _AGENT_HEADER: self.agent,
47
+ }
48
+ if self.mcp_session_id:
49
+ headers["Mcp-Session-Id"] = self.mcp_session_id
50
+ if self.end_user_subject:
51
+ headers[_END_USER_SUBJECT_HEADER] = self.end_user_subject
52
+ if self.end_user_display_hint:
53
+ headers[_END_USER_DISPLAY_HINT_HEADER] = self.end_user_display_hint
54
+ self.mcp = SessionMcp(url=f"{base_url()}/v1/mcp", headers=headers)
55
+
56
+
57
+ class CortexhubKeyClient:
58
+ """Send MCP gateway calls authenticated by an org API key."""
59
+
60
+ def __init__(self, *, api_key: str) -> None:
61
+ cleaned = (api_key or "").strip()
62
+ if not cleaned:
63
+ raise ValueError("api_key= is required.")
64
+ if not cleaned.startswith(_KEY_PREFIX):
65
+ raise ValueError(
66
+ f"api_key must start with {_KEY_PREFIX!r}. Org API keys begin "
67
+ "with this prefix; if you have an OAuth client_id and "
68
+ "client_secret instead, use the OAuth credentials path."
69
+ )
70
+ self.api_key = cleaned
71
+
72
+ @property
73
+ def masked_key(self) -> str:
74
+ """Return the key id portion with the secret masked, for logs and repr."""
75
+ sep = self.api_key.find("_", len(_KEY_PREFIX))
76
+ if sep <= len(_KEY_PREFIX):
77
+ return self.api_key[:12] + "..."
78
+ return self.api_key[:sep] + "_..."
79
+
80
+ def session(
81
+ self,
82
+ *,
83
+ agent: str,
84
+ mcp_session_id: str | None = None,
85
+ end_user_subject: str | None = None,
86
+ end_user_display_hint: str | None = None,
87
+ ) -> McpKeySession:
88
+ """Return MCP transport headers for a single agent call."""
89
+ if not agent or not agent.strip():
90
+ raise ValueError("agent= is required.")
91
+ return McpKeySession(
92
+ api_key=self.api_key,
93
+ agent=agent.strip(),
94
+ mcp_session_id=(mcp_session_id or "").strip() or None,
95
+ end_user_subject=(end_user_subject or "").strip() or None,
96
+ end_user_display_hint=(end_user_display_hint or "").strip() or None,
97
+ )
98
+
99
+ def __repr__(self) -> str:
100
+ return f"CortexhubKeyClient(api_key={self.masked_key!r})"
@@ -1,10 +1,4 @@
1
- """MCP OAuth client for users with a CortexHub identity.
2
-
3
- Use this when your MCP client signs in an interactive CortexHub user (for
4
- example, your application has a logged-in user that maps to a CortexHub
5
- member). For programmatic backends that act on behalf of users who do not
6
- have CortexHub identities, use :mod:`cortexhub.mcp_key` instead.
7
- """
1
+ """MCP OAuth client for users with a CortexHub identity."""
8
2
 
9
3
  from __future__ import annotations
10
4
 
@@ -13,13 +7,12 @@ import urllib.error
13
7
  import urllib.parse
14
8
  import urllib.request
15
9
  from dataclasses import dataclass, field
16
- from typing import Any, Literal
10
+ from typing import Any
17
11
 
18
12
  from ._config import base_url
19
13
  from .errors import APIError, AuthenticationError
20
14
  from .session import SessionMcp
21
15
 
22
- _INVOCATION_MODE_HEADER = "X-CortexHub-Invocation-Mode"
23
16
  _AGENT_HEADER = "X-CortexHub-Agent"
24
17
  _CONVERSATION_TITLE_HEADER = "X-CortexHub-Conversation-Title"
25
18
  _LAST_USER_MESSAGE_HEADER = "X-CortexHub-Last-User-Message"
@@ -35,11 +28,6 @@ class McpOAuthToken:
35
28
  scope: str = ""
36
29
 
37
30
 
38
- InvocationMode = Literal["interactive", "autonomous"]
39
-
40
- _VALID_INVOCATION_MODES = frozenset({"interactive", "autonomous"})
41
-
42
-
43
31
  @dataclass
44
32
  class McpOAuthSession:
45
33
  """MCP connection using Bearer JWT + optional agent and session headers."""
@@ -49,7 +37,6 @@ class McpOAuthSession:
49
37
  mcp_session_id: str | None = None
50
38
  conversation_title: str | None = None
51
39
  last_user_message: str | None = None
52
- invocation_mode: InvocationMode | None = None
53
40
  mcp: SessionMcp = field(init=False)
54
41
 
55
42
  def __post_init__(self) -> None:
@@ -64,8 +51,6 @@ class McpOAuthSession:
64
51
  headers[_CONVERSATION_TITLE_HEADER] = self.conversation_title
65
52
  if self.last_user_message:
66
53
  headers[_LAST_USER_MESSAGE_HEADER] = self.last_user_message
67
- if self.invocation_mode:
68
- headers[_INVOCATION_MODE_HEADER] = self.invocation_mode
69
54
  self.mcp = SessionMcp(url=f"{base_url()}/v1/mcp", headers=headers)
70
55
 
71
56
 
@@ -122,32 +107,11 @@ class CortexhubMcpOAuthClient:
122
107
  mcp_session_id: str | None = None,
123
108
  conversation_title: str | None = None,
124
109
  last_user_message: str | None = None,
125
- invocation_mode: InvocationMode | None = None,
126
110
  refresh: bool = False,
127
111
  ) -> McpOAuthSession:
128
- """Return MCP headers for ``agent`` (required on every call).
129
-
130
- Pass ``mcp_session_id`` (your chat or conversation id) to group tool
131
- activity into a single workspace session.
132
-
133
- Pass ``conversation_title`` and ``last_user_message`` to add context
134
- that operators can see when reviewing this session in CortexHub
135
- (sent on every MCP request via headers).
136
-
137
- Pass ``invocation_mode``:
138
-
139
- * ``"interactive"`` (default for OAuth callers) -- a human is
140
- present and can answer in-client consent prompts.
141
- * ``"autonomous"`` -- cron jobs, queue workers, webhook handlers,
142
- and other unattended runs. The gateway routes consent through
143
- configured personal channels instead of expecting a live answer.
144
- """
112
+ """Return MCP headers for ``agent`` (required on every call)."""
145
113
  if not agent or not agent.strip():
146
114
  raise ValueError("agent= is required.")
147
- if invocation_mode is not None and invocation_mode not in _VALID_INVOCATION_MODES:
148
- raise ValueError(
149
- "invocation_mode must be 'interactive' or 'autonomous'."
150
- )
151
115
  token = self.fetch_token(refresh=refresh)
152
116
  session_id = (mcp_session_id or "").strip() or None
153
117
  title = (conversation_title or "").strip() or None
@@ -162,7 +126,6 @@ class CortexhubMcpOAuthClient:
162
126
  mcp_session_id=session_id,
163
127
  conversation_title=title,
164
128
  last_user_message=user_message,
165
- invocation_mode=invocation_mode,
166
129
  )
167
130
 
168
131
 
@@ -1,104 +0,0 @@
1
- # Python
2
- __pycache__/
3
- *.py[cod]
4
- *$py.class
5
- *.so
6
- .Python
7
- build/
8
- develop-eggs/
9
- dist/
10
- downloads/
11
- eggs/
12
- .eggs/
13
- lib/
14
- lib64/
15
- parts/
16
- sdist/
17
- var/
18
- wheels/
19
- *.egg-info/
20
- .installed.cfg
21
- *.egg
22
- .pytest_cache/
23
- .ruff_cache/
24
- .mypy_cache/
25
- .coverage
26
- htmlcov/
27
- .venv/
28
- venv/
29
- ENV/
30
- uv.lock
31
-
32
- # Rust
33
- target/
34
- Cargo.lock
35
- **/*.rs.bk
36
- *.pdb
37
-
38
- # Go
39
- *.exe
40
- *.exe~
41
- *.dll
42
- *.so
43
- *.dylib
44
- *.test
45
- *.out
46
- go.work
47
- vendor/
48
-
49
- # Java
50
- target/
51
- pom.xml.tag
52
- pom.xml.releaseBackup
53
- pom.xml.versionsBackup
54
- pom.xml.next
55
- release.properties
56
- dependency-reduced-pom.xml
57
- buildNumber.properties
58
- .mvn/timing.properties
59
- .mvn/wrapper/maven-wrapper.jar
60
- *.class
61
- *.jar
62
- *.war
63
- *.ear
64
- hs_err_pid*
65
-
66
- # TypeScript/JavaScript
67
- node_modules/
68
- dist/
69
- build/
70
- *.tsbuildinfo
71
- .turbo/
72
- .next/
73
- .cache/
74
- coverage/
75
-
76
- # IDE
77
- .vscode/
78
- .idea/
79
- *.swp
80
- *.swo
81
- *~
82
- .DS_Store
83
-
84
- # Logs
85
- *.log
86
- npm-debug.log*
87
- yarn-debug.log*
88
- yarn-error.log*
89
- pnpm-debug.log*
90
-
91
- # Environment
92
- .env
93
- .env.local
94
- .env.*.local
95
- .pypirc
96
-
97
- # OS
98
- .DS_Store
99
- Thumbs.db
100
- python/cortexhub_data
101
-
102
- .planning/
103
- .cursor/
104
- .claude/
cortexhub-2.0.5/PKG-INFO DELETED
@@ -1,105 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: cortexhub
3
- Version: 2.0.5
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 client for the **CortexHub MCP gateway**.
26
-
27
- This package builds the URL and headers your MCP transport needs to call
28
- `https://mcp.cortexhub.ai/v1/mcp`. It does not call the CortexHub
29
- Platform API; for organisation and workspace management, see the
30
- [Platform API reference](https://docs.cortexhub.ai/docs/rest-api/overview).
31
-
32
- [Documentation](https://docs.cortexhub.ai/docs/sdks/overview)
33
-
34
- ## Install
35
-
36
- ```bash
37
- pip install cortexhub
38
- ```
39
-
40
- ## Two ways to authenticate
41
-
42
- The SDK supports both gateway authentication paths through one entry
43
- point. Pick the one that matches how your application identifies users.
44
-
45
- ### Workspace MCP API key (recommended for backends)
46
-
47
- Use this when your application has its own users who do not have
48
- CortexHub accounts. The workspace key authenticates the gateway; the
49
- end-user identity is attested per call.
50
-
51
- Mint the key from **Workspace settings → MCP API keys** in the
52
- CortexHub dashboard, or programmatically via the Platform API.
53
-
54
- ```python
55
- from cortexhub import Cortexhub
56
-
57
- cx = Cortexhub(api_key="cxh_mcpk_<id>_<secret>")
58
- session = cx.session(
59
- agent="invoice-bot",
60
- end_user_subject="user_42", # required for end-user accountability policies
61
- end_user_display_hint="Alice", # optional, render-only, never persisted
62
- invocation_mode="autonomous", # default; pass "interactive" if a human is present
63
- )
64
- # session.mcp.url and session.mcp.headers → pass to your MCP transport
65
- ```
66
-
67
- ### MCP OAuth client
68
-
69
- Use this when your application signs in CortexHub users interactively.
70
- Create the OAuth client from **Account settings → MCP OAuth clients** and
71
- copy the `client_id` and `client_secret`.
72
-
73
- ```python
74
- from cortexhub import Cortexhub
75
-
76
- cx = Cortexhub(client_id="...", client_secret="...")
77
- session = cx.session(
78
- agent="helpdesk-bot",
79
- mcp_session_id="chat-42", # optional: groups activity per session
80
- conversation_title="Engineering standup", # optional: context shown in audit
81
- last_user_message="Create a standup page", # optional: context shown in audit
82
- )
83
- ```
84
-
85
- ## Environment variables
86
-
87
- | Variable | Default | Purpose |
88
- |---|---|---|
89
- | `CORTEXHUB_URL` | `https://mcp.cortexhub.ai` | MCP gateway base URL |
90
- | `CORTEXHUB_API_KEY` | — | Workspace MCP API key (`cxh_mcpk_*`) |
91
- | `CORTEXHUB_CLIENT_ID` | — | MCP OAuth client id |
92
- | `CORTEXHUB_CLIENT_SECRET` | — | MCP OAuth client secret |
93
-
94
- If both `CORTEXHUB_API_KEY` and OAuth credentials are configured, the
95
- API key wins.
96
-
97
- ## What the SDK returns
98
-
99
- In both modes, `session.mcp.url` and `session.mcp.headers` are ready to
100
- wire into the MCP transport of your choice (the official MCP Python SDK,
101
- a custom HTTP client, anything that accepts URL + headers).
102
-
103
- ## License
104
-
105
- MIT.
cortexhub-2.0.5/README.md DELETED
@@ -1,83 +0,0 @@
1
- # cortexhub
2
-
3
- Official Python client for the **CortexHub MCP gateway**.
4
-
5
- This package builds the URL and headers your MCP transport needs to call
6
- `https://mcp.cortexhub.ai/v1/mcp`. It does not call the CortexHub
7
- Platform API; for organisation and workspace management, see the
8
- [Platform API reference](https://docs.cortexhub.ai/docs/rest-api/overview).
9
-
10
- [Documentation](https://docs.cortexhub.ai/docs/sdks/overview)
11
-
12
- ## Install
13
-
14
- ```bash
15
- pip install cortexhub
16
- ```
17
-
18
- ## Two ways to authenticate
19
-
20
- The SDK supports both gateway authentication paths through one entry
21
- point. Pick the one that matches how your application identifies users.
22
-
23
- ### Workspace MCP API key (recommended for backends)
24
-
25
- Use this when your application has its own users who do not have
26
- CortexHub accounts. The workspace key authenticates the gateway; the
27
- end-user identity is attested per call.
28
-
29
- Mint the key from **Workspace settings → MCP API keys** in the
30
- CortexHub dashboard, or programmatically via the Platform API.
31
-
32
- ```python
33
- from cortexhub import Cortexhub
34
-
35
- cx = Cortexhub(api_key="cxh_mcpk_<id>_<secret>")
36
- session = cx.session(
37
- agent="invoice-bot",
38
- end_user_subject="user_42", # required for end-user accountability policies
39
- end_user_display_hint="Alice", # optional, render-only, never persisted
40
- invocation_mode="autonomous", # default; pass "interactive" if a human is present
41
- )
42
- # session.mcp.url and session.mcp.headers → pass to your MCP transport
43
- ```
44
-
45
- ### MCP OAuth client
46
-
47
- Use this when your application signs in CortexHub users interactively.
48
- Create the OAuth client from **Account settings → MCP OAuth clients** and
49
- copy the `client_id` and `client_secret`.
50
-
51
- ```python
52
- from cortexhub import Cortexhub
53
-
54
- cx = Cortexhub(client_id="...", client_secret="...")
55
- session = cx.session(
56
- agent="helpdesk-bot",
57
- mcp_session_id="chat-42", # optional: groups activity per session
58
- conversation_title="Engineering standup", # optional: context shown in audit
59
- last_user_message="Create a standup page", # optional: context shown in audit
60
- )
61
- ```
62
-
63
- ## Environment variables
64
-
65
- | Variable | Default | Purpose |
66
- |---|---|---|
67
- | `CORTEXHUB_URL` | `https://mcp.cortexhub.ai` | MCP gateway base URL |
68
- | `CORTEXHUB_API_KEY` | — | Workspace MCP API key (`cxh_mcpk_*`) |
69
- | `CORTEXHUB_CLIENT_ID` | — | MCP OAuth client id |
70
- | `CORTEXHUB_CLIENT_SECRET` | — | MCP OAuth client secret |
71
-
72
- If both `CORTEXHUB_API_KEY` and OAuth credentials are configured, the
73
- API key wins.
74
-
75
- ## What the SDK returns
76
-
77
- In both modes, `session.mcp.url` and `session.mcp.headers` are ready to
78
- wire into the MCP transport of your choice (the official MCP Python SDK,
79
- a custom HTTP client, anything that accepts URL + headers).
80
-
81
- ## License
82
-
83
- MIT.
@@ -1,11 +0,0 @@
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("/")
@@ -1,150 +0,0 @@
1
- """Workspace MCP API key client.
2
-
3
- Use this when your backend acts on behalf of users who do not have
4
- CortexHub identities. The workspace MCP API key authenticates the
5
- gateway; the end-user identity is attested per call via
6
- ``X-CortexHub-End-User-Subject``. No CortexHub user row is created
7
- for the end user, no email is required, no PII is stored.
8
-
9
- For applications that sign in CortexHub users interactively, see
10
- :mod:`cortexhub.mcp_oauth` instead.
11
- """
12
-
13
- from __future__ import annotations
14
-
15
- from dataclasses import dataclass, field
16
- from typing import Literal
17
-
18
- from ._config import base_url
19
- from .session import SessionMcp
20
-
21
- _KEY_HEADER = "X-CortexHub-Key"
22
- _AGENT_HEADER = "X-CortexHub-Agent"
23
- _END_USER_SUBJECT_HEADER = "X-CortexHub-End-User-Subject"
24
- _END_USER_DISPLAY_HINT_HEADER = "X-CortexHub-End-User-Display-Hint"
25
- _INVOCATION_MODE_HEADER = "X-CortexHub-Invocation-Mode"
26
-
27
- InvocationMode = Literal["interactive", "autonomous"]
28
-
29
- _VALID_INVOCATION_MODES = frozenset({"interactive", "autonomous"})
30
-
31
- _KEY_PREFIX = "cxh_mcpk_"
32
-
33
-
34
- @dataclass
35
- class McpKeySession:
36
- """MCP connection using a workspace API key + per-call end-user attestation.
37
-
38
- Wire into your MCP transport via ``session.mcp.url`` and
39
- ``session.mcp.headers``.
40
- """
41
-
42
- api_key: str
43
- agent: str
44
- mcp_session_id: str | None = None
45
- end_user_subject: str | None = None
46
- end_user_display_hint: str | None = None
47
- invocation_mode: InvocationMode | None = None
48
- mcp: SessionMcp = field(init=False)
49
-
50
- def __post_init__(self) -> None:
51
- headers: dict[str, str] = {
52
- _KEY_HEADER: self.api_key,
53
- _AGENT_HEADER: self.agent,
54
- }
55
- if self.mcp_session_id:
56
- headers["Mcp-Session-Id"] = self.mcp_session_id
57
- if self.end_user_subject:
58
- headers[_END_USER_SUBJECT_HEADER] = self.end_user_subject
59
- if self.end_user_display_hint:
60
- headers[_END_USER_DISPLAY_HINT_HEADER] = self.end_user_display_hint
61
- if self.invocation_mode:
62
- headers[_INVOCATION_MODE_HEADER] = self.invocation_mode
63
- self.mcp = SessionMcp(url=f"{base_url()}/v1/mcp", headers=headers)
64
-
65
-
66
- class CortexhubKeyClient:
67
- """Send MCP gateway calls authenticated by a workspace MCP API key.
68
-
69
- The key looks like ``cxh_mcpk_<id>_<secret>`` and is minted in your
70
- workspace settings (or via the Platform API). It is tenant-scoped: one
71
- key, one workspace.
72
-
73
- Unlike OAuth this is **not** a token-exchange flow. The key itself is
74
- sent on every request as ``X-CortexHub-Key``. There is nothing to
75
- refresh and no JWT involved.
76
- """
77
-
78
- def __init__(self, *, api_key: str) -> None:
79
- cleaned = (api_key or "").strip()
80
- if not cleaned:
81
- raise ValueError("api_key= is required.")
82
- if not cleaned.startswith(_KEY_PREFIX):
83
- raise ValueError(
84
- f"api_key must start with {_KEY_PREFIX!r}. Workspace MCP API "
85
- "keys begin with this prefix; if you have an OAuth client_id "
86
- "and client_secret instead, use the OAuth credentials path."
87
- )
88
- self.api_key = cleaned
89
-
90
- @property
91
- def masked_key(self) -> str:
92
- """Return the key id portion with the secret masked, for logs and repr."""
93
- # The key splits on the FIRST underscore after the prefix. The id
94
- # tail is base36 (no underscores); the secret may contain
95
- # underscores. So we find the first separator AFTER the prefix.
96
- sep = self.api_key.find("_", len(_KEY_PREFIX))
97
- if sep <= len(_KEY_PREFIX):
98
- return self.api_key[:12] + "…"
99
- return self.api_key[:sep] + "_…"
100
-
101
- def session(
102
- self,
103
- *,
104
- agent: str,
105
- mcp_session_id: str | None = None,
106
- end_user_subject: str | None = None,
107
- end_user_display_hint: str | None = None,
108
- invocation_mode: InvocationMode | None = None,
109
- ) -> McpKeySession:
110
- """Return MCP transport headers for a single agent call.
111
-
112
- ``agent`` is the workspace agent reference (a human-friendly slug
113
- or a ``cxh_agent_*`` id). On first sight of a new ref the gateway
114
- creates the agent inside the workspace; subsequent calls reuse it.
115
-
116
- ``end_user_subject`` is the opaque identifier of the user the call
117
- is acting on behalf of. The gateway requires it for any policy
118
- with end-user accountability; missing it on such a call returns
119
- HTTP 400. The string is yours, the only constraint is that it
120
- identifies the same end user consistently across calls.
121
-
122
- ``end_user_display_hint`` is an optional short label shown in
123
- consent dialogs (e.g. ``"Alice"``). It is render-only and is
124
- **never** persisted on any audit, decision, receipt, or span row.
125
-
126
- ``mcp_session_id`` groups tool activity into a single workspace
127
- session.
128
-
129
- ``invocation_mode`` defaults to ``"autonomous"`` on the gateway
130
- for API-key callers; set ``"interactive"`` explicitly if a human
131
- is present at the time of the call and can answer in-client
132
- consent prompts.
133
- """
134
- if not agent or not agent.strip():
135
- raise ValueError("agent= is required.")
136
- if invocation_mode is not None and invocation_mode not in _VALID_INVOCATION_MODES:
137
- raise ValueError(
138
- "invocation_mode must be 'interactive' or 'autonomous'."
139
- )
140
- return McpKeySession(
141
- api_key=self.api_key,
142
- agent=agent.strip(),
143
- mcp_session_id=(mcp_session_id or "").strip() or None,
144
- end_user_subject=(end_user_subject or "").strip() or None,
145
- end_user_display_hint=(end_user_display_hint or "").strip() or None,
146
- invocation_mode=invocation_mode,
147
- )
148
-
149
- def __repr__(self) -> str:
150
- return f"CortexhubKeyClient(api_key={self.masked_key!r})"
File without changes