cortexhub 2.1.0__tar.gz → 3.1.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.
- cortexhub-3.1.0/PKG-INFO +280 -0
- cortexhub-3.1.0/README.md +251 -0
- {cortexhub-2.1.0 → cortexhub-3.1.0}/pyproject.toml +18 -3
- {cortexhub-2.1.0 → cortexhub-3.1.0}/src/cortexhub/__init__.py +5 -3
- cortexhub-3.1.0/src/cortexhub/_config.py +22 -0
- cortexhub-3.1.0/src/cortexhub/ai.py +63 -0
- {cortexhub-2.1.0 → cortexhub-3.1.0}/src/cortexhub/client.py +92 -9
- {cortexhub-2.1.0 → cortexhub-3.1.0}/src/cortexhub/mcp_key.py +53 -7
- cortexhub-2.1.0/PKG-INFO +0 -104
- cortexhub-2.1.0/README.md +0 -82
- cortexhub-2.1.0/src/cortexhub/_config.py +0 -11
- {cortexhub-2.1.0 → cortexhub-3.1.0}/.gitignore +0 -0
- {cortexhub-2.1.0 → cortexhub-3.1.0}/LICENSE +0 -0
- {cortexhub-2.1.0 → cortexhub-3.1.0}/src/cortexhub/errors.py +0 -0
- {cortexhub-2.1.0 → cortexhub-3.1.0}/src/cortexhub/mcp_oauth.py +0 -0
- {cortexhub-2.1.0 → cortexhub-3.1.0}/src/cortexhub/session.py +0 -0
cortexhub-3.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cortexhub
|
|
3
|
+
Version: 3.1.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
|
+
## Run a session (recommended)
|
|
65
|
+
|
|
66
|
+
Your agent runs in your own runtime, but every run should show up in CortexHub
|
|
67
|
+
with the same visibility as a co-worker on CortexHub's runtime -- one **Session**
|
|
68
|
+
in the Sessions tab, with its Trace, Spans, cost, and user attribution.
|
|
69
|
+
|
|
70
|
+
Use one `cx.session(...)` handle for the whole run. Pass the identity only your
|
|
71
|
+
app knows: a stable **session id** (your id for the conversation or autonomous
|
|
72
|
+
run) and the **end user** it acts for. The handle's `.llm` (inference) and `.mcp`
|
|
73
|
+
(tools) both land in that one session.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
s = cx.session(
|
|
77
|
+
agent="support-bot",
|
|
78
|
+
mcp_session_id="conv-42", # your stable id -> one CortexHub session
|
|
79
|
+
end_user_subject="user_42", # who it acts for (None for an autonomous run)
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# Inference (OpenAI-compatible). model="cortexhub/auto" lets CortexHub route per
|
|
83
|
+
# turn; or pass any model enabled on the platform.
|
|
84
|
+
s.llm.chat.completions.create(model="cortexhub/auto", messages=[{"role": "user", "content": "hi"}])
|
|
85
|
+
|
|
86
|
+
# Tools + brain + files, in the SAME session:
|
|
87
|
+
s.mcp.url # https://mcp.cortexhub.ai/v1/mcp
|
|
88
|
+
s.mcp.headers # wire into your MCP transport (see "Tools" below)
|
|
89
|
+
|
|
90
|
+
s.session_id # "conv-42" -- log or forward it to correlate
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Reuse the same handle across the run's turns so they group. An autonomous agent
|
|
94
|
+
(e.g. a cron job) does the same with a per-run id and no `end_user_subject`
|
|
95
|
+
(extra for `.llm`: `cortexhub[ai]`).
|
|
96
|
+
|
|
97
|
+
## Inference without a session
|
|
98
|
+
|
|
99
|
+
For a quick, standalone call, `cx.llm` is a ready OpenAI-compatible client and
|
|
100
|
+
`cx.ai` gives the raw `base_url` + `api_key` any framework needs. These are NOT
|
|
101
|
+
grouped into a session (no Sessions row) -- prefer `cx.session(...)` above when
|
|
102
|
+
you want the run visible in CortexHub.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
cx.llm.chat.completions.create(model="cortexhub/auto", messages=[...])
|
|
106
|
+
cx.llm.responses.create(model="cortexhub/auto", input="hi")
|
|
107
|
+
cx.llm.models.list()
|
|
108
|
+
|
|
109
|
+
cx.ai.base_url # e.g. https://api.cortexhub.ai/v1 (override with CORTEXHUB_ROUTER_URL)
|
|
110
|
+
cx.ai.api_key # your cxh_key_...
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Use your existing framework
|
|
114
|
+
|
|
115
|
+
The router speaks the OpenAI wire protocol, so every framework integrates the
|
|
116
|
+
same way: point its OpenAI-compatible provider at `cx.ai.base_url`, pass
|
|
117
|
+
`cx.ai.api_key`, and choose a `model`.
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
base, key = cx.ai.base_url, cx.ai.api_key
|
|
121
|
+
|
|
122
|
+
# OpenAI SDK / plain
|
|
123
|
+
from openai import OpenAI
|
|
124
|
+
OpenAI(base_url=base, api_key=key).chat.completions.create(model="cortexhub/auto", messages=[...])
|
|
125
|
+
|
|
126
|
+
# LangChain / LangGraph
|
|
127
|
+
from langchain_openai import ChatOpenAI
|
|
128
|
+
ChatOpenAI(base_url=base, api_key=key, model="cortexhub/auto")
|
|
129
|
+
|
|
130
|
+
# CrewAI (LiteLLM under the hood)
|
|
131
|
+
from crewai import LLM
|
|
132
|
+
LLM(model="openai/cortexhub/auto", base_url=base, api_key=key)
|
|
133
|
+
|
|
134
|
+
# AutoGen
|
|
135
|
+
from autogen_ext.models.openai import OpenAIChatCompletionClient
|
|
136
|
+
OpenAIChatCompletionClient(model="cortexhub/auto", base_url=base, api_key=key)
|
|
137
|
+
|
|
138
|
+
# Pydantic AI
|
|
139
|
+
from pydantic_ai.models.openai import OpenAIModel
|
|
140
|
+
from pydantic_ai.providers.openai import OpenAIProvider
|
|
141
|
+
OpenAIModel("cortexhub/auto", provider=OpenAIProvider(base_url=base, api_key=key))
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
**Anthropic SDK:** the router is OpenAI-compatible, not Anthropic-Messages, so
|
|
145
|
+
point the *OpenAI* client at CortexHub with a `claude-*` model (we route to
|
|
146
|
+
Claude) rather than the Anthropic SDK.
|
|
147
|
+
|
|
148
|
+
## Tools, brain, and files (MCP gateway)
|
|
149
|
+
|
|
150
|
+
`s.mcp` (the session handle above) is the MCP connection your agent's loop
|
|
151
|
+
drives. Any MCP-capable framework registers it as a server; the `cortexhub_*`
|
|
152
|
+
tools (governed toolkit calls, brain recall/learn, files search) then appear
|
|
153
|
+
automatically -- and, on the session handle, group with that run's LLM turns.
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
conn = s.mcp # from cx.session(...) -> same session as .llm
|
|
157
|
+
conn.url # https://mcp.cortexhub.ai/v1/mcp
|
|
158
|
+
conn.headers # wire into your MCP transport
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
`cx.mcp(agent=..., end_user_subject=...)` is the standalone form when you only
|
|
162
|
+
need tools (no session grouping).
|
|
163
|
+
|
|
164
|
+
## A full turn: reason, act, and approvals
|
|
165
|
+
|
|
166
|
+
One session, end to end: the model reasons with `s.llm`, acts through the
|
|
167
|
+
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).
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
import asyncio, json
|
|
183
|
+
from cortexhub import Cortexhub
|
|
184
|
+
from mcp import ClientSession
|
|
185
|
+
from mcp.client.streamable_http import streamablehttp_client
|
|
186
|
+
|
|
187
|
+
cx = Cortexhub(api_key="cxh_key_...")
|
|
188
|
+
|
|
189
|
+
async def run_turn(user_text: str) -> str:
|
|
190
|
+
# One session for this end user's conversation -> LLM + tools share it.
|
|
191
|
+
s = cx.session(agent="support-bot", mcp_session_id="conv-42", end_user_subject="user_42")
|
|
192
|
+
|
|
193
|
+
async with streamablehttp_client(s.mcp.url, headers=s.mcp.headers) as (read, write, _):
|
|
194
|
+
async with ClientSession(read, write) as mcp:
|
|
195
|
+
await mcp.initialize()
|
|
196
|
+
|
|
197
|
+
# Offer the governed cortexhub_* tools to the model.
|
|
198
|
+
listed = await mcp.list_tools()
|
|
199
|
+
tools = [{
|
|
200
|
+
"type": "function",
|
|
201
|
+
"function": {"name": t.name, "description": t.description or "",
|
|
202
|
+
"parameters": t.inputSchema or {"type": "object", "properties": {}}},
|
|
203
|
+
} for t in listed.tools]
|
|
204
|
+
|
|
205
|
+
messages = [{"role": "user", "content": user_text}]
|
|
206
|
+
for _ in range(8): # a few reason -> act rounds
|
|
207
|
+
msg = s.llm.chat.completions.create(
|
|
208
|
+
model="cortexhub/auto", messages=messages, tools=tools,
|
|
209
|
+
).choices[0].message
|
|
210
|
+
if not msg.tool_calls:
|
|
211
|
+
return msg.content or "" # final answer
|
|
212
|
+
|
|
213
|
+
messages.append(msg.model_dump())
|
|
214
|
+
for call in msg.tool_calls:
|
|
215
|
+
args = json.loads(call.function.arguments or "{}")
|
|
216
|
+
result = await mcp.call_tool(call.function.name, args)
|
|
217
|
+
text = _text(result)
|
|
218
|
+
|
|
219
|
+
task = _parked_task(result) # governed action -> needs approval?
|
|
220
|
+
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
|
|
223
|
+
|
|
224
|
+
messages.append({"role": "tool", "tool_call_id": call.id, "content": text})
|
|
225
|
+
return ""
|
|
226
|
+
|
|
227
|
+
# --- small helpers over the MCP result ---
|
|
228
|
+
def _text(result) -> str:
|
|
229
|
+
return "\n".join(b.text for b in result.content if getattr(b, "text", None)) or "{}"
|
|
230
|
+
|
|
231
|
+
def _payload(result):
|
|
232
|
+
sc = getattr(result, "structuredContent", None)
|
|
233
|
+
if sc:
|
|
234
|
+
return sc
|
|
235
|
+
try:
|
|
236
|
+
return json.loads(_text(result))
|
|
237
|
+
except json.JSONDecodeError:
|
|
238
|
+
return {}
|
|
239
|
+
|
|
240
|
+
def _parked_task(result):
|
|
241
|
+
# A parked approval comes back as an `mcp_task` carrying a signed consent_url.
|
|
242
|
+
def walk(node):
|
|
243
|
+
if isinstance(node, dict):
|
|
244
|
+
t = node.get("mcp_task")
|
|
245
|
+
if isinstance(t, dict) and t.get("consent_url"):
|
|
246
|
+
return t
|
|
247
|
+
for v in node.values():
|
|
248
|
+
if (found := walk(v)):
|
|
249
|
+
return found
|
|
250
|
+
elif isinstance(node, list):
|
|
251
|
+
for item in node:
|
|
252
|
+
if (found := walk(item)):
|
|
253
|
+
return found
|
|
254
|
+
return None
|
|
255
|
+
return walk(_payload(result))
|
|
256
|
+
|
|
257
|
+
async def _await_decision(mcp, task_id: str) -> str:
|
|
258
|
+
# Poll until the human decides in CortexHub; an approval runs the action.
|
|
259
|
+
for _ in range(600): # ~10 min at 1s waits
|
|
260
|
+
res = await mcp.call_tool("cortexhub_get_task", {"task_id": task_id, "wait_ms": 1000})
|
|
261
|
+
if _payload(res).get("terminal"):
|
|
262
|
+
return _text(res)
|
|
263
|
+
return "approval timed out"
|
|
264
|
+
|
|
265
|
+
print(asyncio.run(run_turn("Email the Q3 report to the finance team")))
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
The whole turn is one CortexHub session (`conv-42`): open its Sessions tab to see
|
|
269
|
+
the model step, each tool call, and the approval as a single trace.
|
|
270
|
+
|
|
271
|
+
## Authentication modes
|
|
272
|
+
|
|
273
|
+
- **API key** (`api_key=cxh_key_...`, or `CORTEXHUB_API_KEY`) - backends whose
|
|
274
|
+
end users do not have CortexHub accounts. Attest the end user per call with
|
|
275
|
+
`end_user_subject`. Required for `cx.ai` / `cx.llm`.
|
|
276
|
+
- **MCP OAuth client** (`client_id=` / `client_secret=`) - for interactive
|
|
277
|
+
CortexHub users, MCP gateway only.
|
|
278
|
+
|
|
279
|
+
The MCP gateway also accepts MCP OAuth from third-party clients (Claude, Cursor)
|
|
280
|
+
independently of this SDK.
|
|
@@ -0,0 +1,251 @@
|
|
|
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
|
+
## Run a session (recommended)
|
|
36
|
+
|
|
37
|
+
Your agent runs in your own runtime, but every run should show up in CortexHub
|
|
38
|
+
with the same visibility as a co-worker on CortexHub's runtime -- one **Session**
|
|
39
|
+
in the Sessions tab, with its Trace, Spans, cost, and user attribution.
|
|
40
|
+
|
|
41
|
+
Use one `cx.session(...)` handle for the whole run. Pass the identity only your
|
|
42
|
+
app knows: a stable **session id** (your id for the conversation or autonomous
|
|
43
|
+
run) and the **end user** it acts for. The handle's `.llm` (inference) and `.mcp`
|
|
44
|
+
(tools) both land in that one session.
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
s = cx.session(
|
|
48
|
+
agent="support-bot",
|
|
49
|
+
mcp_session_id="conv-42", # your stable id -> one CortexHub session
|
|
50
|
+
end_user_subject="user_42", # who it acts for (None for an autonomous run)
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
# Inference (OpenAI-compatible). model="cortexhub/auto" lets CortexHub route per
|
|
54
|
+
# turn; or pass any model enabled on the platform.
|
|
55
|
+
s.llm.chat.completions.create(model="cortexhub/auto", messages=[{"role": "user", "content": "hi"}])
|
|
56
|
+
|
|
57
|
+
# Tools + brain + files, in the SAME session:
|
|
58
|
+
s.mcp.url # https://mcp.cortexhub.ai/v1/mcp
|
|
59
|
+
s.mcp.headers # wire into your MCP transport (see "Tools" below)
|
|
60
|
+
|
|
61
|
+
s.session_id # "conv-42" -- log or forward it to correlate
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Reuse the same handle across the run's turns so they group. An autonomous agent
|
|
65
|
+
(e.g. a cron job) does the same with a per-run id and no `end_user_subject`
|
|
66
|
+
(extra for `.llm`: `cortexhub[ai]`).
|
|
67
|
+
|
|
68
|
+
## Inference without a session
|
|
69
|
+
|
|
70
|
+
For a quick, standalone call, `cx.llm` is a ready OpenAI-compatible client and
|
|
71
|
+
`cx.ai` gives the raw `base_url` + `api_key` any framework needs. These are NOT
|
|
72
|
+
grouped into a session (no Sessions row) -- prefer `cx.session(...)` above when
|
|
73
|
+
you want the run visible in CortexHub.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
cx.llm.chat.completions.create(model="cortexhub/auto", messages=[...])
|
|
77
|
+
cx.llm.responses.create(model="cortexhub/auto", input="hi")
|
|
78
|
+
cx.llm.models.list()
|
|
79
|
+
|
|
80
|
+
cx.ai.base_url # e.g. https://api.cortexhub.ai/v1 (override with CORTEXHUB_ROUTER_URL)
|
|
81
|
+
cx.ai.api_key # your cxh_key_...
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Use your existing framework
|
|
85
|
+
|
|
86
|
+
The router speaks the OpenAI wire protocol, so every framework integrates the
|
|
87
|
+
same way: point its OpenAI-compatible provider at `cx.ai.base_url`, pass
|
|
88
|
+
`cx.ai.api_key`, and choose a `model`.
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
base, key = cx.ai.base_url, cx.ai.api_key
|
|
92
|
+
|
|
93
|
+
# OpenAI SDK / plain
|
|
94
|
+
from openai import OpenAI
|
|
95
|
+
OpenAI(base_url=base, api_key=key).chat.completions.create(model="cortexhub/auto", messages=[...])
|
|
96
|
+
|
|
97
|
+
# LangChain / LangGraph
|
|
98
|
+
from langchain_openai import ChatOpenAI
|
|
99
|
+
ChatOpenAI(base_url=base, api_key=key, model="cortexhub/auto")
|
|
100
|
+
|
|
101
|
+
# CrewAI (LiteLLM under the hood)
|
|
102
|
+
from crewai import LLM
|
|
103
|
+
LLM(model="openai/cortexhub/auto", base_url=base, api_key=key)
|
|
104
|
+
|
|
105
|
+
# AutoGen
|
|
106
|
+
from autogen_ext.models.openai import OpenAIChatCompletionClient
|
|
107
|
+
OpenAIChatCompletionClient(model="cortexhub/auto", base_url=base, api_key=key)
|
|
108
|
+
|
|
109
|
+
# Pydantic AI
|
|
110
|
+
from pydantic_ai.models.openai import OpenAIModel
|
|
111
|
+
from pydantic_ai.providers.openai import OpenAIProvider
|
|
112
|
+
OpenAIModel("cortexhub/auto", provider=OpenAIProvider(base_url=base, api_key=key))
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
**Anthropic SDK:** the router is OpenAI-compatible, not Anthropic-Messages, so
|
|
116
|
+
point the *OpenAI* client at CortexHub with a `claude-*` model (we route to
|
|
117
|
+
Claude) rather than the Anthropic SDK.
|
|
118
|
+
|
|
119
|
+
## Tools, brain, and files (MCP gateway)
|
|
120
|
+
|
|
121
|
+
`s.mcp` (the session handle above) is the MCP connection your agent's loop
|
|
122
|
+
drives. Any MCP-capable framework registers it as a server; the `cortexhub_*`
|
|
123
|
+
tools (governed toolkit calls, brain recall/learn, files search) then appear
|
|
124
|
+
automatically -- and, on the session handle, group with that run's LLM turns.
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
conn = s.mcp # from cx.session(...) -> same session as .llm
|
|
128
|
+
conn.url # https://mcp.cortexhub.ai/v1/mcp
|
|
129
|
+
conn.headers # wire into your MCP transport
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`cx.mcp(agent=..., end_user_subject=...)` is the standalone form when you only
|
|
133
|
+
need tools (no session grouping).
|
|
134
|
+
|
|
135
|
+
## A full turn: reason, act, and approvals
|
|
136
|
+
|
|
137
|
+
One session, end to end: the model reasons with `s.llm`, acts through the
|
|
138
|
+
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).
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
import asyncio, json
|
|
154
|
+
from cortexhub import Cortexhub
|
|
155
|
+
from mcp import ClientSession
|
|
156
|
+
from mcp.client.streamable_http import streamablehttp_client
|
|
157
|
+
|
|
158
|
+
cx = Cortexhub(api_key="cxh_key_...")
|
|
159
|
+
|
|
160
|
+
async def run_turn(user_text: str) -> str:
|
|
161
|
+
# One session for this end user's conversation -> LLM + tools share it.
|
|
162
|
+
s = cx.session(agent="support-bot", mcp_session_id="conv-42", end_user_subject="user_42")
|
|
163
|
+
|
|
164
|
+
async with streamablehttp_client(s.mcp.url, headers=s.mcp.headers) as (read, write, _):
|
|
165
|
+
async with ClientSession(read, write) as mcp:
|
|
166
|
+
await mcp.initialize()
|
|
167
|
+
|
|
168
|
+
# Offer the governed cortexhub_* tools to the model.
|
|
169
|
+
listed = await mcp.list_tools()
|
|
170
|
+
tools = [{
|
|
171
|
+
"type": "function",
|
|
172
|
+
"function": {"name": t.name, "description": t.description or "",
|
|
173
|
+
"parameters": t.inputSchema or {"type": "object", "properties": {}}},
|
|
174
|
+
} for t in listed.tools]
|
|
175
|
+
|
|
176
|
+
messages = [{"role": "user", "content": user_text}]
|
|
177
|
+
for _ in range(8): # a few reason -> act rounds
|
|
178
|
+
msg = s.llm.chat.completions.create(
|
|
179
|
+
model="cortexhub/auto", messages=messages, tools=tools,
|
|
180
|
+
).choices[0].message
|
|
181
|
+
if not msg.tool_calls:
|
|
182
|
+
return msg.content or "" # final answer
|
|
183
|
+
|
|
184
|
+
messages.append(msg.model_dump())
|
|
185
|
+
for call in msg.tool_calls:
|
|
186
|
+
args = json.loads(call.function.arguments or "{}")
|
|
187
|
+
result = await mcp.call_tool(call.function.name, args)
|
|
188
|
+
text = _text(result)
|
|
189
|
+
|
|
190
|
+
task = _parked_task(result) # governed action -> needs approval?
|
|
191
|
+
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
|
|
194
|
+
|
|
195
|
+
messages.append({"role": "tool", "tool_call_id": call.id, "content": text})
|
|
196
|
+
return ""
|
|
197
|
+
|
|
198
|
+
# --- small helpers over the MCP result ---
|
|
199
|
+
def _text(result) -> str:
|
|
200
|
+
return "\n".join(b.text for b in result.content if getattr(b, "text", None)) or "{}"
|
|
201
|
+
|
|
202
|
+
def _payload(result):
|
|
203
|
+
sc = getattr(result, "structuredContent", None)
|
|
204
|
+
if sc:
|
|
205
|
+
return sc
|
|
206
|
+
try:
|
|
207
|
+
return json.loads(_text(result))
|
|
208
|
+
except json.JSONDecodeError:
|
|
209
|
+
return {}
|
|
210
|
+
|
|
211
|
+
def _parked_task(result):
|
|
212
|
+
# A parked approval comes back as an `mcp_task` carrying a signed consent_url.
|
|
213
|
+
def walk(node):
|
|
214
|
+
if isinstance(node, dict):
|
|
215
|
+
t = node.get("mcp_task")
|
|
216
|
+
if isinstance(t, dict) and t.get("consent_url"):
|
|
217
|
+
return t
|
|
218
|
+
for v in node.values():
|
|
219
|
+
if (found := walk(v)):
|
|
220
|
+
return found
|
|
221
|
+
elif isinstance(node, list):
|
|
222
|
+
for item in node:
|
|
223
|
+
if (found := walk(item)):
|
|
224
|
+
return found
|
|
225
|
+
return None
|
|
226
|
+
return walk(_payload(result))
|
|
227
|
+
|
|
228
|
+
async def _await_decision(mcp, task_id: str) -> str:
|
|
229
|
+
# Poll until the human decides in CortexHub; an approval runs the action.
|
|
230
|
+
for _ in range(600): # ~10 min at 1s waits
|
|
231
|
+
res = await mcp.call_tool("cortexhub_get_task", {"task_id": task_id, "wait_ms": 1000})
|
|
232
|
+
if _payload(res).get("terminal"):
|
|
233
|
+
return _text(res)
|
|
234
|
+
return "approval timed out"
|
|
235
|
+
|
|
236
|
+
print(asyncio.run(run_turn("Email the Q3 report to the finance team")))
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
The whole turn is one CortexHub session (`conv-42`): open its Sessions tab to see
|
|
240
|
+
the model step, each tool call, and the approval as a single trace.
|
|
241
|
+
|
|
242
|
+
## Authentication modes
|
|
243
|
+
|
|
244
|
+
- **API key** (`api_key=cxh_key_...`, or `CORTEXHUB_API_KEY`) - backends whose
|
|
245
|
+
end users do not have CortexHub accounts. Attest the end user per call with
|
|
246
|
+
`end_user_subject`. Required for `cx.ai` / `cx.llm`.
|
|
247
|
+
- **MCP OAuth client** (`client_id=` / `client_secret=`) - for interactive
|
|
248
|
+
CortexHub users, MCP gateway only.
|
|
249
|
+
|
|
250
|
+
The MCP gateway also accepts MCP OAuth from third-party clients (Claude, Cursor)
|
|
251
|
+
independently of this SDK.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "cortexhub"
|
|
3
|
-
version = "
|
|
4
|
-
description = "
|
|
3
|
+
version = "3.1.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,7 +73,13 @@ ignore = ["E501"]
|
|
|
64
73
|
python_version = "3.10"
|
|
65
74
|
strict = true
|
|
66
75
|
warn_return_any = true
|
|
67
|
-
|
|
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"
|
|
@@ -9,9 +9,9 @@ Two gateway authentication paths through one entry point:
|
|
|
9
9
|
|
|
10
10
|
.. code-block:: python
|
|
11
11
|
|
|
12
|
-
# Org
|
|
12
|
+
# Org API key (recommended for backends):
|
|
13
13
|
from cortexhub import Cortexhub
|
|
14
|
-
cx = Cortexhub(api_key="
|
|
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,15 +24,17 @@ 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__ = "
|
|
34
|
+
__version__ = "3.1.0"
|
|
34
35
|
__all__ = [
|
|
35
36
|
"APIError",
|
|
37
|
+
"AiGateway",
|
|
36
38
|
"AuthenticationError",
|
|
37
39
|
"ConfigurationError",
|
|
38
40
|
"Cortexhub",
|
|
@@ -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
|
-
* **Org
|
|
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="
|
|
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
|
-
"""
|
|
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`` -- org
|
|
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= (org
|
|
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."
|
|
@@ -101,9 +112,21 @@ class Cortexhub:
|
|
|
101
112
|
last_user_message: str | None = None,
|
|
102
113
|
refresh: bool = False,
|
|
103
114
|
) -> McpKeySession | McpOAuthSession:
|
|
104
|
-
"""Return
|
|
115
|
+
"""Return a session handle for ONE conversation or autonomous run.
|
|
116
|
+
|
|
117
|
+
The handle carries both planes so everything the run does lands in ONE
|
|
118
|
+
CortexHub session (Session -> Trace -> Span, with cost + user attribution,
|
|
119
|
+
exactly like a co-worker):
|
|
120
|
+
|
|
121
|
+
- ``.mcp`` -- ``.url`` + ``.headers`` for your MCP transport (tools).
|
|
122
|
+
- ``.llm`` -- a ready OpenAI-compatible client scoped to this session
|
|
123
|
+
(key mode; extra ``ai``). Its turns group under the same session.
|
|
124
|
+
- ``.session_id`` -- the id the run groups under (the ``mcp_session_id``).
|
|
105
125
|
|
|
106
|
-
``
|
|
126
|
+
Pass ``mcp_session_id`` = your stable id for the conversation/run and
|
|
127
|
+
``end_user_subject`` = the end user it acts for (``None`` for an
|
|
128
|
+
autonomous run); reuse the same handle across the run's turns so they
|
|
129
|
+
group. ``agent`` is required on every call.
|
|
107
130
|
|
|
108
131
|
**Org API key mode**: pass ``end_user_subject`` to attest
|
|
109
132
|
the end user the call is acting on behalf of. The gateway
|
|
@@ -152,6 +175,66 @@ class Cortexhub:
|
|
|
152
175
|
"""OAuth token URL when in OAuth mode. Empty string in key mode."""
|
|
153
176
|
return self._oauth_backend.token_url if self._oauth_backend else ""
|
|
154
177
|
|
|
178
|
+
@property
|
|
179
|
+
def ai(self) -> AiGateway:
|
|
180
|
+
"""LLM router config (``base_url`` + ``api_key``). Key mode only.
|
|
181
|
+
|
|
182
|
+
Point any OpenAI-compatible framework at ``cx.ai.base_url`` with
|
|
183
|
+
``cx.ai.api_key``; pass a ``model`` (``cortexhub/auto`` or a specific
|
|
184
|
+
enabled model). The key is bound to one agent, so no agent argument.
|
|
185
|
+
"""
|
|
186
|
+
if self._key_backend is None:
|
|
187
|
+
raise ConfigurationError(
|
|
188
|
+
"cx.ai / cx.llm require an org API key (api_key=cxh_key_...). "
|
|
189
|
+
"The LLM router authenticates with the API key as a Bearer "
|
|
190
|
+
"token; OAuth client credentials are for the MCP gateway."
|
|
191
|
+
)
|
|
192
|
+
return build_ai_gateway(self._key_backend.api_key)
|
|
193
|
+
|
|
194
|
+
@property
|
|
195
|
+
def llm(self) -> Any:
|
|
196
|
+
"""A ready OpenAI-compatible client at the router (extra: ``cortexhub[ai]``).
|
|
197
|
+
|
|
198
|
+
.. code-block:: python
|
|
199
|
+
|
|
200
|
+
cx.llm.chat.completions.create(model="cortexhub/auto", messages=[...])
|
|
201
|
+
cx.llm.responses.create(model="cortexhub/auto", input="...")
|
|
202
|
+
|
|
203
|
+
Cached per client. Requires the ``openai`` package.
|
|
204
|
+
"""
|
|
205
|
+
cached = getattr(self, "_llm_client", None)
|
|
206
|
+
if cached is None:
|
|
207
|
+
cached = self.ai.client()
|
|
208
|
+
self._llm_client = cached
|
|
209
|
+
return cached
|
|
210
|
+
|
|
211
|
+
def mcp(
|
|
212
|
+
self,
|
|
213
|
+
*,
|
|
214
|
+
agent: str,
|
|
215
|
+
mcp_session_id: str | None = None,
|
|
216
|
+
end_user_subject: str | None = None,
|
|
217
|
+
end_user_display_hint: str | None = None,
|
|
218
|
+
conversation_title: str | None = None,
|
|
219
|
+
last_user_message: str | None = None,
|
|
220
|
+
refresh: bool = False,
|
|
221
|
+
) -> SessionMcp:
|
|
222
|
+
"""MCP gateway connection (``.url`` + ``.headers``) for your agent.
|
|
223
|
+
|
|
224
|
+
A shortcut for ``cx.session(...).mcp``. Wire ``.url`` and ``.headers``
|
|
225
|
+
into your MCP transport; tools, brain, and files appear as governed
|
|
226
|
+
tools. Works in both key and OAuth mode.
|
|
227
|
+
"""
|
|
228
|
+
return self.session(
|
|
229
|
+
agent=agent,
|
|
230
|
+
mcp_session_id=mcp_session_id,
|
|
231
|
+
end_user_subject=end_user_subject,
|
|
232
|
+
end_user_display_hint=end_user_display_hint,
|
|
233
|
+
conversation_title=conversation_title,
|
|
234
|
+
last_user_message=last_user_message,
|
|
235
|
+
refresh=refresh,
|
|
236
|
+
).mcp
|
|
237
|
+
|
|
155
238
|
def fetch_token(self, *, refresh: bool = False) -> McpOAuthToken:
|
|
156
239
|
"""OAuth-mode only. Mint or refresh an access token directly.
|
|
157
240
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"""Org
|
|
1
|
+
"""Org API key client.
|
|
2
2
|
|
|
3
3
|
Use this when your backend acts on behalf of users who do not have
|
|
4
|
-
CortexHub identities. The org
|
|
4
|
+
CortexHub identities. The org API key authenticates the
|
|
5
5
|
gateway; the end-user identity is attested per call via
|
|
6
6
|
``X-CortexHub-End-User-Subject``. No CortexHub user row is created
|
|
7
7
|
for the end user, no email is required, no PII is stored.
|
|
@@ -13,6 +13,7 @@ For applications that sign in CortexHub users interactively, see
|
|
|
13
13
|
from __future__ import annotations
|
|
14
14
|
|
|
15
15
|
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any
|
|
16
17
|
|
|
17
18
|
from ._config import base_url
|
|
18
19
|
from .session import SessionMcp
|
|
@@ -22,7 +23,14 @@ _AGENT_HEADER = "X-CortexHub-Agent"
|
|
|
22
23
|
_END_USER_SUBJECT_HEADER = "X-CortexHub-End-User-Subject"
|
|
23
24
|
_END_USER_DISPLAY_HINT_HEADER = "X-CortexHub-End-User-Display-Hint"
|
|
24
25
|
|
|
25
|
-
|
|
26
|
+
# The LLM router groups a turn into a CortexHub session by these headers -- the
|
|
27
|
+
# same session the MCP tool calls (Mcp-Session-Id) land in -- so one handle's
|
|
28
|
+
# ``.llm`` and ``.mcp`` share one Session -> Trace -> Span with cost + user
|
|
29
|
+
# attribution. The router names them without the ``-Subject`` suffix.
|
|
30
|
+
_ROUTER_SESSION_HEADER = "X-CortexHub-Session-Id"
|
|
31
|
+
_ROUTER_END_USER_HEADER = "X-CortexHub-End-User"
|
|
32
|
+
|
|
33
|
+
_KEY_PREFIX = "cxh_key_"
|
|
26
34
|
|
|
27
35
|
|
|
28
36
|
@dataclass
|
|
@@ -53,9 +61,47 @@ class McpKeySession:
|
|
|
53
61
|
headers[_END_USER_DISPLAY_HINT_HEADER] = self.end_user_display_hint
|
|
54
62
|
self.mcp = SessionMcp(url=f"{base_url()}/v1/mcp", headers=headers)
|
|
55
63
|
|
|
64
|
+
@property
|
|
65
|
+
def session_id(self) -> str | None:
|
|
66
|
+
"""The CortexHub session this handle's turns group under.
|
|
67
|
+
|
|
68
|
+
It is the ``mcp_session_id`` you passed - your stable id for the
|
|
69
|
+
conversation OR autonomous run. Log or forward it to correlate; every
|
|
70
|
+
``.llm`` and ``.mcp`` call on this handle lands in this one session.
|
|
71
|
+
"""
|
|
72
|
+
return self.mcp_session_id
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def llm(self) -> Any:
|
|
76
|
+
"""A ready OpenAI-compatible client scoped to THIS session (extra: ``ai``).
|
|
77
|
+
|
|
78
|
+
Every call carries the session id + end user, so the LLM turns land in
|
|
79
|
+
the SAME CortexHub session as this handle's tool calls -- one Session ->
|
|
80
|
+
Trace -> Span, with cost and user attribution, exactly like a co-worker
|
|
81
|
+
on CortexHub's own runtime.
|
|
82
|
+
|
|
83
|
+
.. code-block:: python
|
|
84
|
+
|
|
85
|
+
s = cx.session(agent="support-bot",
|
|
86
|
+
mcp_session_id="conv-42", # your conversation id
|
|
87
|
+
end_user_subject="user_42") # who it acts for
|
|
88
|
+
s.llm.chat.completions.create(model="cortexhub/auto", messages=[...])
|
|
89
|
+
# ...and s.mcp for tools -- both in session "conv-42".
|
|
90
|
+
|
|
91
|
+
Requires the ``openai`` package (``pip install 'cortexhub[ai]'``).
|
|
92
|
+
"""
|
|
93
|
+
from .ai import build_ai_gateway
|
|
94
|
+
|
|
95
|
+
headers: dict[str, str] = {}
|
|
96
|
+
if self.mcp_session_id:
|
|
97
|
+
headers[_ROUTER_SESSION_HEADER] = self.mcp_session_id
|
|
98
|
+
if self.end_user_subject:
|
|
99
|
+
headers[_ROUTER_END_USER_HEADER] = self.end_user_subject
|
|
100
|
+
return build_ai_gateway(self.api_key).client(default_headers=headers)
|
|
101
|
+
|
|
56
102
|
|
|
57
103
|
class CortexhubKeyClient:
|
|
58
|
-
"""Send MCP gateway calls authenticated by an org
|
|
104
|
+
"""Send MCP gateway calls authenticated by an org API key."""
|
|
59
105
|
|
|
60
106
|
def __init__(self, *, api_key: str) -> None:
|
|
61
107
|
cleaned = (api_key or "").strip()
|
|
@@ -63,9 +109,9 @@ class CortexhubKeyClient:
|
|
|
63
109
|
raise ValueError("api_key= is required.")
|
|
64
110
|
if not cleaned.startswith(_KEY_PREFIX):
|
|
65
111
|
raise ValueError(
|
|
66
|
-
f"api_key must start with {_KEY_PREFIX!r}. Org
|
|
67
|
-
"
|
|
68
|
-
"
|
|
112
|
+
f"api_key must start with {_KEY_PREFIX!r}. Org API keys begin "
|
|
113
|
+
"with this prefix; if you have an OAuth client_id and "
|
|
114
|
+
"client_secret instead, use the OAuth credentials path."
|
|
69
115
|
)
|
|
70
116
|
self.api_key = cleaned
|
|
71
117
|
|
cortexhub-2.1.0/PKG-INFO
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: cortexhub
|
|
3
|
-
Version: 2.1.0
|
|
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, agent, and member 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
|
-
### Org 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 org key authenticates the gateway; the
|
|
49
|
-
end-user identity is attested per call.
|
|
50
|
-
|
|
51
|
-
Mint the key from **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
|
-
)
|
|
63
|
-
# session.mcp.url and session.mcp.headers -> pass to your MCP transport
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
### MCP OAuth client
|
|
67
|
-
|
|
68
|
-
Use this when your application signs in CortexHub users interactively.
|
|
69
|
-
Create the OAuth client from **Account settings -> MCP OAuth clients** and
|
|
70
|
-
copy the `client_id` and `client_secret`.
|
|
71
|
-
|
|
72
|
-
```python
|
|
73
|
-
from cortexhub import Cortexhub
|
|
74
|
-
|
|
75
|
-
cx = Cortexhub(client_id="...", client_secret="...")
|
|
76
|
-
session = cx.session(
|
|
77
|
-
agent="helpdesk-bot",
|
|
78
|
-
mcp_session_id="chat-42", # optional: groups activity per session
|
|
79
|
-
conversation_title="Engineering standup", # optional: context shown in audit
|
|
80
|
-
last_user_message="Create a standup page", # optional: context shown in audit
|
|
81
|
-
)
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
## Environment variables
|
|
85
|
-
|
|
86
|
-
| Variable | Default | Purpose |
|
|
87
|
-
|---|---|---|
|
|
88
|
-
| `CORTEXHUB_URL` | `https://mcp.cortexhub.ai` | MCP gateway base URL |
|
|
89
|
-
| `CORTEXHUB_API_KEY` | - | Org MCP API key (`cxh_mcpk_*`) |
|
|
90
|
-
| `CORTEXHUB_CLIENT_ID` | - | MCP OAuth client id |
|
|
91
|
-
| `CORTEXHUB_CLIENT_SECRET` | - | MCP OAuth client secret |
|
|
92
|
-
|
|
93
|
-
If both `CORTEXHUB_API_KEY` and OAuth credentials are configured, the
|
|
94
|
-
API key wins.
|
|
95
|
-
|
|
96
|
-
## What the SDK returns
|
|
97
|
-
|
|
98
|
-
In both modes, `session.mcp.url` and `session.mcp.headers` are ready to
|
|
99
|
-
wire into the MCP transport of your choice (the official MCP Python SDK,
|
|
100
|
-
a custom HTTP client, anything that accepts URL + headers).
|
|
101
|
-
|
|
102
|
-
## License
|
|
103
|
-
|
|
104
|
-
MIT.
|
cortexhub-2.1.0/README.md
DELETED
|
@@ -1,82 +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, agent, and member 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
|
-
### Org 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 org key authenticates the gateway; the
|
|
27
|
-
end-user identity is attested per call.
|
|
28
|
-
|
|
29
|
-
Mint the key from **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
|
-
)
|
|
41
|
-
# session.mcp.url and session.mcp.headers -> pass to your MCP transport
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
### MCP OAuth client
|
|
45
|
-
|
|
46
|
-
Use this when your application signs in CortexHub users interactively.
|
|
47
|
-
Create the OAuth client from **Account settings -> MCP OAuth clients** and
|
|
48
|
-
copy the `client_id` and `client_secret`.
|
|
49
|
-
|
|
50
|
-
```python
|
|
51
|
-
from cortexhub import Cortexhub
|
|
52
|
-
|
|
53
|
-
cx = Cortexhub(client_id="...", client_secret="...")
|
|
54
|
-
session = cx.session(
|
|
55
|
-
agent="helpdesk-bot",
|
|
56
|
-
mcp_session_id="chat-42", # optional: groups activity per session
|
|
57
|
-
conversation_title="Engineering standup", # optional: context shown in audit
|
|
58
|
-
last_user_message="Create a standup page", # optional: context shown in audit
|
|
59
|
-
)
|
|
60
|
-
```
|
|
61
|
-
|
|
62
|
-
## Environment variables
|
|
63
|
-
|
|
64
|
-
| Variable | Default | Purpose |
|
|
65
|
-
|---|---|---|
|
|
66
|
-
| `CORTEXHUB_URL` | `https://mcp.cortexhub.ai` | MCP gateway base URL |
|
|
67
|
-
| `CORTEXHUB_API_KEY` | - | Org MCP API key (`cxh_mcpk_*`) |
|
|
68
|
-
| `CORTEXHUB_CLIENT_ID` | - | MCP OAuth client id |
|
|
69
|
-
| `CORTEXHUB_CLIENT_SECRET` | - | MCP OAuth client secret |
|
|
70
|
-
|
|
71
|
-
If both `CORTEXHUB_API_KEY` and OAuth credentials are configured, the
|
|
72
|
-
API key wins.
|
|
73
|
-
|
|
74
|
-
## What the SDK returns
|
|
75
|
-
|
|
76
|
-
In both modes, `session.mcp.url` and `session.mcp.headers` are ready to
|
|
77
|
-
wire into the MCP transport of your choice (the official MCP Python SDK,
|
|
78
|
-
a custom HTTP client, anything that accepts URL + headers).
|
|
79
|
-
|
|
80
|
-
## License
|
|
81
|
-
|
|
82
|
-
MIT.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|