cortexhub 3.1.0__tar.gz → 3.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cortexhub
3
- Version: 3.1.0
3
+ Version: 3.2.0
4
4
  Summary: CortexHub platform SDK: point your agent at the governed LLM router + MCP gateway.
5
5
  Project-URL: Homepage, https://cortexhub.ai
6
6
  Project-URL: Documentation, https://docs.cortexhub.ai
@@ -21,10 +21,10 @@ Requires-Python: >=3.10
21
21
  Provides-Extra: ai
22
22
  Requires-Dist: openai>=1.40; extra == 'ai'
23
23
  Provides-Extra: all
24
- Requires-Dist: mcp>=1.0; extra == 'all'
24
+ Requires-Dist: mcp<2,>=1.0; extra == 'all'
25
25
  Requires-Dist: openai>=1.40; extra == 'all'
26
26
  Provides-Extra: mcp
27
- Requires-Dist: mcp>=1.0; extra == 'mcp'
27
+ Requires-Dist: mcp<2,>=1.0; extra == 'mcp'
28
28
  Description-Content-Type: text/markdown
29
29
 
30
30
  # cortexhub
@@ -57,8 +57,12 @@ API keys, or the agent's page). The `cxh_key_...` *is* that agent's identity -
57
57
  every call is attributed, governed, and metered to it. No agent argument needed.
58
58
 
59
59
  ```python
60
+ import cortexhub
61
+ cx = cortexhub.init("cxh_key_...") # or set CORTEXHUB_API_KEY
62
+
63
+ # equivalently:
60
64
  from cortexhub import Cortexhub
61
- cx = Cortexhub(api_key="cxh_key_...") # or set CORTEXHUB_API_KEY
65
+ cx = Cortexhub(api_key="cxh_key_...")
62
66
  ```
63
67
 
64
68
  ## Run a session (recommended)
@@ -165,24 +169,31 @@ need tools (no session grouping).
165
169
 
166
170
  One session, end to end: the model reasons with `s.llm`, acts through the
167
171
  governed `cortexhub_*` tools on `s.mcp`, and when a governed action needs the end
168
- user's **approval** it comes back parked with a signed `consent_url` -- you show
169
- that to the user and poll until they decide in CortexHub. Needs both extras:
170
- `pip install 'cortexhub[ai,mcp]'`.
171
-
172
- > **How consent reaches your user.** The gateway picks the consent surface from
173
- > what your MCP client declares at initialize. A UI host that declares the
174
- > MCP-UI / Tasks extension (e.g. claude.ai) gets consent rendered **inline**. A
175
- > plain backend client like the one below declares neither, so the gateway hands
176
- > it the **`consent_url` fallback** shown here -- a signed link you surface to
177
- > your end user however your app does UI (a page, an email, a Slack DM), then
178
- > poll `cortexhub_get_task` for the decision. This is the right pattern for a
179
- > headless or autonomous agent (there is no host to render inline consent).
172
+ user's **approval** it comes back parked, carrying an `approval_id` and the
173
+ `presentation` (headline / sections / summary) of what will happen. Needs both
174
+ extras: `pip install 'cortexhub[ai,mcp]'`.
175
+
176
+ > **How consent reaches your user.** Your agent is headless, so *you* own the
177
+ > consent UI. When a call parks, read the `approval_id` + `presentation` from the
178
+ > result, show it to your end user however your app does UI, and when they decide
179
+ > submit it through the SDK:
180
+ >
181
+ > ```python
182
+ > s.decide(approval_id, "approve", note="ok by me") # or "deny"
183
+ > ```
184
+ >
185
+ > `s.decide` records the decision as *that end user's* consent -- no CortexHub
186
+ > account for the end user is required -- bound to the same agent + `end_user_subject`
187
+ > this session runs as. Then poll `cortexhub_get_task` (below): an approved call
188
+ > runs server-side and its result comes back. If you'd rather not build any UI,
189
+ > the parked result also carries a signed **`consent_url`** you can hand the user
190
+ > to approve in a browser instead. (A UI host that declares the MCP-UI extension,
191
+ > e.g. claude.ai, gets consent rendered inline and never reaches this path.)
180
192
 
