cortexhub 2.0.3__tar.gz → 2.0.4__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cortexhub
3
- Version: 2.0.3
3
+ Version: 2.0.4
4
4
  Summary: MCP gateway client for CortexHub programmatic agent access.
5
5
  Project-URL: Homepage, https://cortexhub.ai
6
6
  Project-URL: Documentation, https://docs.cortexhub.ai
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cortexhub"
3
- version = "2.0.3"
3
+ version = "2.0.4"
4
4
  description = "MCP gateway client for CortexHub programmatic agent access."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -0,0 +1,42 @@
1
+ """cortexhub - programmatic MCP gateway access.
2
+
3
+ Two authentication paths through one entry point:
4
+
5
+ .. code-block:: python
6
+
7
+ # Workspace MCP API key (recommended for backends):
8
+ from cortexhub import Cortexhub
9
+ cx = Cortexhub(api_key="cxh_mcpk_<id>_<secret>")
10
+ session = cx.session(agent="invoice-bot", end_user_subject="user_42")
11
+
12
+ # MCP OAuth client (interactive CortexHub users):
13
+ cx = Cortexhub(client_id="...", client_secret="...")
14
+ session = cx.session(agent="helpdesk-bot")
15
+
16
+ In either case ``session.mcp.url`` and ``session.mcp.headers`` are ready
17
+ to wire into your MCP transport.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from .client import Cortexhub
23
+ from .errors import APIError, AuthenticationError, ConfigurationError, CortexhubError
24
+ from .mcp_key import CortexhubKeyClient, McpKeySession
25
+ from .mcp_oauth import CortexhubMcpOAuthClient, McpOAuthSession, McpOAuthToken
26
+ from .session import SessionMcp
27
+
28
+ __version__ = "2.0.4"
29
+ __all__ = [
30
+ "Cortexhub",
31
+ "CortexhubKeyClient",
32
+ "CortexhubMcpOAuthClient",
33
+ "McpKeySession",
34
+ "McpOAuthSession",
35
+ "McpOAuthToken",
36
+ "SessionMcp",
37
+ "CortexhubError",
38
+ "ConfigurationError",
39
+ "AuthenticationError",
40
+ "APIError",
41
+ "__version__",
42
+ ]
@@ -0,0 +1,185 @@
1
+ """``Cortexhub`` - programmatic MCP gateway client.
2
+
3
+ Two authentication paths are supported through one entry point:
4
+
5
+ * **Workspace MCP API key** (recommended for backends whose end users do
6
+ not have CortexHub accounts):
7
+
8
+ .. code-block:: python
9
+
10
+ cx = Cortexhub(api_key="cxh_mcpk_<id>_<secret>")
11
+ session = cx.session(agent="invoice-bot", end_user_subject="user_42")
12
+
13
+ * **MCP OAuth client** (when your application signs in CortexHub users):
14
+
15
+ .. code-block:: python
16
+
17
+ cx = Cortexhub(client_id="...", client_secret="...")
18
+ session = cx.session(agent="helpdesk-bot")
19
+
20
+ Each ``session()`` call returns ``.mcp.url`` and ``.mcp.headers`` ready
21
+ to wire into the MCP transport of your choice.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import os
27
+ from typing import Literal
28
+
29
+ from .errors import ConfigurationError
30
+ from .mcp_key import CortexhubKeyClient, McpKeySession
31
+ from .mcp_oauth import CortexhubMcpOAuthClient, McpOAuthSession, McpOAuthToken
32
+
33
+
34
+ class Cortexhub:
35
+ """MCP gateway client. Pass either a workspace API key OR OAuth credentials.
36
+
37
+ Environment variables (optional fallbacks):
38
+
39
+ - ``CORTEXHUB_API_KEY`` -- workspace MCP API key (``cxh_mcpk_*``)
40
+ - ``CORTEXHUB_CLIENT_ID`` and ``CORTEXHUB_CLIENT_SECRET`` -- MCP OAuth credentials
41
+ - ``CORTEXHUB_URL`` -- gateway base URL (default ``https://mcp.cortexhub.ai``)
42
+
43
+ Exactly one credential path must be present. If both an API key and
44
+ OAuth credentials are configured, the API key takes precedence.
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ *,
50
+ api_key: str | None = None,
51
+ client_id: str | None = None,
52
+ client_secret: str | None = None,
53
+ token_url: str | None = None,
54
+ ) -> None:
55
+ resolved_key = (api_key or os.environ.get("CORTEXHUB_API_KEY") or "").strip()
56
+ resolved_id = (client_id or os.environ.get("CORTEXHUB_CLIENT_ID") or "").strip()
57
+ resolved_secret = (
58
+ client_secret or os.environ.get("CORTEXHUB_CLIENT_SECRET") or ""
59
+ ).strip()
60
+
61
+ if resolved_key:
62
+ self._key_backend: CortexhubKeyClient | None = CortexhubKeyClient(
63
+ api_key=resolved_key
64
+ )
65
+ self._oauth_backend: CortexhubMcpOAuthClient | None = None
66
+ self._mode: Literal["key", "oauth"] = "key"
67
+ return
68
+
69
+ if resolved_id and resolved_secret:
70
+ kwargs: dict[str, str] = {
71
+ "client_id": resolved_id,
72
+ "client_secret": resolved_secret,
73
+ }
74
+ if token_url:
75
+ kwargs["token_url"] = token_url.strip()
76
+ self._key_backend = None
77
+ self._oauth_backend = CortexhubMcpOAuthClient(**kwargs)
78
+ self._mode = "oauth"
79
+ return
80
+
81
+ raise ConfigurationError(
82
+ "Missing credentials. Pass api_key= (workspace MCP API key) OR "
83
+ "client_id= and client_secret= (MCP OAuth client). You can also "
84
+ "set CORTEXHUB_API_KEY, or CORTEXHUB_CLIENT_ID and "
85
+ "CORTEXHUB_CLIENT_SECRET."
86
+ )
87
+
88
+ @property
89
+ def mode(self) -> Literal["key", "oauth"]:
90
+ """Which authentication path this client is using."""
91
+ return self._mode
92
+
93
+ def session(
94
+ self,
95
+ *,
96
+ agent: str,
97
+ mcp_session_id: str | None = None,
98
+ end_user_subject: str | None = None,
99
+ end_user_display_hint: str | None = None,
100
+ conversation_title: str | None = None,
101
+ last_user_message: str | None = None,
102
+ invocation_mode: Literal["interactive", "autonomous"] | None = None,
103
+ refresh: bool = False,
104
+ ) -> McpKeySession | McpOAuthSession:
105
+ """Return MCP transport details (``.mcp.url`` and ``.mcp.headers``).
106
+
107
+ ``agent`` is required on every call.
108
+
109
+ **Workspace API key mode**: pass ``end_user_subject`` to attest
110
+ the end user the call is acting on behalf of. The gateway
111
+ requires it for any policy with end-user accountability; missing
112
+ it on such a call returns HTTP 400. ``end_user_display_hint`` is
113
+ an optional short label shown in consent dialogs and is never
114
+ persisted.
115
+
116
+ **OAuth mode**: ``end_user_subject`` and ``end_user_display_hint``
117
+ are ignored. ``conversation_title`` and ``last_user_message`` are
118
+ attached so operators can see session context when reviewing
119
+ spans for this session in CortexHub.
120
+
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
+ ``refresh`` only applies to OAuth mode -- force a refresh-token
129
+ exchange instead of reusing the cached token.
130
+ """
131
+ if self._mode == "key":
132
+ assert self._key_backend is not None
133
+ return self._key_backend.session(
134
+ agent=agent,
135
+ mcp_session_id=mcp_session_id,
136
+ end_user_subject=end_user_subject,
137
+ end_user_display_hint=end_user_display_hint,
138
+ invocation_mode=invocation_mode,
139
+ )
140
+ assert self._oauth_backend is not None
141
+ return self._oauth_backend.session(
142
+ agent=agent,
143
+ mcp_session_id=mcp_session_id,
144
+ conversation_title=conversation_title,
145
+ last_user_message=last_user_message,
146
+ invocation_mode=invocation_mode,
147
+ refresh=refresh,
148
+ )
149
+
150
+ @property
151
+ def client_id(self) -> str:
152
+ """OAuth ``client_id`` when in OAuth mode. Empty string in key mode."""
153
+ return self._oauth_backend.client_id if self._oauth_backend else ""
154
+
155
+ @property
156
+ def client_secret(self) -> str:
157
+ """OAuth ``client_secret`` when in OAuth mode. Empty string in key mode."""
158
+ return self._oauth_backend.client_secret if self._oauth_backend else ""
159
+
160
+ @property
161
+ def token_url(self) -> str:
162
+ """OAuth token URL when in OAuth mode. Empty string in key mode."""
163
+ return self._oauth_backend.token_url if self._oauth_backend else ""
164
+
165
+ def fetch_token(self, *, refresh: bool = False) -> McpOAuthToken:
166
+ """OAuth-mode only. Mint or refresh an access token directly.
167
+
168
+ Raises ``RuntimeError`` if the client was built with a workspace
169
+ API key -- those do not require a token exchange.
170
+ """
171
+ if self._oauth_backend is None:
172
+ raise RuntimeError(
173
+ "fetch_token() is only available when the client was built "
174
+ "with client_id and client_secret. Workspace API keys do not "
175
+ "require a token exchange."
176
+ )
177
+ return self._oauth_backend.fetch_token(refresh=refresh)
178
+
179
+ def __repr__(self) -> str:
180
+ if self._key_backend is not None:
181
+ return f"Cortexhub(api_key={self._key_backend.masked_key!r})"
182
+ assert self._oauth_backend is not None
183
+ cid = self._oauth_backend.client_id
184
+ prefix = cid[:12] + "…" if len(cid) > 12 else cid
185
+ return f"Cortexhub(client_id={prefix!r})"
@@ -0,0 +1,150 @@
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})"
@@ -1,4 +1,10 @@
1
- """Member MCP OAuth programmatic client."""
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
+ """
2
8
 
