cortexhub 1.1.0__tar.gz → 2.0.1__tar.gz

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