181
193
  ```python
182
194
  import asyncio, json
183
195
  from cortexhub import Cortexhub
184
196
  from mcp import ClientSession
185
- from mcp.client.streamable_http import streamablehttp_client
186
197
 
187
198
  cx = Cortexhub(api_key="cxh_key_...")
188
199
 
@@ -190,7 +201,8 @@ async def run_turn(user_text: str) -> str:
190
201
  # One session for this end user's conversation -> LLM + tools share it.
191
202
  s = cx.session(agent="support-bot", mcp_session_id="conv-42", end_user_subject="user_42")
192
203
 
193
- async with streamablehttp_client(s.mcp.url, headers=s.mcp.headers) as (read, write, _):
204
+ # s.mcp.open() opens the transport across mcp client versions.
205
+ async with s.mcp.open() as (read, write):
194
206
  async with ClientSession(read, write) as mcp:
195
207
  await mcp.initialize()
196
208
 
@@ -218,8 +230,10 @@ async def run_turn(user_text: str) -> str:
218
230
 
219
231
  task = _parked_task(result) # governed action -> needs approval?
220
232
  if task:
221
- print("Approve to continue:", task["consent_url"]) # show the end user
222
- text = await _await_decision(mcp, task["task_id"]) # wait for the decision
233
+ # Show task["presentation"] in YOUR UI and get the user's
234
+ # decision. Here we auto-approve to keep the example runnable.
235
+ s.decide(task["approval_id"], "approve", note="demo auto-approve")
236
+ text = await _await_decision(mcp, task["task_id"]) # resume + read result
223
237
 
224
238
  messages.append({"role": "tool", "tool_call_id": call.id, "content": text})
225
239
  return ""
@@ -238,11 +252,15 @@ def _payload(result):
238
252
  return {}
239
253
 
240
254
  def _parked_task(result):
241
- # A parked approval comes back as an `mcp_task` carrying a signed consent_url.
255
+ # A parked approval comes back as an `mcp_task` carrying an approval_id (and a
256
+ # signed consent_url fallback). The presentation you passed to the tool call
257
+ # rides alongside it, so you can render your own consent UI.
242
258
  def walk(node):
243
259
  if isinstance(node, dict):
244
260
  t = node.get("mcp_task")
245
- if isinstance(t, dict) and t.get("consent_url"):
261
+ if isinstance(t, dict) and t.get("approval_id"):
262
+ if "presentation" in node and "presentation" not in t:
263
+ t = {**t, "presentation": node["presentation"]}
246
264
  return t
247
265
  for v in node.values():
248
266
  if (found := walk(v)):
@@ -28,8 +28,12 @@ API keys, or the agent's page). The `cxh_key_...` *is* that agent's identity -
28
28
  every call is attributed, governed, and metered to it. No agent argument needed.
29
29
 
30
30
  ```python
31
+ import cortexhub
32
+ cx = cortexhub.init("cxh_key_...") # or set CORTEXHUB_API_KEY
33
+
34
+ # equivalently:
31
35
  from cortexhub import Cortexhub
32
- cx = Cortexhub(api_key="cxh_key_...") # or set CORTEXHUB_API_KEY
36
+ cx = Cortexhub(api_key="cxh_key_...")
33
37
  ```
34
38
 
35
39
  ## Run a session (recommended)
@@ -136,24 +140,31 @@ need tools (no session grouping).
136
140
 
137
141
  One session, end to end: the model reasons with `s.llm`, acts through the
138
142
  governed `cortexhub_*` tools on `s.mcp`, and when a governed action needs the end
139
- user's **approval** it comes back parked with a signed `consent_url` -- you show
140
- that to the user and poll until they decide in CortexHub. Needs both extras:
141
- `pip install 'cortexhub[ai,mcp]'`.
142
-
143
- > **How consent reaches your user.** The gateway picks the consent surface from
144
- > what your MCP client declares at initialize. A UI host that declares the
145
- > MCP-UI / Tasks extension (e.g. claude.ai) gets consent rendered **inline**. A
146
- > plain backend client like the one below declares neither, so the gateway hands
147
- > it the **`consent_url` fallback** shown here -- a signed link you surface to
148
- > your end user however your app does UI (a page, an email, a Slack DM), then
149
- > poll `cortexhub_get_task` for the decision. This is the right pattern for a
150
- > headless or autonomous agent (there is no host to render inline consent).
143
+ user's **approval** it comes back parked, carrying an `approval_id` and the
144
+ `presentation` (headline / sections / summary) of what will happen. Needs both
145
+ extras: `pip install 'cortexhub[ai,mcp]'`.
146
+
147
+ > **How consent reaches your user.** Your agent is headless, so *you* own the
148
+ > consent UI. When a call parks, read the `approval_id` + `presentation` from the
149
+ > result, show it to your end user however your app does UI, and when they decide
150
+ > submit it through the SDK:
151
+ >
152
+ > ```python
153
+ > s.decide(approval_id, "approve", note="ok by me") # or "deny"
154
+ > ```
155
+ >
156
+ > `s.decide` records the decision as *that end user's* consent -- no CortexHub
157
+ > account for the end user is required -- bound to the same agent + `end_user_subject`
158
+ > this session runs as. Then poll `cortexhub_get_task` (below): an approved call
159
+ > runs server-side and its result comes back. If you'd rather not build any UI,
160
+ > the parked result also carries a signed **`consent_url`** you can hand the user
161
+ > to approve in a browser instead. (A UI host that declares the MCP-UI extension,
162
+ > e.g. claude.ai, gets consent rendered inline and never reaches this path.)
151
163
 
152
164
  ```python