3
9
  from __future__ import annotations
4
10
 
@@ -29,9 +35,9 @@ class McpOAuthToken:
29
35
  scope: str = ""
30
36
 
31
37
 
32
- InvocationMode = Literal["interactive", "scheduled", "programmatic"]
38
+ InvocationMode = Literal["interactive", "autonomous"]
33
39
 
34
- _VALID_INVOCATION_MODES = frozenset({"interactive", "scheduled", "programmatic"})
40
+ _VALID_INVOCATION_MODES = frozenset({"interactive", "autonomous"})
35
41
 
36
42
 
37
43
  @dataclass
@@ -119,22 +125,28 @@ class CortexhubMcpOAuthClient:
119
125
  invocation_mode: InvocationMode | None = None,
120
126
  refresh: bool = False,
121
127
  ) -> McpOAuthSession:
122
- """Return MCP headers for ``agent`` (required on every programmatic call).
128
+ """Return MCP headers for ``agent`` (required on every call).
123
129
 
124
130
  Pass ``mcp_session_id`` (your chat or conversation id) to group tool
125
- activity into separate rows in CortexHub Cloud.
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).
126
136
 
127
- Pass ``conversation_title`` and ``last_user_message`` so operators can
128
- see session context in the portal (sent on every MCP request via headers).
137
+ Pass ``invocation_mode``:
129
138
 