153
165
  import asyncio, json
154
166
  from cortexhub import Cortexhub
155
167
  from mcp import ClientSession
156
- from mcp.client.streamable_http import streamablehttp_client
157
168
 
158
169
  cx = Cortexhub(api_key="cxh_key_...")
159
170
 
@@ -161,7 +172,8 @@ async def run_turn(user_text: str) -> str:
161
172
  # One session for this end user's conversation -> LLM + tools share it.
162
173
  s = cx.session(agent="support-bot", mcp_session_id="conv-42", end_user_subject="user_42")
163
174
 
164
- async with streamablehttp_client(s.mcp.url, headers=s.mcp.headers) as (read, write, _):
175
+ # s.mcp.open() opens the transport across mcp client versions.
176
+ async with s.mcp.open() as (read, write):
165
177
  async with ClientSession(read, write) as mcp:
166
178
  await mcp.initialize()
167
179
 
@@ -189,8 +201,10 @@ async def run_turn(user_text: str) -> str:
189
201
 
190
202
  task = _parked_task(result) # governed action -> needs approval?
191
203
  if task:
192
- print("Approve to continue:", task["consent_url"]) # show the end user
193
- text = await _await_decision(mcp, task["task_id"]) # wait for the decision
204
+ # Show task["presentation"] in YOUR UI and get the user's
205
+ # decision. Here we auto-approve to keep the example runnable.
206
+ s.decide(task["approval_id"], "approve", note="demo auto-approve")
207
+ text = await _await_decision(mcp, task["task_id"]) # resume + read result
194
208
 
195
209
  messages.append({"role": "tool", "tool_call_id": call.id, "content": text})
196
210
  return ""
@@ -209,11 +223,15 @@ def _payload(result):
209
223
  return {}
210
224
 
211
225
  def _parked_task(result):
212
- # A parked approval comes back as an `mcp_task` carrying a signed consent_url.
226
+ # A parked approval comes back as an `mcp_task` carrying an approval_id (and a
227
+ # signed consent_url fallback). The presentation you passed to the tool call
228
+ # rides alongside it, so you can render your own consent UI.
213
229
  def walk(node):
214
230
  if isinstance(node, dict):
215
231
  t = node.get("mcp_task")
216
- if isinstance(t, dict) and t.get("consent_url"):
232
+ if isinstance(t, dict) and t.get("approval_id"):
233
+ if "presentation" in node and "presentation" not in t:
234
+ t = {**t, "presentation": node["presentation"]}
217
235
  return t
218
236
  for v in node.values():
219
237
  if (found := walk(v)):
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cortexhub"
3
- version = "3.1.0"
3
+ version = "3.2.0"
4
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"
@@ -33,8 +33,11 @@ dependencies = []
33
33
  # pip install 'cortexhub[mcp]' -> the official MCP client for cx.mcp() sessions
34
34
  [project.optional-dependencies]
35
35
  ai = ["openai>=1.40"]
36
- mcp = ["mcp>=1.0"]
37
- all = ["openai>=1.40", "mcp>=1.0"]
36
+ # The CortexHub MCP gateway serves the 1.x Streamable-HTTP transport; the 2.x
37
+ # client's initialize handshake 404s on it. Cap to the gateway's major until it
38
+ # moves to 2.x, so `pip install cortexhub[mcp]` resolves a compatible client.
39
+ mcp = ["mcp>=1.0,<2"]
40
+ all = ["openai>=1.40", "mcp>=1.0,<2"]
38
41
 
39
42
  [project.urls]
40
43
  Homepage = "https://cortexhub.ai"
@@ -31,7 +31,24 @@ from .mcp_key import CortexhubKeyClient, McpKeySession
31
31
  from .mcp_oauth import CortexhubMcpOAuthClient, McpOAuthSession, McpOAuthToken
32
32
  from .session import SessionMcp
33
33
 
34
- __version__ = "3.1.0"
34
+ __version__ = "3.2.0"
35
+
36
+
37
+ def init(api_key: str | None = None, **kwargs: object) -> Cortexhub:
38
+ """Create a CortexHub client. Alias for :class:`Cortexhub`.
39
+
40
+ .. code-block:: python
41
+
42
+ import cortexhub
43
+ cx = cortexhub.init("cxh_key_...")
44
+ s = cx.session(agent="support-bot", end_user_subject="user_42")
45
+ s.llm.chat.completions.create(...) # governed LLM router
46
+ s.mcp # governed MCP tool gateway
47
+ s.decide(approval_id, "approve") # end-user consent, no identity
48
+ """
49
+ return Cortexhub(api_key=api_key, **kwargs) # type: ignore[arg-type]
50
+
51
+
35
52
  __all__ = [
36
53
  "APIError",
37
54
  "AiGateway",
@@ -45,5 +62,6 @@ __all__ = [
45
62
  "McpOAuthSession",
46
63
  "McpOAuthToken",
47
64
  "SessionMcp",
65
+ "init",
48
66
  "__version__",
49
67
  ]
@@ -99,6 +99,72 @@ class McpKeySession:
99
99
  headers[_ROUTER_END_USER_HEADER] = self.end_user_subject
100
100
  return build_ai_gateway(self.api_key).client(default_headers=headers)
101
101
 
102
+ def decide(
103
+ self, approval_id: str, decision: str, note: str | None = None
104
+ ) -> dict[str, Any]:
105
+ """Record this end user's approve/deny for a parked governed tool call.
106
+
107
+ When a tool needs end-user consent, the parked ``cortexhub_invoke_tools``
108
+ result carries an ``approval_id``. Show the action in your own UI however
109
+ you like; when the user decides, call this with that ``approval_id``, their
110
+ ``decision`` (``"approve"`` or ``"deny"``), and an optional ``note``.
111
+ CortexHub records it as the consent of THIS session's end user - no
112
+ CortexHub identity for the end user is required. Then keep polling the task
113
+ (or the invoke retries) until it is terminal; an approved call runs and its
114
+ result comes back.
115
+
116
+ Authenticated by this session's org key + agent + end-user-subject, so the
117
+ decision is bound to the same identity the parked call ran on. Synchronous
118
+ (a plain HTTPS POST, no extra dependencies); returns
119
+ ``{"approval_id", "status", "already_decided"}``.
120
+
121
+ .. code-block:: python
122
+
123
+ s = cx.session(agent="support-bot", end_user_subject="user_42")
124
+ # ... s.mcp tool call parks -> read approval_id from the result ...
125
+ s.decide(approval_id, "approve", note="ok by me")
126
+ """
127
+ import json
128
+ import urllib.error
129
+ import urllib.request
130
+
131
+ from ._config import base_url
132
+ from .errors import APIError
133
+
134
+ norm = (decision or "").strip().lower()
135
+ if norm not in ("approve", "deny"):
136
+ raise ValueError("decision must be 'approve' or 'deny'.")
137
+ if not self.end_user_subject:
138
+ raise ValueError(
139
+ "This session has no end_user_subject; a consent decision must be "
140
+ "bound to the end user the parked call acted for."
141
+ )
142
+ body = json.dumps(
143
+ {"approval_id": approval_id, "decision": norm, "note": note}
144
+ ).encode("utf-8")
145
+ headers = {
146
+ "Content-Type": "application/json",
147
+ _KEY_HEADER: self.api_key,
148
+ _AGENT_HEADER: self.agent,
149
+ _END_USER_SUBJECT_HEADER: self.end_user_subject,
150
+ }
151
+ req = urllib.request.Request(
152
+ f"{base_url()}/v1/consent/decide",
153
+ data=body,
154
+ headers=headers,
155
+ method="POST",
156
+ )
157
+ try:
158
+ with urllib.request.urlopen(req, timeout=30) as resp: # noqa: S310 - https
159
+ return json.loads(resp.read().decode("utf-8"))
160
+ except urllib.error.HTTPError as exc:
161
+ detail = exc.read().decode("utf-8", errors="replace")[:300]
162
+ raise APIError(
163
+ f"decide failed ({exc.code}): {detail}", status=exc.code
164
+ ) from exc
165
+ except urllib.error.URLError as exc:
166
+ raise APIError(f"decide request failed: {exc.reason}") from exc
167
+
102
168
 
103
169
  class CortexhubKeyClient:
104
170
  """Send MCP gateway calls authenticated by an org API key."""
@@ -0,0 +1,89 @@
1
+ """Session types for the MCP gateway connection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from collections.abc import AsyncIterator
7
+ from contextlib import asynccontextmanager
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+
12
+ def _streamable_http_opener() -> Any:
13
+ """A ``(url, headers) -> transport`` opener over the installed ``mcp`` client.
14
+
15
+ The official ``mcp`` client's streamable-HTTP entry point is not stable across
16
+ releases: 1.x exposes ``streamablehttp_client(url, headers=...)``; 2.x renamed
17
+ it to ``streamable_http_client(url, *, http_client=...)`` (headers must be
18
+ baked into an httpx client) and dropped the old name. This adapts to whichever
19
+ is installed so callers never depend on a specific mcp version.
20
+ """
21
+ from mcp.client import streamable_http as module
22
+
23
+ legacy = getattr(module, "streamablehttp_client", None)
24
+ if legacy is not None and "headers" in inspect.signature(legacy).parameters:
25
+
26
+ def _open(url: str, headers: dict[str, str]) -> Any:
27
+ return legacy(url, headers=headers)
28
+
29
+ return _open
30
+
31
+ modern = getattr(module, "streamable_http_client", None)
32
+ if modern is not None:
33
+ params = inspect.signature(modern).parameters
34
+ if "headers" in params:
35
+
36
+ def _open(url: str, headers: dict[str, str]) -> Any:
37
+ return modern(url, headers=headers)
38
+
39
+ return _open
40
+ if "http_client" in params:
41
+ from mcp.client.streamable_http import ( # type: ignore[attr-defined]
42
+ create_mcp_http_client,
43
+ )
44
+
45
+ def _open(url: str, headers: dict[str, str]) -> Any:
46
+ return modern(url, http_client=create_mcp_http_client(headers=headers))
47
+
48
+ return _open
49
+
50
+ raise ImportError( # pragma: no cover - defensive across future renames
51
+ "The installed 'mcp' package has no usable streamable-HTTP client entry point. "
52
+ "Install a supported version with: pip install 'cortexhub[mcp]'"
53
+ )
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class SessionMcp:
58
+ """MCP gateway connection: ``.url`` + ``.headers`` for your MCP transport.
59
+
60
+ Wire these into any MCP client, or use :meth:`open` to open the transport
61
+ directly without touching the mcp client's version-specific entry points.
62
+ """
63
+
64
+ url: str
65
+ headers: dict[str, str] = field(default_factory=dict)
66
+
67
+ @asynccontextmanager
68
+ async def open(self) -> AsyncIterator[tuple[Any, Any]]:
69
+ """Open the streamable-HTTP transport, yielding ``(read, write)`` for
70
+ ``mcp.ClientSession`` -- across mcp client versions (the entry-point name,
71
+ the ``headers`` vs ``http_client`` argument, and the 2- vs 3-tuple yield
72
+ all differ between mcp 1.x and 2.x). Requires ``cortexhub[mcp]``.
73
+
74
+ .. code-block:: python
75
+
76
+ from mcp import ClientSession
77
+
78
+ async with s.mcp.open() as (read, write):
79
+ async with ClientSession(read, write) as mcp:
80
+ await mcp.initialize()
81
+ tools = await mcp.list_tools()
82
+ """
83
+ opener = _streamable_http_opener()
84
+ async with opener(self.url, self.headers) as streams:
85
+ # 2.x yields (read, write); older releases add get_session_id.
86
+ yield streams[0], streams[1]
87
+
88
+
89
+ __all__ = ["SessionMcp"]
@@ -1,13 +0,0 @@
1
- """Session types for MCP programmatic OAuth."""
2
-
3
- from __future__ import annotations
4
-
5
- from dataclasses import dataclass, field
6
-
7
-
8
- @dataclass(frozen=True)
9
- class SessionMcp:
10
- """MCP streamable-HTTP connection details for your framework."""
11
-
12
- url: str
13
- headers: dict[str, str] = field(default_factory=dict)
File without changes
File without changes
File without changes