130
- Pass ``invocation_mode`` for cron or background workers when policy allows
131
- unattended execution; omit for interactive sessions (gateway default).
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.
132
144
  """
133
145
  if not agent or not agent.strip():
134
- raise ValueError("agent= is required for programmatic MCP OAuth.")
146
+ raise ValueError("agent= is required.")
135
147
  if invocation_mode is not None and invocation_mode not in _VALID_INVOCATION_MODES:
136
148
  raise ValueError(
137
- "invocation_mode must be interactive, scheduled, or programmatic."
149
+ "invocation_mode must be 'interactive' or 'autonomous'."
138
150
  )
139
151
  token = self.fetch_token(refresh=refresh)
140
152
  session_id = (mcp_session_id or "").strip() or None
@@ -1,30 +0,0 @@
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.2.0"
19
- __all__ = [
20
- "Cortexhub",
21
- "CortexhubMcpOAuthClient",
22
- "McpOAuthSession",
23
- "McpOAuthToken",
24
- "SessionMcp",
25
- "CortexhubError",
26
- "ConfigurationError",
27
- "AuthenticationError",
28
- "APIError",
29
- "__version__",
30
- ]
@@ -1,68 +0,0 @@
1
- """``Cortexhub`` - programmatic MCP access via member MCP OAuth."""
2
-
3
- from __future__ import annotations
4
-
5
- import os
6
- from typing import Literal
7
-
8
- from .errors import ConfigurationError
9
- from .mcp_oauth import CortexhubMcpOAuthClient, McpOAuthSession
10
-
11
-
12
- class Cortexhub(CortexhubMcpOAuthClient):
13
- """MCP gateway client using a member MCP OAuth client.
14
-
15
- Environment variables (optional):
16
-
17
- - ``CORTEXHUB_CLIENT_ID``
18
- - ``CORTEXHUB_CLIENT_SECRET``
19
- - ``CORTEXHUB_URL`` (default ``https://mcp.cortexhub.ai``)
20
- """
21
-
22
- def __init__(
23
- self,
24
- *,
25
- client_id: str | None = None,
26
- client_secret: str | None = None,
27
- token_url: str | None = None,
28
- ) -> None:
29
- resolved_id = (client_id or os.environ.get("CORTEXHUB_CLIENT_ID") or "").strip()
30
- resolved_secret = (
31
- client_secret or os.environ.get("CORTEXHUB_CLIENT_SECRET") or ""
32
- ).strip()
33
- if not resolved_id or not resolved_secret:
34
- raise ConfigurationError(
35
- "Missing OAuth client credentials. Pass client_id= and client_secret= "
36
- "or set CORTEXHUB_CLIENT_ID and CORTEXHUB_CLIENT_SECRET."
37
- )
38
- kwargs: dict[str, str] = {
39
- "client_id": resolved_id,
40
- "client_secret": resolved_secret,
41
- }
42
- if token_url:
43
- kwargs["token_url"] = token_url.strip()
44
- super().__init__(**kwargs)
45
-
46
- def session(
47
- self,
48
- *,
49
- agent: str,
50
- mcp_session_id: str | None = None,
51
- conversation_title: str | None = None,
52
- last_user_message: str | None = None,
53
- invocation_mode: Literal["interactive", "scheduled", "programmatic"] | None = None,
54
- refresh: bool = False,
55
- ) -> McpOAuthSession:
56
- """Return MCP headers for ``agent`` (required on every programmatic call)."""
57
- return super().session(
58
- agent=agent,
59
- mcp_session_id=mcp_session_id,
60
- conversation_title=conversation_title,
61
- last_user_message=last_user_message,
62
- invocation_mode=invocation_mode,
63
- refresh=refresh,
64
- )
65
-
66
- def __repr__(self) -> str:
67
- prefix = self.client_id[:12] + "…" if len(self.client_id) > 12 else self.client_id
68
- return f"Cortexhub(client_id={prefix!r})"
File without changes
File without changes
File without changes